Java源码示例:org.apache.jena.util.FileManager

示例1
private ReasoningOntology(String ontologyFile){
//		data = ModelFactory.createOntologyModel();
		
		// use the FileManager to find the input file
		 InputStream in = FileManager.get().open( ontologyFile );
		if (in == null) {
		    throw new IllegalArgumentException(
		                                 "File: " + ontologyFile + " not found");
		}

		
		// read the RDF/XML file
		ontology.read(in, null);
		data = ontology;
//		data.read(in, null);
		updateInfModel();
		
	}
 
示例2
/**
 * Create an SPDX Document from a file
 * @param fileNameOrUrl local file name or Url containing the SPDX data.  Can be in RDF/XML or RDFa format
 * @return SPDX Document initialized with the exsiting data
 * @throws IOException
 * @throws InvalidSPDXAnalysisException
 */
public static SPDXDocument creatSpdxDocument(String fileNameOrUrl) throws IOException, InvalidSPDXAnalysisException {
	try {
		Class.forName("net.rootdev.javardfa.jena.RDFaReader");
	} catch(java.lang.ClassNotFoundException e) {}  // do nothing

	Model model = ModelFactory.createDefaultModel();

	InputStream spdxRdfInput = FileManager.get().open(fileNameOrUrl);
	if (spdxRdfInput == null)
		throw new FileNotFoundException("Unable to open \"" + fileNameOrUrl + "\" for reading");

	model.read(spdxRdfInput, figureBaseUri(fileNameOrUrl), fileType(fileNameOrUrl));

	return new SPDXDocument(model);
}
 
示例3
private Dataset buildBaseDataset() {
	Dataset jenaData;
	
	if (StringUtils.isNotBlank(jenaConfig.getAssemblerFile())) {
		LOGGER.debug("Building dataset from assembler file {}", jenaConfig.getAssemblerFile());
		jenaData = DatasetFactory.assemble(jenaConfig.getAssemblerFile(), jenaConfig.getAssemblerDataset());
	} else if (StringUtils.isNotBlank(jenaConfig.getTdbPath())) {
		LOGGER.debug("Building dataset from TDB data at {}", jenaConfig.getTdbPath());
		jenaData = TDBFactory.createDataset(jenaConfig.getTdbPath());
	} else {
		LOGGER.debug("Building dataset from ontology URI {}", jenaConfig.getOntologyUri());
		FileManager fileManager = FileManager.get();
		Model model = fileManager.loadModel(jenaConfig.getOntologyUri());
		
		// Build the base dataset backed by the model loaded from the URI
		jenaData = DatasetFactory.create(model);
	}
	
	return jenaData;
}
 
示例4
public static void main (String args[]) {
    // create an empty model
    Model model1 = ModelFactory.createDefaultModel();
    Model model2 = ModelFactory.createDefaultModel();
   
    // use the class loader to find the input file
    InputStream in1 = FileManager.get().open(inputFileName1);
    if (in1 == null) {
        throw new IllegalArgumentException( "File: " + inputFileName1 + " not found");
    }
    InputStream in2 = FileManager.get().open(inputFileName2);
    if (in2 == null) {
        throw new IllegalArgumentException( "File: " + inputFileName2 + " not found");
    }
    
    // read the RDF/XML files
    model1.read( in1, "" );
    model2.read( in2, "" );
    
    // merge the graphs
    Model model = model1.union(model2);
    
    // print the graph as RDF/XML
    model.write(System.out, "RDF/XML-ABBREV");
    System.out.println();
}
 
示例5
public static void main (String args[]) {
    // create an empty model
    Model model = ModelFactory.createDefaultModel();
   
    // use the FileManager to find the input file
    InputStream in = FileManager.get().open(inputFileName);
    if (in == null) {
        throw new IllegalArgumentException( "File: " + inputFileName + " not found");
    }
    
    // read the RDF/XML file
    model.read( in, "");
    
    // select all the resources with a VCARD.FN property
    ResIterator iter = model.listResourcesWithProperty(VCARD.FN);
    if (iter.hasNext()) {
        System.out.println("The database contains vcards for:");
        while (iter.hasNext()) {
            System.out.println("  " + iter.nextResource()
                                          .getRequiredProperty(VCARD.FN)
                                          .getString() );
        }
    } else {
        System.out.println("No vcards were found in the database");
    }            
}
 
