/**
 * Copyright © World Wide Web Consortium, (Massachusetts Institute of
 * Technology, Institut National de Recherche en Informatique et en
 * Automatique, Keio University).
 *
 * All Rights Reserved.
 *
 * Please see the full Copyright clause at
 * <http://www.w3.org/Consortium/Legal/copyright-software.html>
 *
 * ConsumerDemo class the demonstrates the use of the RDFConsumer interface
 *
 * @author      Dan Brickley <daniel.brickley@bristol.ac.uk>
 * @author      Janne Saarela <jsaarela@w3.org>
 */

package org.w3c.rdf;

import java.net.URL;

public class ConsumerDemo implements RDFConsumer
{
    /**
     * start is called when parsing of data is started
     *
     * @param	ds	DataSource starting its job
     */
    public void start (DataSource ds) {
	System.out.println("ConsumerDemo: incoming data from datasource: " + ds);
    }

    /**
     * end is called when parsing of data is ended
     *
     * @param	ds	DataSource finishing its job
     */
    public void end (DataSource ds){
	System.out.println("ConsumerDemo: end of data from datasource: " + ds);
    }

    /**
     * assert is called every time a new statement within
     * RDF data model is added
     *
     * @param	ds	DataSource who assert'ed this statement
     *                  (can be null if the assert'ing party
     *                   does not implement the DataSource interface)
     */
    public void assert (DataSource ds,
			Property predicate,
			Resource subject,
			RDFnode object) {

	/* 
	 * Echo what we're told to standard output channel 
	 * We could instead write this into an in-memory graph, store on disk,
	 * filter and pass to one or more other RDFConsumer objects
	 * depending on which DataSource etc etc
	 */
	
	System.out.print(predicate+" ( "+ subject +" , ");
	if (object instanceof Literal) { System.out.print("\""); }
	System.out.print( object.toString() );
	if (object instanceof Literal) { System.out.print("\""); }
	System.out.print(" )\n");
    }

    public static void main(String[] args) {
	String url = "example1.rdf";
	if (args.length > 0) {
	    url = args[(args.length-1)];
	}

	DataSource sirpac = new SiRPAC();

	try {
	    RDFSource data = new RDFSource (new URL(url) );
	    sirpac.setRDFSource(data);

	    System.out.println("Setting datasource URI to "+data);
	} catch (Exception e) { 

	    try {
		URL url2 = new URL ("file", null, args[0]);

		RDFSource data = new RDFSource (url2);
		sirpac.setRDFSource(data);
		
		System.out.println("Setting datasource file URI to "+data);
	    } catch (Exception e2) {
		System.err.println("Network or URL error: "+url);
	    }
	}
	
	RDFConsumer stdout = new ConsumerDemo();
	sirpac.register(stdout);
	try {
	    sirpac.fetchRDF();
	}
	catch (Exception e){
	    System.err.println("ConsumerDemo: error getting data from sirpac: "+e);
	}
    }
}
