Esempio n. 1
0
  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();
    }
  }
Esempio n. 2
0
  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());
  }
Esempio n. 3
0
 /**
  * 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();
   }
 }
Esempio n. 4
0
 /**
  * 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);
   }
 }
Esempio n. 5
0
  /**
   * Builds the full URI path to this resource method.
   *
   * @return the full URI path to this resource method.
   */
  public String getFullpath() {
    List<String> subpaths = new ArrayList<String>();
    if (getSubpath() != null) {
      subpaths.add(0, getSubpath());
    }

    Resource parent = getParent();
    while (parent != null) {
      subpaths.add(0, parent.getPath());
      parent = parent.getParent();
    }

    StringBuilder builder = new StringBuilder();
    for (String subpath : subpaths) {
      subpath = subpath.trim();
      if (!subpath.startsWith("/")) {
        subpath = '/' + subpath;
      }
      while (subpath.endsWith("/")) {
        subpath = subpath.substring(0, subpath.length() - 1);
      }
      subpath = scrubParamNames(subpath);

      builder.append(subpath);
    }

    return builder.toString();
  }
Esempio n. 6
0
  public void testBackwardCompatibility() throws RegistryException {
    Registry rootRegistry = embeddedRegistryService.getSystemRegistry();
    Resource r1 = rootRegistry.newResource();
    r1.setContent("r1 content");
    rootRegistry.put("/test/comments/r1", r1);

    rootRegistry.addComment(
        "/test/comments/r1", new Comment("backward-compatibility1 on this resource :)"));
    rootRegistry.addComment(
        "/test/comments/r1", new Comment("backward-compatibility2 on this resource :)"));

    String sql =
        "SELECT REG_COMMENT_ID FROM REG_COMMENT C, REG_RESOURCE_COMMENT RC "
            + "WHERE C.REG_COMMENT_TEXT LIKE ? AND C.REG_ID=RC.REG_COMMENT_ID";

    Resource queryR = rootRegistry.newResource();
    queryR.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
    queryR.addProperty(
        RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.COMMENTS_RESULT_TYPE);
    rootRegistry.put("/beep/x", queryR);
    Map<String, String> params = new HashMap<String, String>();
    params.put("query", sql);
    params.put(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.COMMENTS_RESULT_TYPE);
    params.put("1", "backward-compatibility1%");
    Collection qResults = rootRegistry.executeQuery("/beep/x", params);

    String[] qPaths = (String[]) qResults.getContent();

    assertEquals("Query result count should be 1", qPaths.length, 1);
  }