示例6
private void read(String file_path) {
  InputStream in = FileManager.get().open(file_path);

  if (null == in) {
    throw new IllegalArgumentException( "File: " + file_path + " not found." );
  }

  read(in);
}
 
示例7
private void read(String filenameOrURI) {
  InputStream in = FileManager.get().open(filenameOrURI);

  if (null == in) {
    throw new IllegalArgumentException("File: " + filenameOrURI + " not found.");
  }

  read(in);
}
 
示例8
/**
 * Initial ontology model from an ontology file
 *
 * @param file the file path or url of the ontology
 */
public OntModelWrapper(String file) {
  this();
  InputStream in = FileManager.get().open(file);

  if (null == in) {
    throw new IllegalArgumentException( "File: " + file + " not found.");
  }
  read(in);
}
 
示例9
public static void main(String[] args) throws IOException, InterruptedException {

		PROPERTY_SURFACE_FORMS = DIRECTORY + "property_surface_forms.ttl";

		// create an empty model
		Model inputModel = ModelFactory.createDefaultModel();

		// use the FileManager to find the input file
		InputStream in = FileManager.get().open(DBPEDIA_PROPERTY_FILE);
		if (in == null) {
			throw new IllegalArgumentException("File: " + DBPEDIA_PROPERTY_FILE + " not found");
		}

		// read the RDF/XML file
		inputModel.read(in, null, "N-TRIPLE");
		inputModel.write(System.out);

		Model outputModel = ModelFactory.createDefaultModel();
		QueryExecution qExec = QueryExecutionFactory
				.create("SELECT ?s  ?label WHERE{?s a <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>."
						+ " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. }", inputModel);
		ResultSet rs = qExec.execSelect();
		System.out.println(qExec);
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource uri = qs.get("?s").asResource();
			RDFNode label = qs.get("?label");
			StatementImpl s = new StatementImpl(uri, RDFS.label, label);
			outputModel.add(s);

		}

		qExec.close();

		FileOutputStream outputFile = new FileOutputStream(PROPERTY_SURFACE_FORMS);
		RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES);
	}
 
示例10
public static void main(String[] args) throws IOException, InterruptedException {

		CLASS_SURFACE_FORMS = DIRECTORY + "class_surface_forms.ttl";

		// create an empty model
		Model inputModel = ModelFactory.createDefaultModel();

		// use the FileManager to find the input file
		InputStream in = FileManager.get().open(DBPEDIA_CLASSE_FILE);
		if (in == null) {
			throw new IllegalArgumentException("File: " + DBPEDIA_CLASSE_FILE + " not found");
		}

		// read the RDF/XML file
		inputModel.read(in, null, "N-TRIPLE");

		Model outputModel = ModelFactory.createDefaultModel();
		QueryExecution qExec = QueryExecutionFactory
				.create("SELECT ?s ?label WHERE{?s a <http://www.w3.org/2002/07/owl#Class>."
						+ " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. "
						+ "FILTER (lang(?label) = \"en\")}", inputModel);
		ResultSet rs = qExec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource uri = qs.get("?s").asResource();
			RDFNode label = qs.get("?label");
			StatementImpl s = new StatementImpl(uri, RDFS.label, label);
			outputModel.add(s);

		}

		qExec.close();

		FileOutputStream outputFile = new FileOutputStream(CLASS_SURFACE_FORMS);
		RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES);

	}
 
示例11
@Test
public void testLocalUri() throws IOException {
	String id = "BSD-3-Clause";
	File licenseHtmlFile = new File("TestFiles" + File.separator + id);
	String stdLicUri = "file://" + licenseHtmlFile.getAbsolutePath().replace('\\', '/').replace(" ", "%20");
	byte[] buf = new byte[2048];

	InputStream in = FileManager.get().open(stdLicUri);
	try {
		int readLen = in.read(buf, 0, 2048);
		assertTrue(readLen > 0);
	} finally {
		in.close();
	}
}
 
