public static boolean generateHandler(Registry configSystemRegistry, String resourceFullPath) throws RegistryException, XMLStreamException { RegistryContext registryContext = configSystemRegistry.getRegistryContext(); if (registryContext == null) { return false; } Resource resource = configSystemRegistry.get(resourceFullPath); if (resource != null) { String content = null; if (resource.getContent() != null) { content = RegistryUtils.decodeBytes((byte[]) resource.getContent()); } if (content != null) { OMElement handler = AXIOMUtil.stringToOM(content); if (handler != null) { OMElement dummy = OMAbstractFactory.getOMFactory().createOMElement("dummy", null); dummy.addChild(handler); try { configSystemRegistry.beginTransaction(); boolean status = RegistryConfigurationProcessor.updateHandler( dummy, configSystemRegistry.getRegistryContext(), HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE); configSystemRegistry.commitTransaction(); return status; } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw new RegistryException("Unable to add handler", e); } } } } return false; }
public static boolean addHandler(Registry configSystemRegistry, String payload) throws RegistryException, XMLStreamException { String name; OMElement element = AXIOMUtil.stringToOM(payload); if (element != null) { name = element.getAttributeValue(new QName("class")); } else return false; if (isHandlerNameInUse(name)) throw new RegistryException("The added handler name is already in use!"); String path = getContextRoot() + name; Resource resource; if (!handlerExists(configSystemRegistry, name)) { resource = new ResourceImpl(); } else { throw new RegistryException("The added handler name is already in use!"); } resource.setContent(payload); try { configSystemRegistry.beginTransaction(); configSystemRegistry.put(path, resource); generateHandler(configSystemRegistry, path); configSystemRegistry.commitTransaction(); } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw new RegistryException("Unable to generate handler", e); } return true; }
/** Return a list of all tests of the given type, according to the current filters */ public List<Resource> findTestsOfType(Resource testType) { ArrayList<Resource> result = new ArrayList<>(); StmtIterator si = testDefinitions.listStatements(null, RDF.type, testType); while (si.hasNext()) { Resource test = si.nextStatement().getSubject(); boolean accept = true; // Check test status Literal status = (Literal) test.getProperty(RDFTest.status).getObject(); if (approvedOnly) { accept = status.getString().equals(STATUS_FLAGS[0]); } else { accept = false; for (String STATUS_FLAG : STATUS_FLAGS) { if (status.getString().equals(STATUS_FLAG)) { accept = true; break; } } } // Check for blocked tests for (String BLOCKED_TEST : BLOCKED_TESTS) { if (BLOCKED_TEST.equals(test.toString())) { accept = false; } } // End of filter tests if (accept) { result.add(test); } } return result; }
public static void testEnum() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test.metatype"); b.setProperty("-metatype", "*"); b.build(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Resource r = b.getJar().getResource("OSGI-INF/metatype/test.metatype.MetatypeTest$Enums.xml"); IO.copy(r.openInputStream(), System.err); Document d = db.parse(r.openInputStream()); assertEquals( "http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement().getNamespaceURI()); Properties p = new Properties(); p.setProperty("r", "requireConfiguration"); p.setProperty("i", "ignoreConfiguration"); p.setProperty("o", "optionalConfiguration"); Enums enums = Configurable.createConfigurable(Enums.class, (Map<Object, Object>) p); assertEquals(Enums.X.requireConfiguration, enums.r()); assertEquals(Enums.X.ignoreConfiguration, enums.i()); assertEquals(Enums.X.optionalConfiguration, enums.o()); }
private static void main2(String[] args) { Config.cmdline(args); try { javabughack(); } catch (InterruptedException e) { return; } setupres(); MainFrame f = new MainFrame(null); if (Utils.getprefb("fullscreen", false)) f.setfs(); f.mt.start(); try { f.mt.join(); } catch (InterruptedException e) { f.g.interrupt(); return; } dumplist(Resource.remote().loadwaited(), Config.loadwaited); dumplist(Resource.remote().cached(), Config.allused); if (ResCache.global != null) { try { Writer w = new OutputStreamWriter(ResCache.global.store("tmp/allused"), "UTF-8"); try { Resource.dumplist(Resource.remote().used(), w); } finally { w.close(); } } catch (IOException e) { } } System.exit(0); }
public static String RenderTemplatePage(Bindings b, String templateName) throws IOException { MediaType mt = MediaType.TEXT_HTML; Resource config = model.createResource("eh:/root"); Mode prefixMode = Mode.PreferPrefixes; ShortnameService sns = new StandardShortnameService(); List<Resource> noResults = CollectionUtils.list(root.inModel(model)); Graph resultGraph = graphModel.getGraph(); resultGraph.getPrefixMapping().setNsPrefix("api", API.NS); resultGraph.add(Triple.create(root.asNode(), API.items.asNode(), RDF.nil.asNode())); APIResultSet rs = new APIResultSet(resultGraph, noResults, true, true, "details", View.ALL); VelocityRenderer vr = new VelocityRenderer(mt, null, config, prefixMode, sns); VelocityRendering vx = new VelocityRendering(b, rs, vr); VelocityEngine ve = vx.createVelocityEngine(); VelocityContext vc = vx.createVelocityContext(b); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(bos, "UTF-8"); Template t = ve.getTemplate(templateName); t.merge(vc, w); w.close(); return bos.toString(); }
private void copy(File workspaceDir, InputStream in, Pattern glob, boolean overwrite) throws Exception { Jar jar = new Jar("dot", in); try { for (Entry<String, Resource> e : jar.getResources().entrySet()) { String path = e.getKey(); bnd.trace("path %s", path); if (glob != null && !glob.matcher(path).matches()) continue; Resource r = e.getValue(); File dest = Processor.getFile(workspaceDir, path); if (overwrite || !dest.isFile() || dest.lastModified() < r.lastModified() || r.lastModified() <= 0) { bnd.trace("copy %s to %s", path, dest); File dp = dest.getParentFile(); if (!dp.exists() && !dp.mkdirs()) { throw new IOException("Could not create directory " + dp); } IO.copy(r.openInputStream(), dest); } } } finally { jar.close(); } }
/** * Invoke a script from the command line. * * @param scriptResource the script resource of path * @param scriptArgs an array of command line arguments * @return the return value * @throws IOException an I/O related error occurred * @throws JavaScriptException the script threw an error during compilation or execution */ public Object runScript(Object scriptResource, String... scriptArgs) throws IOException, JavaScriptException { Resource resource; if (scriptResource instanceof Resource) { resource = (Resource) scriptResource; } else if (scriptResource instanceof String) { resource = findResource((String) scriptResource, null, null); } else { throw new IOException("Unsupported script resource: " + scriptResource); } if (!resource.exists()) { throw new FileNotFoundException(scriptResource.toString()); } Context cx = contextFactory.enterContext(); try { Object retval; Map<Trackable, ReloadableScript> scripts = getScriptCache(cx); commandLineArgs = Arrays.asList(scriptArgs); ReloadableScript script = new ReloadableScript(resource, this); scripts.put(resource, script); mainScope = new ModuleScope(resource.getModuleName(), resource, globalScope, mainWorker); retval = mainWorker.evaluateScript(cx, script, mainScope); mainScope.updateExports(); return retval instanceof Wrapper ? ((Wrapper) retval).unwrap() : retval; } finally { Context.exit(); } }
/** * Search for a resource in a local path, or the main repository path. * * @param path the resource name * @param loaders optional list of module loaders * @param localRoot a repository to look first * @return the resource * @throws IOException if an I/O error occurred */ public Resource findResource(String path, ModuleLoader[] loaders, Repository localRoot) throws IOException { // Note: as an extension to the CommonJS modules API // we allow absolute module paths for resources File file = new File(path); if (file.isAbsolute()) { Resource res; outer: if (loaders != null) { // loaders must contain at least one loader assert loaders.length > 0 && loaders[0] != null; for (ModuleLoader loader : loaders) { res = new FileResource(path + loader.getExtension()); if (res.exists()) { break outer; } } res = new FileResource(path + loaders[0].getExtension()); } else { res = new FileResource(file); } res.setAbsolute(true); return res; } else if (localRoot != null && (path.startsWith("./") || path.startsWith("../"))) { String newpath = localRoot.getRelativePath() + path; return findResource(newpath, loaders, null); } else { return config.getResource(normalizePath(path), loaders); } }
public static String getHandlerConfiguration(Registry configSystemRegistry, String name) throws RegistryException, XMLStreamException { String path = getContextRoot() + name; Resource resource; if (handlerExists(configSystemRegistry, name)) { resource = configSystemRegistry.get(path); return RegistryUtils.decodeBytes((byte[]) resource.getContent()); } return null; }
public Folder getFolder(String path) throws IOException, com.ettrema.httpclient.HttpException, NotAuthorizedException, BadRequestException { Resource res = find(path); if (res instanceof Folder) { return (Folder) res; } else { throw new RuntimeException("Not a folder: " + res.href()); } }
/** * Example the conclusions graph for introduction of restrictions which require a comprehension * rewrite and declare new (anon) classes for those restrictions. */ public void comprehensionAxioms(Model premises, Model conclusions) { // Comprehend all restriction declarations and note them in a map Map<Resource, Resource> comprehension = new HashMap<>(); StmtIterator ri = conclusions.listStatements(null, RDF.type, OWL.Restriction); while (ri.hasNext()) { Resource restriction = ri.nextStatement().getSubject(); StmtIterator pi = restriction.listProperties(OWL.onProperty); while (pi.hasNext()) { Resource prop = (Resource) pi.nextStatement().getObject(); StmtIterator vi = restriction.listProperties(); while (vi.hasNext()) { Statement rs = vi.nextStatement(); if (!rs.getPredicate().equals(OWL.onProperty)) { // Have a restriction on(prop) of type rs in the conclusions // So assert a premise that such a restriction could exisit Resource comp = premises .createResource() .addProperty(RDF.type, OWL.Restriction) .addProperty(OWL.onProperty, prop) .addProperty(rs.getPredicate(), rs.getObject()); comprehension.put(restriction, comp); } } } } // Comprehend any intersectionOf lists. Introduce anon class which has the form // of the intersection expression. // Rewrite queries of the form (X intersectionOf Y) to the form // (X equivalentClass ?CC) (?CC intersectionOf Y) StmtIterator ii = conclusions.listStatements(null, OWL.intersectionOf, (RDFNode) null); List<Statement> intersections = new ArrayList<>(); while (ii.hasNext()) { intersections.add(ii.nextStatement()); } for (Statement is : intersections) { // Declare in the premises that such an intersection exists Resource comp = premises .createResource() .addProperty(RDF.type, OWL.Class) .addProperty( OWL.intersectionOf, mapList(premises, (Resource) is.getObject(), comprehension)); // Rewrite the conclusions to be a test for equivalence between the class being // queried and the comprehended interesection conclusions.remove(is); conclusions.add(is.getSubject(), OWL.equivalentClass, comp); } // Comprehend any oneOf lists StmtIterator io = conclusions.listStatements(null, OWL.oneOf, (RDFNode) null); while (io.hasNext()) { Statement s = io.nextStatement(); Resource comp = premises.createResource().addProperty(OWL.oneOf, s.getObject()); } }
/** Run a single test of any sort, return true if the test succeeds. */ public boolean doRunTest(Resource test) throws IOException { if (test.hasProperty(RDF.type, OWLTest.PositiveEntailmentTest) || test.hasProperty(RDF.type, OWLTest.NegativeEntailmentTest) || test.hasProperty(RDF.type, OWLTest.OWLforOWLTest) || test.hasProperty(RDF.type, OWLTest.ImportEntailmentTest) || test.hasProperty(RDF.type, OWLTest.TrueTest)) { // Entailment tests boolean processImports = test.hasProperty(RDF.type, OWLTest.ImportEntailmentTest); Model premises = getDoc(test, RDFTest.premiseDocument, processImports); Model conclusions = getDoc(test, RDFTest.conclusionDocument); comprehensionAxioms(premises, conclusions); long t1 = System.currentTimeMillis(); InfGraph graph = reasoner.bind(premises.getGraph()); if (printProfile) { ((FBRuleInfGraph) graph).resetLPProfile(true); } Model result = ModelFactory.createModelForGraph(graph); boolean correct = WGReasonerTester.testConclusions(conclusions.getGraph(), result.getGraph()); long t2 = System.currentTimeMillis(); lastTestDuration = t2 - t1; if (printProfile) { ((FBRuleInfGraph) graph).printLPProfile(); } if (test.hasProperty(RDF.type, OWLTest.NegativeEntailmentTest)) { correct = !correct; } return correct; } else if (test.hasProperty(RDF.type, OWLTest.InconsistencyTest)) { // System.out.println("Starting: " + test); Model input = getDoc(test, RDFTest.inputDocument); long t1 = System.currentTimeMillis(); InfGraph graph = reasoner.bind(input.getGraph()); boolean correct = !graph.validate().isValid(); long t2 = System.currentTimeMillis(); lastTestDuration = t2 - t1; return correct; } else if (test.hasProperty(RDF.type, OWLTest.ConsistencyTest)) { // Not used normally becase we are not complete enough to prove consistency // System.out.println("Starting: " + test); Model input = getDoc(test, RDFTest.inputDocument); long t1 = System.currentTimeMillis(); InfGraph graph = reasoner.bind(input.getGraph()); boolean correct = graph.validate().isValid(); long t2 = System.currentTimeMillis(); lastTestDuration = t2 - t1; return correct; } else { for (StmtIterator i = test.listProperties(RDF.type); i.hasNext(); ) { System.out.println("Test type = " + i.nextStatement().getObject()); } throw new ReasonerException("Unknown test type"); } }
@Override public void write(final OutputStream out) throws IOException, Exception { OutputStream unclosable = new FilterOutputStream(out) { @Override public void close() { // Ignore } }; for (Resource r : resources) { r.write(unclosable); unclosable.flush(); } }
/** Initialize the result model. */ public void initResults() { testResults = ModelFactory.createDefaultModel(); jena2 = testResults.createResource(BASE_RESULTS_URI + "#jena2"); jena2.addProperty( RDFS.comment, testResults.createLiteral( "<a xmlns=\"http://www.w3.org/1999/xhtml\" href=\"http://jena.sourceforce.net/\">Jena2</a> includes a rule-based inference engine for RDF processing, " + "supporting both forward and backward chaining rules. Its OWL rule set is designed to provide sound " + "but not complete instance resasoning for that fragment of OWL/Full limited to the OWL/lite vocabulary. In" + "particular it does not support unionOf/complementOf.", true)); jena2.addProperty(RDFS.label, "Jena2"); testResults.setNsPrefix("results", OWLResults.NS); }
@Test public void testSelectToWurcsSparql() throws SparqlException, UnsupportedEncodingException { GlycoSequenceToWurcsSelectSparql s = new GlycoSequenceToWurcsSelectSparql("glycoct"); SparqlEntity se = new SparqlEntity(); se.setValue( GlycoSequenceToWurcsSelectSparql.FromSequence, "RES\n1b:a-dgal-HEX-1:5\n2s:n-acetyl\n3b:b-dgal-HEX-1:5\n4b:b-dglc-HEX-1:5\n5s:n-acetyl\n6b:b-dgal-HEX-1:5\n7b:a-lgal-HEX-1:5|6:d\n8b:b-dglc-HEX-1:5\n9s:n-acetyl\n10b:b-dglc-HEX-1:5\n11s:n-acetyl\n12b:b-dgal-HEX-1:5\n13b:a-lgal-HEX-1:5|6:d\nLIN\n1:1d(2+1)2n\n2:1o(3+1)3d\n3:3o(3+1)4d\n4:4d(2+1)5n\n5:4o(4+1)6d\n6:6o(2+1)7d\n7:3o(6+1)8d\n8:8d(2+1)9n\n9:1o(6+1)10d\n10:10d(2+1)11n\n11:10o(4+1)12d\n12:12o(2+1)13d" .replaceAll("\n", "\\\\n")); s.setSparqlEntity(se); logger.debug(s.getSparql()); Query query = QueryFactory.create(s.getSparql().replaceAll("null", "").replace("?Sequence", "")); // QueryExecution qe = // QueryExecutionFactory.sparqlService("http://localhost:3030/glycobase/query",query); QueryExecution qe = QueryExecutionFactory.sparqlService("http://test.ts.glytoucan.org/sparql", query); ResultSet rs = qe.execSelect(); List<SparqlEntity> results = new ArrayList<SparqlEntity>(); while (rs.hasNext()) { QuerySolution row = rs.next(); Iterator<String> columns = row.varNames(); SparqlEntity se2 = new SparqlEntity(); while (columns.hasNext()) { String column = columns.next(); RDFNode cell = row.get(column); if (cell.isResource()) { Resource resource = cell.asResource(); // do something maybe with the OntModel??? if (resource.isLiteral()) se.setValue(column, resource.asLiteral().getString()); else se.setValue(column, resource.toString()); } else if (cell.isLiteral()) { se.setValue(column, cell.asLiteral().getString()); } else if (cell.isAnon()) { se.setValue(column, "anon"); } else { se.setValue(column, cell.toString()); } } results.add(se); } for (SparqlEntity entity : results) { System.out.println("results: " + entity.getValue("PrimaryId")); } }
public static void testADWithInheritance() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test.metatype"); b.setProperty("-metatype", "*"); b.setProperty("-metatype-inherit", "true"); b.build(); Resource r = b.getJar() .getResource( "OSGI-INF/metatype/test.metatype.MetatypeTest$TestADWithInheritanceChild.xml"); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); System.err.println(b.getJar().getResources().keySet()); assertNotNull(r); IO.copy(r.openInputStream(), System.err); Document d = db.parse(r.openInputStream()); assertAD( d, "fromChild", "From child", "fromChild", null, null, null, 0, "String", null, null, null); assertAD( d, "fromSuperOne", "From super one", "fromSuperOne", null, null, null, 0, "String", null, null, null); assertAD( d, "fromSuperTwo", "From super two", "fromSuperTwo", null, null, null, 0, "String", null, null, null); }
private void evaluateBootstrapScripts(Context cx) throws IOException { List<String> bootstrapScripts = config.getBootstrapScripts(); if (bootstrapScripts != null) { for (String script : bootstrapScripts) { Resource resource = new FileResource(script); // not found, attempt to resolve the file relative to ringo home if (!resource.exists()) { resource = getRingoHome().getResource(script); } if (resource == null || !resource.exists()) { throw new FileNotFoundException("Bootstrap script " + script + " not found"); } mainWorker.evaluateScript(cx, new ReloadableScript(resource, this), globalScope); } } }
/** * Resolves a module id to a package resource. If module id consists of just one term and resolves * to a package directory, the main module of the package is returned. If the module id consists * of several terms and the first term resolves to a package directory, the remaining part of the * module id is resolved against the "lib" directory of the package. * * @link http://nodejs.org/docs/v0.4.4/api/modules.html#folders_as_Modules * @param moduleName the name of the package to load * @param localPath the path of the resource issuing this call * @return the location of the package's main module * @throws IOException an unrecoverable I/O exception occurred while reading the package */ protected Resource loadPackage(String moduleName, Repository localPath) throws IOException { int slash = 0; String packageName, remainingName; do { slash = moduleName.indexOf('/', slash + 1); if (slash == -1) { packageName = moduleName; remainingName = null; } else { packageName = moduleName.substring(0, slash); if (".".equals(packageName) || "..".equals(packageName)) continue; remainingName = moduleName.substring(slash + 1); } Resource json = findResource(packageName + "/package.json", null, localPath); if (json != null && json.exists()) { Scriptable obj = parseJsonResource(json); Repository parent = json.getParentRepository(); String moduleId; Resource res; if (remainingName == null) { // get the main module of this package moduleId = getStringProperty(obj, "main", null); if (moduleId != null) { // optimize for the common case where main module // property links to the exact file name res = parent.getResource(moduleId); if (res != null && res.exists()) return res; } } else { // map remaining name to libs directory String lib = "lib"; Object dirs = ScriptableObject.getProperty(obj, "directories"); if (dirs instanceof Scriptable) { lib = getStringProperty((Scriptable) dirs, "lib", "lib"); } moduleId = lib + "/" + remainingName; } if (moduleId != null) { for (ModuleLoader loader : loaders) { res = parent.getResource(moduleId + loader.getExtension()); if (res != null && res.exists()) return res; } if (remainingName != null) { res = parent.getResource(moduleId); if (res != null && res.exists()) return res; } } } } while (slash != -1); return findResource(moduleName + "/index", loaders, localPath); }
public static boolean equalResources(Resource t, Resource that) throws ModelException { return t.getURI().equals(that.getURI()); /* boolean b = false; String tns = t.getNamespace(); String tn = t.getLocalName(); String thatns = that.getNamespace(); String thatn = that.getLocalName(); // System.err.print("Comparing " + t + " vs " + that + ": "); if(thatns == null) { if(tns == null) { // (null, null) // System.err.println("true"); return thatn.equals(tn); } else // (null, not null) maybe "that" did not detect names b = thatn.equals(t.getURI()); } else { if(tns != null) // (not null, not null) b = thatn.equals(tn) && thatns.equals(tns); else // (not null, null) maybe "this" did not detect names b = that.getURI().equals(tn); } if(b) return true; // else we need to check whether different namespace splitting is used if((tns != null ? tns.length() : 0) + (tn != null ? tn.length() : 0) == (thatns != null ? thatns.length() : 0) + (thatn != null ? thatn.length() : 0)) { b = t.getURI().equals(that.getURI()); } // System.err.println("" + b); return b; */ }
/** Load the premises or conclusions for the test. */ public Model getDoc(Resource test, Property docType) throws IOException { Model result = ModelFactory.createDefaultModel(); StmtIterator si = test.listProperties(docType); while (si.hasNext()) { String fname = si.nextStatement().getObject().toString() + ".rdf"; loadFile(fname, result); } return result; }
public ModuleLoader getModuleLoader(Resource resource) { String name = resource.getName(); for (ModuleLoader loader : loaders) { if (name.endsWith(loader.getExtension())) { return loader; } } return loaders[0]; }
static Visual[] getTrueColor16(Client c) { Vector vec = new Vector(); vec.addElement(new Visual(Resource.fakeClientId(c), 4, 6, 64, 0xf800, 0x7e0, 0x1f)); Visual[] v = new Visual[vec.size()]; for (int i = 0; i < vec.size(); i++) { v[i] = (Visual) vec.elementAt(i); } vec.removeAllElements(); return v; }
static Visual[] getPseudoColor8(Client c) { Vector vec = new Vector(); vec.addElement(new Visual(Resource.fakeClientId(c), 3, 6, 256, 0, 0, 0)); Visual[] v = new Visual[vec.size()]; for (int i = 0; i < vec.size(); i++) { v[i] = (Visual) vec.elementAt(i); } vec.removeAllElements(); return v; }
public static void testSimple() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test.metatype"); b.setProperty("-metatype", "*"); b.build(); Resource r = b.getJar().getResource("OSGI-INF/metatype/test.metatype.MetatypeTest$TestSimple.xml"); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); System.err.println(b.getJar().getResources().keySet()); assertNotNull(r); IO.copy(r.openInputStream(), System.err); Document d = db.parse(r.openInputStream()); assertEquals("TestSimple", xpath.evaluate("//OCD/@name", d)); assertEquals("simple", xpath.evaluate("//OCD/@description", d)); assertEquals("test.metatype.MetatypeTest$TestSimple", xpath.evaluate("//OCD/@id", d)); assertEquals("test.metatype.MetatypeTest$TestSimple", xpath.evaluate("//Designate/@pid", d)); assertEquals("test.metatype.MetatypeTest$TestSimple", xpath.evaluate("//Object/@ocdref", d)); assertEquals("simple", xpath.evaluate("//OCD/AD[@id='simple']/@id", d)); assertEquals("Simple", xpath.evaluate("//OCD/AD[@id='simple']/@name", d)); assertEquals("String", xpath.evaluate("//OCD/AD[@id='simple']/@type", d)); assertEquals("true", xpath.evaluate("//OCD/AD[@id='notSoSimple']/@required", d)); /** * https://github.com/bndtools/bnd/issues/281 * * <p>Using the Bnd annotations library (1.52.3), the generated metatype file will have * required='false' for all fields annotated with @Meta.AD(). When this annotation is omitted, * or when the required property is explicitly set, the field is correctly marked as required. * Taking a glance at the code, the bug appears to be due to aQute.bnd.osgi.Annotation using * aQute.bnd.annotation.metatype.Configurable internally for bridging Bnd-annotations to * Java-annotations. This configurable only obtains the values from the Bnd-annotation, omitting * the defaults defined in the Java annotation. The workaround is to explicitly mention the * required property on each field annotated with @Meta.AD. */ assertEquals("true", xpath.evaluate("//OCD/AD[@id='simple']/@required", d)); assertEquals( Integer.MAX_VALUE + "", xpath.evaluate("//OCD/AD[@id='notSoSimple']/@cardinality", d)); }
private Scriptable parseJsonResource(Resource resource) throws IOException { JsonParser parser = new JsonParser(Context.getCurrentContext(), globalScope); try { Object result = parser.parseValue(resource.getContent()); if (!(result instanceof Scriptable)) { throw new RuntimeException("Expected Object from package.json, got " + result); } return (Scriptable) result; } catch (JsonParser.ParseException px) { throw new RuntimeException(px); } }
private static void addToRegistry(String rootPath, File file, int tenantId) { try { Registry registry = getRegistry(tenantId); // This path is used to store the file resource under registry String fileRegistryPath = REGISTRY_GADGET_STORAGE_PATH + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/"); // Adding the file to the Registry Resource fileResource = registry.newResource(); fileResource.setMediaType("application/vnd.wso2-gadget+xml"); fileResource.setContentStream(new FileInputStream(file)); registry.put(fileRegistryPath, fileResource); } catch (RegistryException e) { log.error(e.getMessage(), e); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } }
/** Run a single test of any sort, performing any appropriate logging and error reporting. */ public void runTest(Resource test) { System.out.println("Running " + test); boolean success = false; boolean fail = false; try { success = doRunTest(test); } catch (Exception e) { fail = true; System.out.print("\nException: " + e); e.printStackTrace(); } testCount++; if (success) { System.out.print((testCount % 40 == 0) ? ".\n" : "."); System.out.flush(); passCount++; } else { System.out.println("\nFAIL: " + test); } Resource resultType = null; if (fail) { resultType = OWLResults.FailingRun; } else { if (test.hasProperty(RDF.type, OWLTest.NegativeEntailmentTest) || test.hasProperty(RDF.type, OWLTest.ConsistencyTest)) { resultType = success ? OWLResults.PassingRun : OWLResults.FailingRun; } else { resultType = success ? OWLResults.PassingRun : OWLResults.IncompleteRun; } } // log to the rdf result format Resource result = testResults .createResource() .addProperty(RDF.type, OWLResults.TestRun) .addProperty(RDF.type, resultType) .addProperty(OWLResults.test, test) .addProperty(OWLResults.system, jena2); }
/** Load the premises or conclusions for the test, optional performing import processing. */ public Model getDoc(Resource test, Property docType, boolean processImports) throws IOException { if (processImports) { Model result = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null); StmtIterator si = test.listProperties(docType); while (si.hasNext()) { String fname = si.nextStatement().getObject().toString() + ".rdf"; loadFile(fname, result); } return result; } else { return getDoc(test, docType); } }
/** * Resolves a type name to a script file within our script directory and returns a Scriptable * evaluated to the file. * * @param moduleName the name of the module to load * @param localPath the path of the resource issuing this call * @return The raw compiled script for the module * @throws JavaScriptException if an error occurred evaluating the script file * @throws IOException if an error occurred reading the script file */ public ReloadableScript getScript(String moduleName, Repository localPath) throws JavaScriptException, IOException { ReloadableScript script; Resource source = findResource(moduleName, loaders, localPath); if (!source.exists()) { source = loadPackage(moduleName, localPath); if (!source.exists()) { source = findResource(moduleName, null, localPath); } } Context cx = Context.getCurrentContext(); Map<Trackable, ReloadableScript> scripts = getScriptCache(cx); if (scripts.containsKey(source)) { script = scripts.get(source); } else { script = new ReloadableScript(source, this); if (source.exists()) { scripts.put(source, script); } } return script; }