Esempio n. 7
0
 /** 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;
 }
Esempio n. 8
0
 public void draw(GOut g) {
   try {
     Resource res = item.res.get();
     Tex tex = res.layer(Resource.imgc).tex();
     drawmain(g, tex);
     if (item.num >= 0) {
       g.atext(Integer.toString(item.num), tex.sz(), 1, 1);
     } else if (itemnum.get() != null) {
       g.aimage(itemnum.get(), tex.sz(), 1, 1);
     }
     if (item.meter > 0) {
       double a = ((double) item.meter) / 100.0;
       g.chcolor(255, 255, 255, 64);
       Coord half = Inventory.isqsz.div(2);
       g.prect(half, half.inv(), half, a * Math.PI * 2);
       g.chcolor();
     }
     if (olcol.get() != null) {
       if (cmask != res) {
         mask = null;
         if (tex instanceof TexI) mask = ((TexI) tex).mkmask();
         cmask = res;
       }
       if (mask != null) {
         g.chcolor(olcol.get());
         g.image(mask, Coord.z);
         g.chcolor();
       }
     }
   } catch (Loading e) {
     missing.loadwait();
     g.image(missing.layer(Resource.imgc).tex(), Coord.z, sz);
   }
 }
Esempio n. 9
0
 @Test
 public void testPresentTotalCount() throws URISyntaxException {
   Integer totalResults = new Integer(17);
   Resource thisMetaPage = createMetadata(true, totalResults);
   Literal tr = thisMetaPage.getModel().createTypedLiteral(totalResults);
   assertTrue(thisMetaPage.hasProperty(OpenSearch.totalResults, tr));
 }
Esempio n. 10
0
 public List<String> getResourceList() {
   ArrayList<String> resources = new ArrayList<>();
   for (Resource res : getCurrentConfig().getAllResources()) {
     resources.add(res.getName());
   }
   return resources;
 }
 private static void addTypeToAll(Resource type, Set<Resource> candidates) {
   List<Resource> types = equivalentTypes(type);
   for (Resource element : candidates) {
     Resource resource = element;
     for (int i = 0; i < types.size(); i += 1) resource.addProperty(RDF.type, types.get(i));
   }
 }
Esempio n. 12
0
 private boolean cons(Pagina p, Collection<Pagina> buf) {
   Pagina[] cp = new Pagina[0];
   Collection<Pagina> open, close = new HashSet<Pagina>();
   synchronized (ui.sess.glob.paginae) {
     open = new HashSet<Pagina>(ui.sess.glob.paginae);
   }
   boolean ret = true;
   while (!open.isEmpty()) {
     Iterator<Pagina> iter = open.iterator();
     Pagina pag = iter.next();
     iter.remove();
     try {
       Resource r = pag.res();
       AButton ad = r.layer(Resource.action);
       if (ad == null) throw (new PaginaException(pag));
       Pagina parent = paginafor(ad.parent);
       if (parent == p) buf.add(pag);
       else if ((parent != null) && !close.contains(parent)) open.add(parent);
       close.add(pag);
     } catch (Loading e) {
       ret = false;
     }
   }
   return (ret);
 }
 public void newwidget(int id, String type, Coord c, int parent, Object... args)
     throws InterruptedException {
   WidgetFactory f;
   if (type.indexOf('/') >= 0) {
     int ver = -1, p;
     if ((p = type.indexOf(':')) > 0) {
       ver = Integer.parseInt(type.substring(p + 1));
       type = type.substring(0, p);
     }
     Resource res = Resource.load(type, ver);
     res.loadwaitint();
     f = res.layer(Resource.CodeEntry.class).get(WidgetFactory.class);
   } else {
     f = Widget.gettype(type);
   }
   synchronized (this) {
     Widget pwdg = widgets.get(parent);
     if (pwdg == null)
       throw (new UIException("Null parent widget " + parent + " for " + id, type, args));
     Widget wdg = f.create(c, pwdg, args);
     bind(wdg, id);
     wdg.binded();
     if (wdg instanceof MapView) mainview = (MapView) wdg;
   }
 }
Esempio n. 14
0
 public static Tex rendertt(Resource res, boolean withpg, boolean hotkey) {
   Resource.AButton ad = res.layer(Resource.action);
   Resource.Pagina pg = res.layer(Resource.pagina);
   String tt = ad.name;
   BufferedImage xp = null, food = null;
   if (hotkey) {
     int pos = tt.toUpperCase().indexOf(Character.toUpperCase(ad.hk));
     if (pos >= 0)
       tt =
           tt.substring(0, pos)
               + "$col[255,255,0]{"
               + tt.charAt(pos)
               + "}"
               + tt.substring(pos + 1);
     else if (ad.hk != 0) tt += " [" + ad.hk + "]";
   }
   if (withpg) {
     if (pg != null) {
       tt += "\n\n" + pg.text;
     }
     xp = getXPgain(ad.name);
     food = getFood(ad.name);
   }
   BufferedImage img = ttfnd.render(tt, 300).img;
   if (xp != null) {
     img = ItemInfo.catimgs(3, img, xp);
   }
   if (food != null) {
     img = ItemInfo.catimgs(3, img, food);
   }
   return (new TexI(img));
 }
Esempio n. 15
0
 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);
 }
Esempio n. 16
0
 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;
 }
Esempio n. 17
0
  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;
  }
Esempio n. 18
0
  /**
   * Returns list of mapped files, that should be transformed. Files can by specified via attributes
   * (srcFile, srcDir) or resources (FileSet, FileList, DirSet, etc). Mapped file represents input
   * and output file for transformation.
   *
   * @return list of mapped files
   */
  public List<MappedFile> getMappedFiles() {
    mappedFiles.clear();

    // one src file
    if (getSrcFile() != null) {
      addMappedFile(getSrcFile());
    }

    if (getSrcDir() != null) {
      addMappedFile(getSrcDir());
    }

    Iterator element = resources.iterator();
    while (element.hasNext()) {
      ResourceCollection rc = (ResourceCollection) element.next();
      if (rc instanceof FileSet && rc.isFilesystemOnly()) {
        FileSet fs = (FileSet) rc;
        File fromDir = fs.getDir(getProject());

        DirectoryScanner ds;
        try {
          ds = fs.getDirectoryScanner(getProject());
        } catch (BuildException ex) {
          log("Could not scan directory " + fromDir, ex, Project.MSG_ERR);
          continue;
        }

        for (String f : ds.getIncludedFiles()) {
          addMappedFile(new File(fromDir + System.getProperty("file.separator") + f), fromDir);
        }
      } else {
        if (!rc.isFilesystemOnly()) {
          log("Only filesystem resources are supported", Project.MSG_WARN);
          continue;
        }
        Iterator rcIt = rc.iterator();
        while (rcIt.hasNext()) {
          Resource r = (Resource) rcIt.next();
          if (!r.isExists()) {
            log("Could not find resource " + r.toLongString(), Project.MSG_VERBOSE);
            continue;
          }

          if (r instanceof FileResource) {
            FileResource fr = (FileResource) r;
            addMappedFile(fr.getFile(), fr.getBaseDir());
          } else {
            log(
                "Only file resources are supported (" + r.getClass().getSimpleName() + " found)",
                Project.MSG_WARN);
            continue;
          }
        }
      }
    }

    return mappedFiles;
  }
  /**
   * Index all the resources in a Jena Model to ES
   *
   * @param model the model to index
   * @param bulkRequest a BulkRequestBuilder
   * @param getPropLabel if set to true all URI property values will be indexed as their label. The
   *     label is taken as the value of one of the properties set in {@link #uriDescriptionList}.
   */
  private void addModelToES(Model model, BulkRequestBuilder bulkRequest, boolean getPropLabel) {
    long startTime = System.currentTimeMillis();
    long bulkLength = 0;
    HashSet<Property> properties = new HashSet<Property>();

    StmtIterator it = model.listStatements();
    while (it.hasNext()) {
      Statement st = it.nextStatement();
      Property prop = st.getPredicate();
      String property = prop.toString();

      if (rdfPropList.isEmpty()
          || (isWhitePropList && rdfPropList.contains(property))
          || (!isWhitePropList && !rdfPropList.contains(property))
          || (normalizeProp.containsKey(property))) {
        properties.add(prop);
      }
    }

    ResIterator resIt = model.listSubjects();

    while (resIt.hasNext()) {
      Resource rs = resIt.nextResource();
      Map<String, ArrayList<String>> jsonMap = getJsonMap(rs, properties, model, getPropLabel);

      bulkRequest.add(
          client.prepareIndex(indexName, typeName, rs.toString()).setSource(mapToString(jsonMap)));
      bulkLength++;

      // We want to execute the bulk for every  DEFAULT_BULK_SIZE requests
      if (bulkLength % EEASettings.DEFAULT_BULK_SIZE == 0) {
        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        // After executing, flush the BulkRequestBuilder.
        bulkRequest = client.prepareBulk();

        if (bulkResponse.hasFailures()) {
          processBulkResponseFailure(bulkResponse);
        }
      }
    }

    // Execute remaining requests
    if (bulkRequest.numberOfActions() > 0) {
      BulkResponse response = bulkRequest.execute().actionGet();
      // Handle failure by iterating through each bulk response item
      if (response.hasFailures()) {
        processBulkResponseFailure(response);
      }
    }

    // Show time taken to index the documents
    logger.info(
        "Indexed {} documents on {}/{} in {} seconds",
        bulkLength,
        indexName,
        typeName,
        (System.currentTimeMillis() - startTime) / 1000.0);
  }