示例12
/**
 * Create an Legacy SPDX Document from a file - Legacy SPDX documents only specification version 1.2 features
 * @param fileNameOrUrl local file name or Url containing the SPDX data.  Can be in RDF/XML or RDFa format
 * @return SPDX Document initialized with the exsiting data
 * @throws IOException
 * @throws InvalidSPDXAnalysisException
 */
@SuppressWarnings("deprecation")
public static SPDXDocument createLegacySpdxDocument(String fileNameOrUrl) throws IOException, InvalidSPDXAnalysisException {
	try {
		Class.forName("net.rootdev.javardfa.jena.RDFaReader");
	} catch(java.lang.ClassNotFoundException e) {
		logger.warn("Unable to load the RDFaReader Class");
	}  

	InputStream spdxRdfInput = FileManager.get().open(fileNameOrUrl);
	if (spdxRdfInput == null)
		throw new FileNotFoundException("Unable to open \"" + fileNameOrUrl + "\" for reading");

	return createLegacySpdxDocument(spdxRdfInput, figureBaseUri(fileNameOrUrl), fileType(fileNameOrUrl));
}
 
示例13
/**
 * Create an SPDX Document from a file
 * @param fileNameOrUrl local file name or Url containing the SPDX data.  Can be in RDF/XML or RDFa format
 * @return SPDX Document initialized with the exsiting data
 * @throws IOException
 * @throws InvalidSPDXAnalysisException
 */
public static SpdxDocument createSpdxDocument(String fileNameOrUrl) throws IOException, InvalidSPDXAnalysisException {
	try {
		Class.forName("net.rootdev.javardfa.jena.RDFaReader");
	} catch(java.lang.ClassNotFoundException e) {
		logger.warn("Unable to load the RDFaReader Class");
	}  

	InputStream spdxRdfInput = FileManager.get().open(fileNameOrUrl);
	if (spdxRdfInput == null)
		throw new FileNotFoundException("Unable to open \"" + fileNameOrUrl + "\" for reading");

	return createSpdxDocument(spdxRdfInput, figureBaseUri(fileNameOrUrl), fileType(fileNameOrUrl));
}
 
示例14
/**
 * Given a path to an RDF/XML or TTL file and a RDF language, load the file as the default model
 * of a TDB dataset backed by a directory to improve processing time. Return the new dataset.
 *
 * <p>WARNING - this creates a directory at given tdbDir location!
 *
 * @param inputPath input path of RDF/XML or TTL file
 * @param tdbDir location to put TDB mappings
 * @return Dataset instantiated with triples
 * @throws JenaException if TDB directory can't be written to
 */
public static Dataset loadToTDBDataset(String inputPath, String tdbDir) throws JenaException {
  Dataset dataset;
  if (new File(tdbDir).isDirectory()) {
    dataset = TDBFactory.createDataset(tdbDir);
    if (!dataset.isEmpty()) {
      return dataset;
    }
  }
  dataset = TDBFactory.createDataset(tdbDir);
  logger.debug(String.format("Parsing input '%s' to dataset", inputPath));
  // Track parsing time
  long start = System.nanoTime();
  Model m;
  dataset.begin(ReadWrite.WRITE);
  try {
    m = dataset.getDefaultModel();
    FileManager.get().readModel(m, inputPath);
    dataset.commit();
  } catch (JenaException e) {
    dataset.abort();
    dataset.end();
    dataset.close();
    throw new JenaException(String.format(syntaxError, inputPath));
  } finally {
    dataset.end();
  }
  long time = (System.nanoTime() - start) / 1000000000;
  logger.debug(String.format("Parsing complete - took %s seconds", String.valueOf(time)));
  return dataset;
}
 
示例15
public void run() {
    // creates a new, empty in-memory model
    Model m = ModelFactory.createDefaultModel();

    // load some data into the model
    FileManager.get().readModel( m, CHEESE_DATA_FILE );

    // generate some output
    showModelSize( m );
    listCheeses( m );
}
 
示例16
public static void main (String args[]) {
    // create an empty model
    Model model = ModelFactory.createDefaultModel();

    InputStream in = FileManager.get().open( inputFileName );
    if (in == null) {
        throw new IllegalArgumentException( "File: " + inputFileName + " not found");
    }
    
    // read the RDF/XML file
    model.read(in, "");
                
    // write it to standard out
    model.write(System.out);            
}
 
