public static void main(String[] args) { // create an empty model Model model = ModelFactory.createDefaultModel(); // use the FileManager to find the input file String inputFileName = "src/main/resources/lab-3.ttl"; InputStream in = FileManager.get().open(inputFileName); if (in == null) { throw new IllegalArgumentException("File: " + inputFileName + " not found"); } // read the Turtle file model.read(in, null, "TTL"); // get the inferred mode /* The getDeductionsFunction somehow returns the incorrect answer, so I have to use the deprecated class 'Filter'. */ InfModel infModel = ModelFactory.createRDFSModel(model); ExtendedIterator<Statement> stmts = infModel .listStatements() .filterDrop( new Filter<Statement>() { @Override public boolean accept(Statement o) { return model.contains(o); } }); Model deductionsModel = ModelFactory.createDefaultModel().add(new StmtIteratorImpl(stmts)); // list new RDFS-inferred triples about 'Museion' outputInfo(deductionsModel, "museion"); // list new RDFS-inferred triples about 'Chicken Hut' outputInfo(deductionsModel, "chickenHut"); }
public void ajouterAllActionListener(ActionListener actionListener) { for (int i = 0; i < model.getTableauBijou().length; i++) { for (int j = 0; j < model.getTableauBijou()[i].length; j++) { tableauBijouButton[i][j].addActionListener(actionListener); } } }
// This is the constructor used from runFromShell public PrologBackend(String[] args) throws Exception { // This parses the args and the ABS program producing the AST whose root is model model = parse(args); if (model.hasParserErrors() || model.hasErrors() || model.hasTypeErrors()) printParserErrorAndExit(); initOutStreamEtc(); }
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(); }
public static Resource getSubject(Model r, Resource predicate, RDFNode object) throws ModelException { Model m = r.find(null, predicate, object); if (m == null || m.size() == 0) return null; // if(m.size() > 1) // throw new RuntimeException("Model contains more than one triple"); return ((Statement) m.elements().nextElement()).subject(); }
private static void addFolder(FileSystem fs, Path p, JsonArray succeeded, JsonArray failed) { try { if (fs == null) return; for (FileStatus file : fs.listStatus(p)) { Path pfs = file.getPath(); if (file.isDir()) { addFolder(fs, pfs, succeeded, failed); } else { Key k = Key.make(pfs.toString()); long size = file.getLen(); Value val = null; if (pfs.getName().endsWith(Extensions.JSON)) { JsonParser parser = new JsonParser(); JsonObject json = parser.parse(new InputStreamReader(fs.open(pfs))).getAsJsonObject(); JsonElement v = json.get(Constants.VERSION); if (v == null) throw new InvalidDataException("Missing version"); JsonElement type = json.get(Constants.TYPE); if (type == null) throw new InvalidDataException("Missing type"); Class c = Class.forName(type.getAsString()); Model model = (Model) c.newInstance(); model.fromJson(json); } else if (pfs.getName().endsWith(Extensions.HEX)) { // Hex file? FSDataInputStream s = fs.open(pfs); int sz = (int) Math.min(1L << 20, size); // Read up to the 1st meg byte[] mem = MemoryManager.malloc1(sz); s.readFully(mem); // Convert to a ValueArray (hope it fits in 1Meg!) ValueArray ary = new ValueArray(k, 0).read(new AutoBuffer(mem)); val = new Value(k, ary, Value.HDFS); } else if (size >= 2 * ValueArray.CHUNK_SZ) { val = new Value( k, new ValueArray(k, size), Value.HDFS); // ValueArray byte wrapper over a large file } else { val = new Value(k, (int) size, Value.HDFS); // Plain Value } val.setdsk(); DKV.put(k, val); JsonObject o = new JsonObject(); o.addProperty(Constants.KEY, k.toString()); o.addProperty(Constants.FILE, pfs.toString()); o.addProperty(Constants.VALUE_SIZE, file.getLen()); succeeded.add(o); } } } catch (Exception e) { Log.err(e); JsonObject o = new JsonObject(); o.addProperty(Constants.FILE, p.toString()); o.addProperty(Constants.ERROR, e.getMessage()); failed.add(o); } }
public void coloreUnCoupPossible() { if (model.getCoupsPossibles().size() == 0) { partieEstPerdu(" coup possible a jouer"); } Coup coupPossible = model.getUnCoupPossible(); tableauBijouButton[coupPossible.getCoord1().getX()][coupPossible.getCoord1().getY()] .setBackground(Color.BLACK); }
public static RDFNode getObject(Model r, Resource subject, Resource predicate) throws ModelException { Model m = r.find(subject, predicate, null); if (m == null || m.size() == 0) return null; // if(m.size() > 1) // throw new RuntimeException("Model contains more than one triple"); // FIXME: we do not check whether it is a resource or literal return ((Statement) m.elements().nextElement()).object(); }
// FIXME: use digest instead of size static void getReachable(Resource r, Model m, Model result) throws ModelException { int oldSize = result.size(); Model directlyReachable = m.find(r, null, null); SetOperations.unite(result, directlyReachable); if (result.size() == oldSize) return; for (Enumeration en = directlyReachable.elements(); en.hasMoreElements(); ) { Statement t = (Statement) en.nextElement(); if (t.object() instanceof Resource) getReachable((Resource) t.object(), m, result); } }
/** Collects the triples of a model into an array. */ public static Statement[] getStatementArray(Model m) throws ModelException { Statement[] v = new Statement[m.size()]; int i = 0; for (Enumeration en = m.elements(); en.hasMoreElements(); ) { Statement t = (Statement) en.nextElement(); v[i++] = t; } return v; }
/** 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"); } }
/** * @return a new model in which all occurrences of the old namespace are replaced by the new one. * All replaced resources are summarized in the map if not null. If resourcesToIgnore != null, * ignore resources listed there. */ public static Model replaceNamespace(Model m, String o, String n, Map o2n, Set resourcesToIgnore) throws ModelException { Model res = m.create(); NodeFactory f = m.getNodeFactory(); Enumeration en = m.elements(); while (en.hasMoreElements()) { Statement st = (Statement) en.nextElement(); res.add(replaceNamespace(st, o, n, f, o2n, resourcesToIgnore)); } return res; }
/** returns true if old triples from r were removed */ public static boolean setUniqueObject( Model r, Resource subject, Resource predicate, RDFNode object) throws ModelException { Model old = r.find(subject, predicate, null); SetOperations.subtract(r, old); Statement stmt = get1(old); if (subject == null && stmt != null) subject = stmt.subject(); if (predicate == null && stmt != null) predicate = stmt.predicate(); r.add(r.getNodeFactory().createStatement(subject, predicate, object)); return !old.isEmpty(); }
/** 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); }
public static List getObjects(Model m, Resource subject, Resource predicate) throws ModelException { List result = new ArrayList(); if (m == null || m.size() == 0) return result; for (Enumeration en = m.find(subject, predicate, null).elements(); en.hasMoreElements(); ) { Statement st = (Statement) en.nextElement(); result.add(st.object()); } return result; }
/** tries to determine the file name from getSourceURI */ public static void saveModel(Model m, RDFSerializer s) throws FileNotFoundException, IOException, ModelException, SerializationException { // URI to filename URL url = null; try { url = new URL(m.getSourceURI()); } catch (Exception any) { throw new ModelException("RDFUtil: cannot determine model file name: " + m.getSourceURI()); } if ("file".equals(url.getProtocol())) saveModel(m, url.getFile().replace('/', File.separatorChar), s); else throw new ModelException("RDFUtil: cannot save to non-file model URI: " + m.getSourceURI()); }
public void actualiserTableau() { for (int i = 0; i < tableauBijouButton.length; i++) { for (int j = 0; j < tableauBijouButton[i].length; j++) { tableauBijouButton[i][j].setType(model.getTableauBijou()[i][j]); tableauBijouButton[i][j].setIcon( model.getTextures()[tableauBijouButton[i][j].getTypeBijou().getIndex()]); if (tableauBijouButton[i][j].getBackground() == Color.BLACK) { tableauBijouButton[i][j].setBackground(Color.WHITE); } } // coloreCoupPossible(); } }
/** Removes all triples which have something to do with the given namespace */ public static Model removeNamespace(String ns, Model m) throws ModelException { Model res = m.duplicate(); for (Enumeration en = m.duplicate().elements(); en.hasMoreElements(); ) { Statement t = (Statement) en.nextElement(); if (t.subject().toString().startsWith(ns) || t.predicate().toString().startsWith(ns) || t.object().toString().startsWith(ns)) { // System.err.println("REMOVING TRIPLE: " + t); res.remove(t); } } return res; }
public static Set toSet(Model m) throws ModelException { Set s = new HashSet(); Enumeration en = m.elements(); while (en.hasMoreElements()) s.add(en.nextElement()); return s; }
public void actualiserTries() { int nbTries = model.getTries(); if (nbTries <= 0) { partieEstPerdu(" trie (essai)"); } tries.setText(String.valueOf(nbTries)); }
public boolean gestionHighScore() { String chemin = "HighScore.txt"; Vector<Integer> highScores = getHighScore(chemin); if (highScores.size() != 0 && model.getScore() > highScores.get(highScores.size() - 1) || highScores.size() < 5) { triTableau(highScores, model.getScore()); ecrireFichier(chemin, highScores); return true; } return false; }
public ArrayList<ArrayList<Coord>> coloreLigneCombo() { ArrayList<ArrayList<Coord>> lignesCombo; lignesCombo = model.getLignesCombo(); if (lignesCombo.size() != 0) { /* for (int i = 0; i < lignesCombo.size(); i++) { for (int j = 0; j < lignesCombo.get(i).size(); j++) { //tableauBijouButton[lignesCombo.get(i).get(j).getX()][lignesCombo.get(i).get(j).getY()].setBackground(Color.CYAN); tableauBijouButton[lignesCombo.get(i).get(j).getX()][lignesCombo.get(i).get(j).getY()].repaint(); } }*/ /* long time1 = java.lang.System.currentTimeMillis(); long time2; do { time2 = java.lang.System.currentTimeMillis(); }while(time1 > time2 + 1000);*/ for (int i = 0; i < lignesCombo.size(); i++) { for (int j = 0; j < lignesCombo.get(i).size(); j++) { tableauBijouButton[lignesCombo.get(i).get(j).getX()][lignesCombo.get(i).get(j).getY()] .setBackground(Color.WHITE); } } actualiserTableau(); } return lignesCombo; }
/** 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; }
/** * Writes a table to a XML-file * * @param t - Output Model * @param destination - File Destination */ public static void writeXML(Model t, String destination) { try { // Create the XML document builder, and document that will be used DocumentBuilderFactory xmlBuilder = DocumentBuilderFactory.newInstance(); DocumentBuilder Builder = xmlBuilder.newDocumentBuilder(); Document xmldoc = Builder.newDocument(); // create Document node, and get it into the file Element Documentnode = xmldoc.createElement("SPREADSHEET"); xmldoc.appendChild(Documentnode); // create element nodes, and their attributes (Cells, and row/column // data) and their content for (int row = 1; row < t.getRows(); row++) { for (int col = 1; col < t.getCols(col); col++) { Element cell = xmldoc.createElement("CELL"); // set attributes cell.setAttribute("column", Integer.toString(col)); cell.setAttribute("row", Integer.toString(col)); // set content cell.appendChild(xmldoc.createTextNode((String) t.getContent(row, col))); // append node to document node Documentnode.appendChild(cell); } } // Creating a datastream for the DOM tree TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); // Indentation to make the XML file look better transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // remove the java version transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); DOMSource stream = new DOMSource(xmldoc); StreamResult target = new StreamResult(new File(destination)); // write the file transformer.transform(stream, target); } catch (ParserConfigurationException e) { System.out.println("Can't create the XML document builder"); } catch (TransformerConfigurationException e) { System.out.println("Can't create transformer"); } catch (TransformerException e) { System.out.println("Can't write to file"); } }
public static void collectNamespaces(Model m, Collection target) throws ModelException { for (Enumeration en = m.elements(); en.hasMoreElements(); ) { Statement st = (Statement) en.nextElement(); collectNamespaces(st, target); } }
/** Prints the triples of a model to the given PrintStream. */ public static void printStatements(Model m, PrintStream ps) throws ModelException { for (Enumeration en = m.elements(); en.hasMoreElements(); ) { Statement t = (Statement) en.nextElement(); ps.println(t); // "triple(\""+t.subject()+"\",\""+t.predicate()+"\",\""+t.object()+"\")."); } }
public static void collectLiterals(Model m, Collection target) throws ModelException { for (Enumeration en = m.elements(); en.hasMoreElements(); ) { Statement st = (Statement) en.nextElement(); if (st.object() instanceof Literal) target.add(st.object()); } }
public static void collectPredicates(Model m, Collection target) throws ModelException { for (Enumeration en = m.elements(); en.hasMoreElements(); ) { Statement st = (Statement) en.nextElement(); target.add(st.predicate()); } }
/** * @return a new model in which all occurrences of the old resources are replaced by the new ones. * Returns number replacements done. */ public static int replaceResources(Model src, Model dest, Map o2n) throws ModelException { NodeFactory f = src.getNodeFactory(); Enumeration en = src.elements(); int replaced = 0; while (en.hasMoreElements()) { Statement st = (Statement) en.nextElement(); Statement st_n = replaceResources(st, f, o2n); dest.add(st_n); if (st_n != st) // yes, pointer comparison replaced++; } return replaced; }
/** * Method that reads a XML-file, and returns a Model that contains the information * * @param file * @return * @return */ public static Model readXML(String file) { // initialize table to be filled with content of XML file Model t = new Model(); try { // Create file to be parsed by document parser File xmlfile = new File(file); // create parser DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // parse the file Document parsedfile = parser.parse(xmlfile); // normalize the parsed file (make it more user-friendly) parsedfile.getDocumentElement().normalize(); NodeList cells = parsedfile.getElementsByTagName("CELL"); for (int i = 0; i < cells.getLength(); i++) { // Get cell at list index i Node currentcell = cells.item(i); // read the elements "location" attributes row/column if (Node.ELEMENT_NODE == currentcell.getNodeType()) { Element cellinfo = (Element) currentcell; // get the row number from node attribute int row = Integer.parseInt(cellinfo.getAttribute("row")) - 1; // get the column number from the node attribute int col = Integer.parseInt(cellinfo.getAttribute("column")) - 1; // get content from node String content = cellinfo.getTextContent(); if (content != null) { content = content.replace("\n", ""); } // Make the content an Integer (if it is a number), easier // for // using it later on // put content in table, with row/column inserted as x/y t.setContent(row, col, (String) content); } } } catch (ParserConfigurationException e) { System.out.println("Fileparser could not be made"); } catch (IOException f) { System.out.println("File could not be parsed, did you enter the correct file name?"); } catch (SAXException g) { System.out.println("Something went wrong in parsing the file"); } return t; }