Exemple #1
0
  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();
  }
Exemple #2
0
  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();
  }
Exemple #3
0
  /** 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;
  }
Exemple #4
0
  // 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);
    }
  }
Exemple #5
0
  /** 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();
  }
Exemple #6
0
  /**
   * @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;
  }
Exemple #7
0
  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;
  }
Exemple #8
0
  /** 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;
  }
Exemple #9
0
  /** 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());
  }
Exemple #10
0
  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;
  }
Exemple #11
0
  /**
   * 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");
    }
  }
Exemple #12
0
  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);
    }
  }
Exemple #13
0
  /**
   * @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;
  }
Exemple #14
0
  /** 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()+"\").");
    }
  }
Exemple #15
0
  /**
   * 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;
  }
Exemple #16
0
  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());
    }
  }
Exemple #17
0
  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());
    }
  }
Exemple #18
0
  /** Fills <tt>m</tt> with statements from <tt>s</tt> and returns it. */
  public static Model toModel(Set s, Model m) throws ModelException {

    Iterator it = s.iterator();
    while (it.hasNext()) {
      Object o = it.next();
      if (o instanceof Statement) m.add((Statement) o);
    }
    return m;
  }
Exemple #19
0
  public static Hashtable getNodes(Model m) throws ModelException {

    Hashtable t = new Hashtable();
    for (Enumeration en = m.elements(); en.hasMoreElements(); ) {
      Statement s = (Statement) en.nextElement();
      t.put(s.subject(), s.subject());
      t.put(s.object(), s.object());
    }
    return t;
  }
Exemple #20
0
  /** Collects the triples of a model in a vector. */
  public static Vector getStatementVector(Model m) throws ModelException {

    Vector v = new Vector();
    for (Enumeration en = m.elements(); en.hasMoreElements(); ) {

      Statement t = (Statement) en.nextElement();
      v.addElement(t);
    }
    return v;
  }
Exemple #21
0
  public static void collectResources(Model m, Collection target) throws ModelException {

    for (Enumeration en = m.elements(); en.hasMoreElements(); ) {

      Statement st = (Statement) en.nextElement();
      if (!(st.object() instanceof Literal) && !(st.object() instanceof Statement))
        target.add(st.object());
      target.add(st.subject());
      target.add(st.predicate());
    }
  }
Exemple #22
0
  /**
   * @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 m, Map o2n) throws ModelException {

    NodeFactory f = m.getNodeFactory();
    Enumeration en = m.elements();

    Model toRemove = m.create();
    Model toAdd = m.create();

    while (en.hasMoreElements()) {

      Statement st = (Statement) en.nextElement();
      Statement st_n = replaceResources(st, f, o2n);

      if (st_n != st) { // yes, pointer comparison
        toAdd.add(st_n);
        toRemove.add(st);
      }
    }

    SetOperations.subtract(m, toRemove);
    SetOperations.unite(m, toAdd);

    return toAdd.size();
  }
Exemple #23
0
  public static void parse(String fileNameOrURL, RDFParser parser, Model model)
      throws IOException, SAXException, MalformedURLException, ModelException {

    URL url = new URL(normalizeURI(fileNameOrURL));

    // maybe this model is loaded as schema...
    //    Model model = factory.registry().get(url.toString());
    //    if(model != null)
    //      return model;

    // Prepare input source
    model.setSourceURI(url.toString());
    InputStream in = url.openStream();
    InputSource source = new InputSource(in);
    source.setSystemId(url.toString());

    parser.parse(source, new ModelConsumer(model));
    in.close();
  }
Exemple #24
0
  public static void main(String args[]) {

    if (args.length < 3) {
      System.err.println("Usage: Generate model-file ( -s length | -c count length )");
      System.exit(1);
    }

    try {
      SAXParserFactory saxFactory = SAXParserFactory.newInstance();
      saxFactory.setNamespaceAware(true);
      SAXParser saxParser = saxFactory.newSAXParser();
      XMLReader xmlReader = saxParser.getXMLReader();

      XMLModelReader modelReader = new XMLModelReader(xmlReader);
      FileReader modelInput = new FileReader(args[0]);
      InputSource source = new InputSource(modelInput);

      Model model = modelReader.load(source);

      modelInput.close();

      model.check();

      if (args[1].equals("-s")) {
        int[][] result = model.generateSequence(Integer.parseInt(args[2]));

        List lexicon = model.getLexicon();
        for (int i = 0; i < result[0].length; i++) {
          System.out.print((Character) lexicon.get(result[0][i]));
        }
        System.out.println();
        int numberOfStates = model.getNumberOfStates();
        if (numberOfStates > 9) {
          for (int i = 0; i < result[1].length; i++) {
            System.out.print(result[1][i]);
            System.out.print(',');
          }
        } else {
          for (int i = 0; i < result[1].length; i++) {
            System.out.print(result[1][i]);
          }
        }
        System.out.println();
        for (int i = 1; i < numberOfStates; i++) {
          System.out.println(i + " = " + model.getStateName(i));
        }
      } else if (args[1].equals("-c")) {
        List lexicon = model.getLexicon();
        int count = Integer.parseInt(args[2]);
        int length = Integer.parseInt(args[3]);
        ListOfSequences uniqueSeqs = new ListOfSequences();
        for (int i = 0; i < count; i++) {
          int[][] result = model.generateSequence(length);
          uniqueSeqs.addSequence(result[0]);
        }
        Iterator seqs = uniqueSeqs.iterator();
        while (seqs.hasNext()) {
          SequenceCount seq = (SequenceCount) seqs.next();
          int[] key = seq.getSequence();
          for (int i = 0; i < key.length; i++) {
            System.out.print((Character) lexicon.get(key[i]));
          }
          System.out.print(',');
          System.out.println(seq.getCount());
        }
      }

    } catch (java.io.IOException ex) {
      ex.printStackTrace();
    } catch (org.xml.sax.SAXException ex) {
      System.err.println(ex.getMessage());
    } catch (javax.xml.parsers.ParserConfigurationException ex) {
      ex.printStackTrace();
    }
  }
Exemple #25
0
  /** Creates a new unique unnamed resource. */
  public static Resource noname(Model m) throws ModelException {

    return m.getNodeFactory().createUniqueResource();
  }
Exemple #26
0
  public static void add(Model m, Resource subject, Resource predicate, RDFNode object)
      throws ModelException {

    m.add(m.getNodeFactory().createStatement(subject, predicate, object));
  }
Exemple #27
0
 /** Returns the first triple of the model */
 public static Statement get1(Model m) throws ModelException {
   if (m == null || m.isEmpty()) return null;
   //    if(m.size() > 1)
   //      throw new RuntimeException("Model contains more than one triple");
   return (Statement) m.elements().nextElement();
 }
Exemple #28
0
 public static boolean isInstanceOf(Model r, Resource i, Resource cls) throws ModelException {
   return !r.find(i, RDF.type, cls).isEmpty();
 }
Exemple #29
0
  /**
   * returns a subgraph of "m" containing "r" and all nodes reachable from "r" via directed edges.
   * These edges are also included in the resulting model.
   */
  public static Model getReachable(Resource r, Model m) throws ModelException {

    Model result = m.create();
    getReachable(r, m, result);
    return result;
  }