示例17
public static void main (String args[]) {
    // create an empty model
    Model model = ModelFactory.createDefaultModel();
   
    // use the FileManager to find the input file
    InputStream in = FileManager.get().open(inputFileName);
    if (in == null) {
        throw new IllegalArgumentException( "File: " + inputFileName + " not found");
    }
    
    // read the RDF/XML file
    model.read(new InputStreamReader(in), "");
    
    // retrieve the Adam Smith vcard resource from the model
    Resource vcard = model.getResource(johnSmithURI);

    // retrieve the value of the N property
    Resource name = (Resource) vcard.getRequiredProperty(VCARD.N)
                                    .getObject();
    // retrieve the given name property
    String fullName = vcard.getRequiredProperty(VCARD.FN)
                           .getString();
    // add two nick name properties to vcard
    vcard.addProperty(VCARD.NICKNAME, "Smithy")
         .addProperty(VCARD.NICKNAME, "Adman");
    
    // set up the output
    System.out.println("The nicknames of \"" + fullName + "\" are:");
    // list the nicknames
    StmtIterator iter = vcard.listProperties(VCARD.NICKNAME);
    while (iter.hasNext()) {
        System.out.println("    " + iter.nextStatement().getObject()
                                        .toString());
    }
}
 
示例18
public static void main (String args[]) {
    // create an empty model
    Model model = ModelFactory.createDefaultModel();
   
    // use the FileManager to find the input file
    InputStream in = FileManager.get().open(inputFileName);
    if (in == null) {
        throw new IllegalArgumentException( "File: " + inputFileName + " not found");
    }
    
    // read the RDF/XML file
    model.read( in, "" );
    
    // select all the resources with a VCARD.FN property
    // whose value ends with "Smith"
    StmtIterator iter = model.listStatements(
        new 
            SimpleSelector(null, VCARD.FN, (RDFNode) null) {
                @Override
                public boolean selects(Statement s) {
                        return s.getString().endsWith("Smith");
                }
            });
    if (iter.hasNext()) {
        System.out.println("The database contains vcards for:");
        while (iter.hasNext()) {
            System.out.println("  " + iter.nextStatement()
                                          .getString());
        }
    } else {
        System.out.println("No Smith's were found in the database");
    }            
}
 
示例19
private static Reader open(String filenameOrURL) {
	try {
		InputStream in = FileManager.get().open(filenameOrURL);
		if (in == null) throw new NotFoundException(filenameOrURL);
		return new InputStreamReader(in, "UTF-8");
	} catch (UnsupportedEncodingException ex) {
		// Can't happen, UTF-8 is always supported
		return null;
	}
}
 
示例20
public static InputStreamSource fromFilenameOrIRI(final String filenameOrIRI, final FileManager fm) {
	return new InputStreamSource() {
		public InputStream open() throws IOException {
			InputStream in = fm.open(filenameOrIRI);
			if (in == null) {
				throw new NotFoundException(filenameOrIRI);
			}
			return in;
		}
	};
}
 
示例21
public static TarqlQueryExecution create(TarqlQuery query, FileManager fm, CSVOptions options) throws IOException {
	String filenameOrURL = getSingleFromClause(query.getQueries().get(0), fm);
	URLOptionsParser parseResult = new URLOptionsParser(filenameOrURL);
	CSVOptions newOptions = new CSVOptions(parseResult.getOptions());
	newOptions.overrideWith(options);
	return create(query, InputStreamSource.fromFilenameOrIRI(parseResult.getRemainingURL(), fm), newOptions);
}
 
示例22
private static String getSingleFromClause(Query query, FileManager fm) {
	if (query.getGraphURIs() == null || query.getGraphURIs().isEmpty()) {
		throw new TarqlException("No input file provided");
	}
	if (query.getGraphURIs().size() > 1) {
		throw new TarqlException("Too many input files: " + query.getGraphURIs());
	}
	return query.getGraphURIs().get(0);
}
 
