⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 n3tordf.java

📁 Jena推理机
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * (c) Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
 * [See end of file]
 */

package com.hp.hpl.jena.n3;

import antlr.collections.AST ;
import java.util.* ;
import com.hp.hpl.jena.rdf.model.* ;
import com.hp.hpl.jena.shared.*;

import com.hp.hpl.jena.vocabulary.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author		Andy Seaborne
 * @version 	$Id: N3toRDF.java,v 1.36 2007/01/28 16:04:13 andy_seaborne Exp $
 */
public class N3toRDF implements N3ParserEventHandler
{
    protected static Log log = LogFactory.getLog( N3toRDF.class );
	
	Model model ;

	// Maps URIref or a _:xxx bNode to a Resource
	Map resourceRef = new HashMap() ;
	// Maps URIref to Property
	Map propertyRef = new HashMap() ;
    
    // A more liberal prefix mapping map.
    Map myPrefixMapping = new HashMap() ;
    
    boolean allowPropertySymbols = true ;
    boolean allowKeywordA        = true ;
	
	// Well known namespaces
	
	static final String NS_rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" ;
    static final String NS_rdfs = "http://www.w3.org/2000/01/rdf-schema#" ;
	
    static final String NS_W3_log = "http://www.w3.org/2000/10/swap/log#" ;
    static final String LOG_IMPLIES = NS_W3_log+"implies" ; 
    static final String LOG_MEANS =   NS_W3_log+"means" ; 

    static final String XMLLiteralURI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral" ;

	private String base = null ;
    //private String basedir = null ;
	final String anonPrefix = "_" ;
	
    public N3toRDF(Model model, String base)
    {
        this.base = base ;
        this.model = model ;
    }

    
	public void startDocument() { }
	public void endDocument()   { }
	
	// When Jena exceptions are runtime, we will change this
	public void error(Exception ex, String message) 		{ throw new N3Exception(message) ; }
	public void error(String message) 						{ error(null, message) ; }
    
	public void warning(Exception ex, String message)       { log.warn(message, ex) ; }
	public void warning(String message)						{ log.warn(message) ; }
    
	public void deprecated(Exception ex, String message)	{ throw new N3Exception(message) ; }
	public void deprecated(String message)					{ deprecated(null, message) ; }
	
	public void startFormula(int line, String context)
	{
		error("Line "+line+": N3toRDF: All statements are asserted - no formulae in RDF") ;
	}
					
	public void endFormula(int line, String context) {}
	