Esempio n. 20
0
  /**
   * Answer the lowest common ancestor of two classes in a given ontology. This is the class that is
   * farthest from the root concept (defaulting to <code>owl:Thing</code> which is a super-class of
   * both <code>u</code> and <code>v</code>. The algorithm is based on <a
   * href="http://en.wikipedia.org/wiki/Tarjan's_off-line_least_common_ancestors_algorithm">Tarjan's
   * off-line LCA</a>. The current implementation expects that the given model:
   *
   * <ul>
   *   <li>is transitively closed over the <code>subClassOf</code> relation
   *   <li>can cheaply determine <em>direct sub-class</em> relations
   * </ul>
   *
   * <p>Both of these conditions are true of the built-in Jena OWL reasoners, such as {@link
   * OntModelSpec#OWL_MEM_MICRO_RULE_INF}, and external DL reasoners such as Pellet.
   *
   * @param m The ontology model being queried to find the LCA, which should conform to the reasoner
   *     capabilities described above
   * @param u An ontology class
   * @param v An ontology class
   * @return The LCA of <code>u</code> and <code>v</code>
   * @exception JenaException if the language profile of the given model does not define a top
   *     concept (e.g. <code>owl:Thing</code>)
   */
  public static OntClass getLCA(OntModel m, OntClass u, OntClass v) {
    Resource root = m.getProfile().THING();
    if (root == null) {
      throw new JenaException(
          "The given OntModel has a language profile that does not define a generic root class (such as owl:Thing)");
    }

    root = root.inModel(m);
    return getLCA(m, root.as(OntClass.class), u, v);
  }