示例23
private boolean loadAnnotationsFromRDFs(Map<String, String> nsPrefixToFileMap){

		for(String nsprefix : nsPrefixToFileMap.keySet()){

			String rdfFile = nsPrefixToFileMap.get(nsprefix);

			Model model = null;
			try{
				model = FileManager.get().loadModel(rdfFile);

				StmtIterator stmtIterator = model.listStatements();

				while(stmtIterator.hasNext()){
					Statement statement = stmtIterator.nextStatement();

					if(statement.getPredicate().getLocalName().equals("type") &&
							statement.getPredicate().getNameSpace().contains("http://www.w3.org/1999/02/22-rdf-syntax-ns") &&
							(statement.getObject().asResource().getLocalName().equals("Property") &&
									statement.getObject().asResource().getNameSpace().contains("http://www.w3.org/2000/01/rdf-schema") ||
									statement.getObject().asResource().getLocalName().equals("Property") &&
											statement.getObject().asResource().getNameSpace().contains("http://www.w3.org/1999/02/22-rdf-syntax-ns"))){
						if(!(statement.getSubject().getLocalName() == null || statement.getSubject().getNameSpace() == null)){
							Set<String> nsSet = null;
							if((nsSet = annotationToNamespaceMap.get(statement.getSubject().getLocalName())) == null){
								nsSet = new HashSet<String>();
								annotationToNamespaceMap.put(statement.getSubject().getLocalName(), nsSet);
							}
							nsSet.add(nsprefix);
							namespacePrefixToURIMap.put(nsprefix, statement.getSubject().getNameSpace());
						}
					}
				}

				model.close();
			}catch(Exception exception){
				logger.log(Level.SEVERE, "Failed to read file '"+rdfFile+"'", exception);
				return false;
			}

		}

		for(String annotation : annotationToNamespaceMap.keySet()){
			if(annotationToNamespaceMap.get(annotation).size() > 1){
				List<String> filepaths = new ArrayList<String>();
				for(String nsPrefix : annotationToNamespaceMap.get(annotation)){
					filepaths.add(nsPrefixToFileMap.get(nsPrefix));
				}
				logger.log(Level.WARNING, "Files " + filepaths + " all have the property with name '"+annotation+"'");
			}
		}

		return true;

	}
 
示例24
public Application(final Dataset dataset, final String endpointURI, final String graphStoreURI, final String quadStoreURI,
        final String authUser, final String authPwd,
        final MediaTypes mediaTypes, final Client client, final Integer maxGetRequestSize, final boolean preemptiveAuth,
        final LocationMapper locationMapper, final String ontologyURI, final String rulesString, boolean cacheSitemap)
{
    super(dataset, endpointURI, graphStoreURI, quadStoreURI, authUser, authPwd,
            mediaTypes, client, maxGetRequestSize, preemptiveAuth);
    if (locationMapper == null) throw new IllegalArgumentException("LocationMapper be null");
    
    if (ontologyURI == null)
    {
        if (log.isErrorEnabled()) log.error("Sitemap ontology URI (" + LDT.ontology.getURI() + ") not configured");
        throw new ConfigurationException(LDT.ontology);
    }
    if (rulesString == null)
    {
        if (log.isErrorEnabled()) log.error("Sitemap Rules (" + AP.sitemapRules.getURI() + ") not configured");
        throw new ConfigurationException(AP.sitemapRules);
    }
    
    this.ontologyURI = ontologyURI;
    this.cacheSitemap = cacheSitemap;

    if (dataset != null)
        service = new com.atomgraph.core.model.impl.dataset.ServiceImpl(dataset, mediaTypes);
    else
    {
        if (endpointURI == null)
        {
            if (log.isErrorEnabled()) log.error("SPARQL endpoint not configured ('{}' not set in web.xml)", SD.endpoint.getURI());
            throw new ConfigurationException(SD.endpoint);
        }
        if (graphStoreURI == null)
        {
            if (log.isErrorEnabled()) log.error("Graph Store not configured ('{}' not set in web.xml)", A.graphStore.getURI());
            throw new ConfigurationException(A.graphStore);
        }

        service = new com.atomgraph.core.model.impl.remote.ServiceImpl(client, mediaTypes,
                ResourceFactory.createResource(endpointURI), ResourceFactory.createResource(graphStoreURI),
                quadStoreURI != null ? ResourceFactory.createResource(quadStoreURI) : null,
                authUser, authPwd, maxGetRequestSize);
    }
    
    application = new ApplicationImpl(service, ResourceFactory.createResource(ontologyURI));

    List<Rule> rules = Rule.parseRules(rulesString);
    OntModelSpec rulesSpec = new OntModelSpec(OntModelSpec.OWL_MEM);
    Reasoner reasoner = new GenericRuleReasoner(rules);
    //reasoner.setDerivationLogging(true);
    //reasoner.setParameter(ReasonerVocabulary.PROPtraceOn, Boolean.TRUE);
    rulesSpec.setReasoner(reasoner);
    this.ontModelSpec = rulesSpec;
    
    BuiltinPersonalities.model.add(Parameter.class, ParameterImpl.factory);
    BuiltinPersonalities.model.add(Template.class, TemplateImpl.factory);

    SPINModuleRegistry.get().init(); // needs to be called before any SPIN-related code
    ARQFactory.get().setUseCaches(false); // enabled caching leads to unexpected QueryBuilder behaviour
    
    DataManager dataManager = new DataManager(locationMapper, client, mediaTypes, preemptiveAuth);
    FileManager.setStdLocators(dataManager);
    FileManager.setGlobalFileManager(dataManager);
    if (log.isDebugEnabled()) log.debug("FileManager.get(): {}", FileManager.get());

    OntDocumentManager.getInstance().setFileManager(dataManager);
    if (log.isDebugEnabled()) log.debug("OntDocumentManager.getInstance().getFileManager(): {}", OntDocumentManager.getInstance().getFileManager());
    OntDocumentManager.getInstance().setCacheModels(cacheSitemap); // lets cache the ontologies FTW!!
}
 
