/* (non-Javadoc)
   * @see org.integratedmodelling.thinklab.IKnowledgeBase#getInstanceFromURI(java.lang.String, org.integratedmodelling.thinklab.interfaces.ISession)
   */
  public IInstance getInstanceFromURI(String uri, ISession session) throws ThinklabException {

    IInstance ret = null;

    String[] ss = uri.split("#");
    if (ss.length != 2) return ret;

    IOntology o = null;

    String csp = getConceptSpaceFromURI(ss[0] + "#");

    if (csp != null) {
      o = knowledgeRepository.retrieveOntology(csp);
      if (o != null) {

        ret = o.getInstance(ss[1]);
        if (ret != null) {
          ret = session.createObject(ret);
        }
      }
    }

    /* not an ontology, so must be a kbox */
    if (ret == null) {

      IKBox kbox = session.retrieveKBox(ss[0]);

      if (kbox != null) {
        ret = kbox.getObjectFromID(ss[1], session);
      }
    }
    return ret;
  }
  @Override
  public IValue execute(Command command, ISession session) throws ThinklabException {

    String concept = command.getArgumentAsString("concept");

    IKBox kbox = KBoxManager.get();
    if (command.hasOption("kbox"))
      kbox = KBoxManager.get().requireGlobalKBox(command.getOptionAsString("kbox"));

    ArrayList<Topology> extents = new ArrayList<Topology>();

    IContext context = null;
    if (!command.getArgumentAsString("context").equals("_NONE_")) {
      context = ModelFactory.get().requireContext(command.getArgumentAsString("context"));
    }

    Constraint c = new Constraint(CoreScience.Observation());

    IInstance inst = session.createObject(Polylist.list(concept));
    c =
        c.restrict(
            new Restriction(
                CoreScience.HAS_OBSERVABLE, new DefaultConformance().getConstraint(inst)));

    if (context != null) {

      ArrayList<Restriction> er = new ArrayList<Restriction>();
      for (IExtent o : context.getExtents()) {
        Restriction r = o.getConstraint("intersects");
        if (r != null) er.add(r);
      }

      if (er.size() > 0) {
        c =
            c.restrict(
                er.size() == 1
                    ? er.get(0)
                    : Restriction.AND(er.toArray(new Restriction[er.size()])));
      }
    }

    IQueryResult r = kbox.query(c);

    session.getOutputStream().print(r.getTotalResultCount() + " possible observation(s) found");

    for (int i = 0; i < r.getTotalResultCount(); i++) {
      Polylist o = r.getResultAsList(i, null);
      session.print(" --- Observation " + i + " ----------------\n");
      session.print(Polylist.prettyPrint(o));
      session.print("\n");
    }

    return null;
  }