Esempio n. 21
0
 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;
 }
Esempio n. 22
0
 /**
  * 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());
   }
 }
 /**
  * the simplest case: if we assert all the components of a reification quad, we can get a
  * ReifiedStatement that represents the reified statement.
  */
 public void testBasicReification() {
   if (model.getReificationStyle() != ModelFactory.Minimal) {
     Resource R = model.createResource(aURI);
     model.add(R, RDF.type, RDF.Statement);
     model.add(R, RDF.subject, S);
     model.add(R, RDF.predicate, P);
     model.add(R, RDF.object, O);
     RDFNode rs = R.as(ReifiedStatement.class);
     assertEquals("can recover statement", SPO, ((ReifiedStatement) rs).getStatement());
   }
 }
Esempio n. 24
0
  public void destroy() {
    log.info("Destroying API: " + name);
    for (Resource resource : resources.values()) {
      resource.destroy();
    }

    for (Handler handler : handlers) {
      if (handler instanceof ManagedLifecycle) {
        ((ManagedLifecycle) handler).destroy();
      }
    }
  }
Esempio n. 25
0
 private BufferedImage tileimg(int t, BufferedImage[] texes) {
   BufferedImage img = texes[t];
   if (img == null) {
     Resource r = ui.sess.glob.map.tilesetr(t);
     if (r == null) return (null);
     Resource.Image ir = r.layer(Resource.imgc);
     if (ir == null) return (null);
     img = ir.img;
     texes[t] = img;
   }
   return (img);
 }
Esempio n. 26
0
  @Test
  public void testTermbindsIncludesMetaproperties() throws URISyntaxException {
    Integer totalResults = null;
    Resource thisMetaPage = createMetadata(false, totalResults);

    for (Property p : expectedTermboundProperties) {
      Model model = thisMetaPage.getModel();
      if (!model.contains(null, API.property, p)) {
        fail("term bindings should include " + model.shortForm(p.getURI()));
      }
    }
  }
Esempio n. 27
0
 private boolean resourceMatches(Resource r1, Resource r2) {
   String[] methods1 = r1.getMethods();
   String[] methods2 = r2.getMethods();
   for (String m1 : methods1) {
     for (String m2 : methods2) {
       if (m1.equals(m2)) {
         return true;
       }
     }
   }
   return false;
 }
Esempio n. 28
0
 /** 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");
   }
 }
Esempio n. 29
0
 static String createUID(Project project, Resource resource) {
   String uid = resource.getKey();
   if (!StringUtils.equals(Scopes.PROJECT, resource.getScope())) {
     // not a project nor a library
     uid =
         new StringBuilder(ResourceModel.KEY_SIZE)
             .append(project.getKey())
             .append(':')
             .append(resource.getKey())
             .toString();
   }
   return uid;
 }
Esempio n. 30
0
 /** 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);
 }