示例25
public static FileManager getFileManager(LocationMapper locationMapper)
{
    FileManager fileManager = FileManager.get();
    fileManager.setLocationMapper(locationMapper);
    return fileManager;
}
 
示例26
public static void convertToNtripleFormat(File in, File out) throws IOException {
	Model model = FileManager.get().loadModel(in.getAbsolutePath());
	BufferedWriter bw = new BufferedWriter(new FileWriter(out));
	model.write(bw, "N-TRIPLE");
	bw.close();
}
 
示例27
public static QueryExecution create(Query query,
		FileManager queryFileManager) {
	return null;
}
 
示例28
public void setFileManager(FileManager arg0)
{
throw new RdfStoreException("Operation not supported");
}
 
示例29
protected void loadData( Model m ) {
    FileManager.get().readModel( m, SOURCE + "pizza.owl.rdf" );
}
 
示例30
public static void main (String args[]) {
    // create an empty model
    Model model = ModelFactory.createDefaultModel();
   
    // use the class loader to find the input file
    InputStream in = FileManager.get().open( inputFileName );
    if (in == null) {
        throw new IllegalArgumentException( "File: " + inputFileName + " not found");
    }
    
    // read the RDF/XML file
    model.read(new InputStreamReader(in), "");
    
    // create a bag
    Bag smiths = model.createBag();
    
    // select all the resources with a VCARD.FN property
    // whose value ends with "Smith"
    StmtIterator iter = model.listStatements(
        new 
            SimpleSelector(null, VCARD.FN, (RDFNode) null) {
                @Override
                public boolean selects(Statement s) {
                        return s.getString().endsWith("Smith");
                }
            });
    // add the Smith's to the bag
    while (iter.hasNext()) {
        smiths.add( iter.nextStatement().getSubject());
    }
    
    // print the graph as RDF/XML
    model.write(new PrintWriter(System.out));
    System.out.println();
    
    // print out the members of the bag
    NodeIterator iter2 = smiths.iterator();
    if (iter2.hasNext()) {
        System.out.println("The bag contains:");
        while (iter2.hasNext()) {
            System.out.println("  " +
                ((Resource) iter2.next())
                                 .getRequiredProperty(VCARD.FN)
                                 .getString());
        }
    } else {
        System.out.println("The bag is empty");
    }
}