	public void directive(int line, AST directive, AST[] args, String context)
	{
		if ( directive.getType() == N3Parser.AT_PREFIX )
		{
			// @prefix now
			if ( args[0].getType() != N3Parser.QNAME )
			{
				error("Line "+line+": N3toRDF: Prefix directive does not start with a prefix! "+args[0].getText()+ "["+N3Parser.getTokenNames()[args[0].getType()]+"]") ;
				return ;
			}
					
			String prefix = args[0].getText() ;
			if ( prefix.endsWith(":") )
				prefix = prefix.substring(0,prefix.length()-1) ;
				
			if ( args[1].getType() != N3Parser.URIREF )
			{
				error("Line "+line+": N3toRDF: Prefix directive does not supply a URIref! "+args[1].getText()) ;
				return ;
			}
			
			String uriref = args[1].getText() ;
            uriref = expandURIRef(uriref, line) ;
            
            if ( uriref == null )
			    error("Line "+line+": N3toRDF: Relative URI can't be resolved in in @prefix directive") ;  
                
            setPrefixMapping(model, prefix, uriref) ;
			return ;
		}
		
		warning("Line "+line+": N3toRDF: Directive not recongized and ignored: "+directive.getText()) ;
		return ;
	}
	
	
	public void quad(int line, AST subj, AST prop, AST obj, String context)
	{
        // Syntax that reverses subject and object is done in the grammar

		if ( context != null )
			error("Line "+line+": N3toRDF: All statement are asserted - no formulae") ;
		
		try
		{
			// Converting N3 to RDF:
			// subject: must be a URIref or a bNode name
			// property: remove sugaring and then must be a URIref
			// object: can be a literal or a URIref or a bNode name
			// context must be zero (no formulae)

            // Lists: The parser creates list elements as sequences of triples:
            //       anon  list:first  ....
            //       anon  list:rest   resource
            // Where "resource" is nil for the last element of the list (generated first).

            // The properties are in a unique namespace to distinguish them
            // from lists encoded explicitly, not with the () syntax.

			int pType = prop.getType();
			String propStr = prop.getText();
            Property pNode = null ;
			
			switch (pType)
			{
				case N3Parser.ARROW_R :
                    if ( ! allowPropertySymbols )
                        error("Line "+line+": N3toRDF: Property symbol '=>' not allowed") ;
					propStr = LOG_IMPLIES ;
					break;
				case N3Parser.ARROW_MEANS :
                    if ( ! allowPropertySymbols )
                        error("Line "+line+": N3toRDF: Property symbol '<=>' not allowed") ;
					propStr = LOG_MEANS ;
					break;
				case N3Parser.ARROW_L :
                    if ( ! allowPropertySymbols )
                        error("Line "+line+": N3toRDF: Property symbol '<=' not allowed") ;
					// Need to reverse subject and object
					propStr = LOG_IMPLIES ;
					AST tmp = obj; obj = subj; subj = tmp;
					break;
				case N3Parser.EQUAL :
					//propStr = NS_DAML + "equivalentTo";
					//propStr = damlVocab.equivalentTo().getURI() ;
                    if ( ! allowPropertySymbols )
                        error("Line "+line+": N3toRDF: Property symbol '=' not allowed") ;
                    pNode = OWL.sameAs ;
					break;
				case N3Parser.KW_A :
                    if ( ! allowKeywordA )
                        error("Line "+line+": N3toRDF: Property symbol 'a' not allowed") ;
                    pNode = RDF.type ;
					break ;
				case N3Parser.QNAME:
                    
                    if ( prop.getText().startsWith("_:") )
                        error("Line "+line+": N3toRDF: Can't have properties with labelled bNodes in RDF") ;
                    
                    String uriref = expandPrefix(model, propStr) ;
                    if ( uriref == propStr )
                    {
                        // Failed to expand ...
                        error("Line "+line+": N3toRDF: Undefined qname namespace: " + propStr);
                        return ;
                    }
                    pNode = model.createProperty(uriref) ;
                    break ;
				case N3Parser.URIREF:
                    propStr = expandURIRef(propStr, line) ;
                    break ;
                case N3Parser.TK_LIST_FIRST:
                    pNode = RDF.first ;
                break ;
                case N3Parser.TK_LIST_REST:
                    pNode = RDF.rest ;
                    break ;
                // Literals, parser generated bNodes (other bnodes handled as QNAMEs)
                // and tokens that can't be properties.
                case N3Parser.ANON:
                    error("Line "+line+": N3toRDF: Can't have anon. properties in RDF") ;
                    break ;
				default:
					error("Line "+line+": N3toRDF: Shouldn't see "+
								N3EventPrinter.formatSlot(prop)+
								" at this point!") ;
                    break ;
			}

            // Didn't find an existing one above so make it ...
            if ( pNode == null )
                pNode = model.createProperty(propStr) ;
            else
                propStr = pNode.getURI() ;

			RDFNode sNode = createNode(line, subj);
            // Must be a resource
			if ( sNode instanceof Literal )
				error("Line "+line+": N3toRDF: Subject can't be a literal: " +subj.getText()) ;

			RDFNode oNode = createNode(line, obj);
			
			Statement stmt = model.createStatement((Resource)sNode, pNode, oNode) ;
			model.add(stmt) ;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -