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

📄 queryresultsformatter.java

📁 Java实现的数据库和RDF之间的转换程序。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * (c) Copyright 2001, 2002, 2003, Hewlett-Packard Development Company, LP
 * [See end of file]
 */
package rdfquery;
import java.util.* ;
import java.io.* ;

import com.hp.hpl.jena.rdf.model.* ;
import com.hp.hpl.jena.vocabulary.* ;

import com.hp.hpl.jena.rdql.* ;
import com.hp.hpl.jena.vocabulary.ResultSet ;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/** <p>Takes a QueryResult object and returns formatted (in various ways)
 *  Useful for the scripting interface.
 *  May help for display in other contexts.</p>
 *
 *  <p>Note: this is compute intensive and memory intensive.
 *  It needs to read all the results first (all the results are now in-memory - not kept here)
 *  in order to find things like the maximum length of a column value; then it needs
 *  to pass over the results again, turning them into Strings again, in order to return them.
 *  </p>
 *  <p>We prefer slow and less memory intensive because it is more rebust for scripting.</p>
 *
 *  Don't keep QueryResultsFormatter's around unnecessarily!
 *
 * @author   Andy Seaborne
 * @version  $Id: QueryResultsFormatter.java,v 1.13 2004/01/20 14:27:43 andy_seaborne Exp $
 */

public class QueryResultsFormatter
{
    static Log log = LogFactory.getLog(QueryResultsFormatter.class);

    QueryResults queryResults ;
    QueryResultsMem all = null ;
    int numRows = -2 ;
    int numCols = -2 ;
    int colWidths[] = null ;
    static final String notThere = "<<unset>>" ;

    public static final String resultsNamespace = "http://jena.hpl.hp.com/2003/03/queryResults#" ;

    /** Create a formatter for a QueryResults object */

    public QueryResultsFormatter(QueryResults qresults)
    {
        queryResults = qresults ;
    }

    /** How wide is the result table */
    public int numColumns() { return queryResults.getResultVars().size() ; }

    /** How deep is the result table.  Negative implies unknown */
    public int numRows() { return numRows ; }

    private void colWidths()
    {
    	if ( all == null )
    		all = new QueryResultsMem(queryResults) ;

        numCols = queryResults.getResultVars().size() ;
        numRows = 0 ;
        colWidths = new int[numCols] ;

        // Widths at least that of the variable name.  Assumes we will print col headings.
        for ( int i = 0 ; i < numCols ; i++ )
            colWidths[i] = ((String)queryResults.getResultVars().get(i)).length() ;

        // Preparation pass : find the maximum width for each column
        for ( ; all.hasNext() ; )
        {
            numRows++ ;
            ResultBinding env = (ResultBinding)all.next() ;
            int col = -1 ;
            for ( Iterator iter = queryResults.getResultVars().iterator() ; iter.hasNext() ; )
            {
                col++ ;
                String rVar = (String)iter.next() ;
                String s = getVarAsString(env, rVar) ;
                if ( colWidths[col] < s.length() )
                    colWidths[col] = s.length() ;
            }
        }
        all.reset() ;
    }

    /** Forcefully clearup.
     *  As results might have been read into memory, this operation signals
     *  intermediate data is no longer needed.
     */
    public void close()
    {
        queryResults.close() ;
        queryResults = null ;
        all = null ;
        colWidths = null ;
    }

    /** Encode the result set as RDF.
     * @return Model       Model contains the results
     */

    public Model toModel()
    {
        Model m = ModelFactory.createDefaultModel() ;
        asRDF(m) ;
        return m ;
    }

    /** Encode the result set as RDF in the model provided.
     *
     * @param model     The place where to put the RDF.
     * @return Resource The resource for the result set.
     */

    public Resource asRDF(Model model)
    {
        Resource results = model.createResource() ;
        results.addProperty(RDF.type, ResultSet.ResultSet) ;

        for (Iterator iter = queryResults.getResultVars().iterator(); iter.hasNext();)
        {
            String vName = (String) iter.next();
            results.addProperty(ResultSet.resultVariable, vName) ;
        }

        int count = 0 ;
        for ( Iterator solutionsIter = queryResults ; solutionsIter.hasNext() ; )
        {
            count++ ;
            ResultBinding env = (ResultBinding)solutionsIter.next() ;
            Resource thisSolution = model.createResource() ;
            results.addProperty(ResultSet.solution, thisSolution) ;
            for (Iterator iter = queryResults.getResultVars().iterator() ; iter.hasNext() ; )
            {
                Resource thisBinding = model.createResource() ;
                String rVar = (String)iter.next() ;
                Object tmp = env.get(rVar) ;
                RDFNode n = null ;
                if ( tmp == null )
                    // This variable was not found in the results.
                    // Encode the result set with an explicit "not defined"
                    n = ResultSet.undefined ;
                else if ( ! (tmp instanceof RDFNode) )
                {
                    log.warn("Class wrong: "+tmp.getClass().getName()) ;
                    continue ;
                }
                else
                    n = (RDFNode)env.get(rVar) ;

                thisBinding.addProperty(ResultSet.variable, rVar) ;
                thisBinding.addProperty(ResultSet.value, n) ;
                thisSolution.addProperty(ResultSet.binding, thisBinding) ;
            }
        }
        queryResults.close() ;
        results.addProperty(ResultSet.size, count) ;
        return results ;
    }



    // Generalise: there are two algorithms : the one pass and the two pass

    /** Write out a compact form.  This encodes all the information is a vaguely
     *  readable way but is suitable for reading in again.  Used for testing.
     */


	public void dump(PrintWriter pw, boolean format)
	{
		if (queryResults.getResultVars().size() == 0)
		{
			pw.println("# ==== No variables ====");
			pw.flush();
			return;
		}
		else
		{
			pw.println("# Variables:");
			for (Iterator iter = queryResults.getResultVars().iterator(); iter.hasNext();)
			{
				String vName = (String) iter.next();
				pw.print("?" + vName+" ");
			}
			pw.println(".") ;
			pw.println("# Data:");
			pw.flush() ;
		}

		if (format)
			dumpAligned(pw);
		else
			dumpRaw(pw);
	}

    // One pass algorithm
    private void dumpRaw(PrintWriter pw)
    {
        numCols = queryResults.getResultVars().size() ;
        for ( Iterator tableIter = queryResults ; tableIter.hasNext() ; )
        {
            ResultBinding env = (ResultBinding)tableIter.next() ;
            for (Iterator iter = queryResults.getResultVars().iterator() ; iter.hasNext() ; )
            {
                String rVar = (String)iter.next() ;
                String s = getVarAsString(env, rVar) ;
                pw.print("?") ;
                pw.print(rVar) ;
                pw.print(" ");
                pw.print(s);
                pw.print(" ");
            }
            pw.println(".") ;
        }
        queryResults.close() ;
    }

    // Dump formated : columns padded for readability.
    // Requires reading all the data into memory - its a two pass algorithm.
    private void dumpAligned(PrintWriter pw)
    {
    	if ( all == null )
    		all = new QueryResultsMem(queryResults) ;

        if ( colWidths == null )
            colWidths() ;

        String row[] = new String[numCols] ;
        int lineWidth = 0 ;
        for ( int col = 0 ; col < numCols ; col++ )
        {
            String rVar = (String)queryResults.getResultVars().get(col) ;
            row[col] = rVar ;
            lineWidth += colWidths[col] ;
        }

        for ( Iterator tableIter = all ; tableIter.hasNext() ; )
        {
            ResultBinding env = (ResultBinding)tableIter.next() ;
            for ( int col = 0 ; col < numCols ; col++ )
            {

⌨️ 快捷键说明

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