Java Code Examples for org.apache.jena.riot.Lang

The following are top voted examples for showing how to use org.apache.jena.riot.Lang. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alvisnlp   File: RDFProjector.java   Source Code and License 6 votes vote down vote up
private Model createModel(Logger logger) throws IOException {
		LoggingUtils.configureSilentLog4J();
		Model model = ModelFactory.createDefaultModel();
		model.setNsPrefixes(PrefixMapping.Standard);
		model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
		model.setNsPrefix("skos", "http://www.w3.org/2004/02/skos/core#");
		model.setNsPrefix("oboInOwl", "http://www.geneontology.org/formats/oboInOwl#");
		model.setNsPrefixes(prefixes);
		for (InputStream is : Iterators.loop(source.getInputStreams())) {
			logger.info("loading model from: " + source.getStreamName(is));
//			System.err.println("is = " + is);
//			model.read(is, null, Lang.RDFXML.toString());
			RDFDataMgr.read(model, is, Lang.RDFXML);
		}
		return model;
	}
 
Example 2
Project: RDF2PT   File: DBpediaGenderDictionary.java   Source Code and License 6 votes vote down vote up
public DBpediaGenderDictionary() {
	Model model = ModelFactory.createDefaultModel();

	Literal maleLit = model.createLiteral(VALUE_MALE, "en");
	Literal femaleLit = model.createLiteral(VALUE_FEMALE, "en");

	RDFDataMgr.read(model, getClass().getClassLoader().getResourceAsStream(GENDER_FILE_LOCATION), Lang.TURTLE);
	StmtIterator iter = model.listStatements(null, model.createProperty(GENDER_PROPERTY), (RDFNode) null);
	while(iter.hasNext()) {
		Statement st = iter.next();
		Literal lit = st.getObject().asLiteral();
		if(lit.equals(maleLit)) {
			male.add(st.getSubject().getURI());
		} else if(lit.equals(femaleLit)){
			female.add(st.getSubject().getURI());
		}
	}
}
 
Example 3
Project: ontonethub   File: ModelWriter.java   Source Code and License 6 votes vote down vote up
@Override
public void writeTo(Model t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
		MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
		throws IOException, WebApplicationException {
	
	Lang lang = null;
	
	if(mediaType.equals(KRFormat.N3_TYPE))
		lang = Lang.N3;
	else if(mediaType.equals(KRFormat.N_TRIPLE_TYPE))
		lang = Lang.NTRIPLES;
	else if(mediaType.equals(KRFormat.RDF_JSON_TYPE))
		lang = Lang.RDFJSON;
	else if(mediaType.equals(new MediaType("application", "json-ld")))
		lang = Lang.JSONLD;
	else lang = Lang.TURTLE;
	
	RDFDataMgr.write(entityStream, t, lang);
	
}
 
Example 4
Project: Squirrel   File: RDFAnalyzer.java   Source Code and License 6 votes vote down vote up
@Override
public Iterator<byte[]> analyze(CrawleableUri curi, File data, Sink sink) {
    FileInputStream fin = null;
    try {
        // First, try to get the language of the data
        Lang lang = null;
        String contentType = (String) curi.getData(HttpHeaders.CONTENT_TYPE);
        if (contentType != null) {
            lang = RDFLanguages.contentTypeToLang(contentType);
        } else {
            lang = RDFLanguages.filenameToLang(data.getName(), null);
        }
        FilterSinkRDF filtered = new FilterSinkRDF(curi, sink);
        RDFDataMgr.parse(filtered, data.getAbsolutePath(), lang);
    } catch (Exception e) {
        LOGGER.error("Exception while analyzing. Aborting.");
    } finally {
        IOUtils.closeQuietly(fin);
    }
    return collector.getUris(curi);
}
 
Example 5
Project: marklogic-contentpump   File: RDFReader.java   Source Code and License 6 votes vote down vote up
public boolean nextStreamingKeyValue() throws IOException, InterruptedException {
    if(rdfIter == null) return false;
    if (!rdfIter.hasNext() && collectionHash.size() == 0) {
        if(compressed) {
            hasNext = false;
            return false;
        } else {
            if (iterator!=null && iterator.hasNext()) {
                close();
                initStream(iterator.next());
            } else {
                hasNext = false;
                return false;
            }
        }
    }

    if (lang == Lang.NQUADS || lang == Lang.TRIG) {
        return nextStramingQuadKeyValue();
    } else {
        return nextStreamingTripleKeyValue();
    }
}
 
Example 6
Project: openml-rdf   File: VocabularyBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Build all properties for each class contained in a specification file.<br>
 * <br>
 * Specification file contains tab-separated rows as:<br>
 * [ClassName][TAB][JSON example URL]
 * 
 * @param specFile
 * @param outFile
 * @throws IOException 
 * @throws JSONException 
 */
public void buildAll(String specFile, String inFile, String outFile) throws JSONException, IOException {
	logger.info("Started.");
	String base = System.getProperty("user.dir") + "/";
	FileOutputStream file = new FileOutputStream(new File(base + outFile));
	logger.info("user.dir = "+base);
	logger.info("Opening RDF file: "+base + inFile);
	Model m = RDFDataMgr.loadModel(base + inFile, Lang.RDFXML);
	Scanner in = new Scanner(new File(specFile));
	while (in.hasNextLine()) {
		String[] line = in.nextLine().split("\t");
		build(line[0], line[1], m);
	}
	in.close();
	logger.info("Writing to file "+outFile+ "...");
	
	m.write(file);
	
	file.close();
	logger.info("Done.");
}
 
Example 7
Project: BENGAL   File: DBpediaGenderDictionary.java   Source Code and License 6 votes vote down vote up
public DBpediaGenderDictionary() {
	Model model = ModelFactory.createDefaultModel();

	Literal maleLit = model.createLiteral(VALUE_MALE, "en");
	Literal femaleLit = model.createLiteral(VALUE_FEMALE, "en");

	RDFDataMgr.read(model, getClass().getClassLoader().getResourceAsStream(GENDER_FILE_LOCATION), Lang.TURTLE);
	StmtIterator iter = model.listStatements(null, model.createProperty(GENDER_PROPERTY), (RDFNode) null);
	while (iter.hasNext()) {
		Statement st = iter.next();
		Literal lit = st.getObject().asLiteral();
		if (lit.equals(maleLit)) {
			male.add(st.getSubject().getURI());
		} else if (lit.equals(femaleLit)) {
			female.add(st.getSubject().getURI());
		}
	}
}
 
Example 8
Project: rdf-delta   File: TestRDFChangesGraph.java   Source Code and License 6 votes vote down vote up
private Graph replay() {
    IO.close(bout);
    final boolean DEBUG = false;
    
    if ( DEBUG ) {
        System.out.println("== Graph ==");
        RDFDataMgr.write(System.out, baseGraph, Lang.NQ);
        System.out.println("== Replay ==");
        String x = StrUtils.fromUTF8bytes(bout.toByteArray());
        System.out.print(x);
        System.out.println("== ==");
    }
    
    // A completely separate graph (different dataset)
    Graph graph2 = txnGraph();
    
    try(ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray())) {
        RDFPatchOps.applyChange(graph2, bin);
        if ( DEBUG ) {
            System.out.println("== Graph outcome ==");
            RDFDataMgr.write(System.out, graph2, Lang.NT);
            System.out.println("== ==");
        }
        return graph2;
    } catch (IOException ex) { IO.exception(ex); return null; }
}
 
Example 9
Project: rdf-delta   File: PatchLogServer.java   Source Code and License 6 votes vote down vote up
/** Build a ServletContextHandler. */
private static ServletContextHandler buildServletContext(String contextPath) {
    if ( contextPath == null || contextPath.isEmpty() )
        contextPath = "/" ;
    else if ( !contextPath.startsWith("/") )
        contextPath = "/" + contextPath ;
    ServletContextHandler context = new ServletContextHandler() ;
    context.setDisplayName("PatchLogServer") ;
    MimeTypes mt = new MimeTypes();
    addMimeType(mt, Lang.TTL);
    addMimeType(mt, Lang.NT);
    addMimeType(mt, Lang.TRIG);
    addMimeType(mt, Lang.NQ);
    addMimeType(mt, Lang.RDFXML);
    context.setMimeTypes(mt);
    ErrorHandler eh = new HttpErrorHandler();
    context.setErrorHandler(eh) ;
    return context ;
}
 
Example 10
Project: sparql-generate   File: TestBase.java   Source Code and License 6 votes vote down vote up
public TestBase(Logger log, File exampleDir, String name) {
    this.log = log;
    this.exampleDir = exampleDir;

    log.info("constructing with " + exampleDir);

    SPARQLGenerate.init();
            
    // read location-mapping
    Model conf = ModelFactory.createDefaultModel();
    conf.add(RDFDataMgr.loadModel(new File(exampleDir, "queryset/configuration.ttl").toString(), Lang.TTL));
    conf.add(RDFDataMgr.loadModel(new File(exampleDir, "documentset/configuration.ttl").toString(), Lang.TTL));

    // initialize stream manager
    SPARQLGenerateStreamManager sm = SPARQLGenerateStreamManager.makeStreamManager(new LocatorFileAccept(exampleDir.toURI().getPath()));
    sm.setLocationMapper(conf);
    SPARQLGenerate.setStreamManager(sm);
}
 
Example 11
Project: ASPG   File: viz.java   Source Code and License 6 votes vote down vote up
private static Model readRDF(String s) {
        Model model = ModelFactory.createDefaultModel();

        if (isPath(s)) {
//            System.out.println("Parsing file " + s);
            model.read(s);
        } else {
            try {
//                System.out.println("Parsing RDF string " + s);
                RDFDataMgr.read(model, new ByteArrayInputStream(s.getBytes("UTF-8")), Lang.TTL);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return model;
    }
 
Example 12
Project: phenopacket-reference-implementation   File: RdfGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Convert a PhenoPacket to RDF triples using the JSON-LD context
 * 
 * @param packet
 * @param base
 *            URI base for generated RDF; if `null` a UUID-based base will
 *            be used
 * @return model containing RDF triples
 * @throws JsonLdError
 * @throws JsonProcessingException
 */
public static Model toRdf(PhenoPacket packet, String base)
		throws JsonLdError, JsonProcessingException {
	PhenoPacket packetWithContext;
	if (packet.getContext() == null) {
		packetWithContext = PhenoPacket.newBuilder(packet)
                           .context(ContextUtil.defaultContextURI)
                           .build();
	} else {
		packetWithContext = packet;
	}
	Model rdfModel = ModelFactory.createDefaultModel();
	StringReader reader = new StringReader(
			JsonGenerator.render(packetWithContext));
	String baseToUse;
	if (base != null) {
		baseToUse = base;
	} else {
		String uuid = UUID.randomUUID().toString();
		baseToUse = "http://phenopackets.org/local/" + uuid + "/";
	}
	RDFDataMgr.read(rdfModel, reader, baseToUse, Lang.JSONLD);
	return rdfModel;
}
 
Example 13
Project: Source   File: SemanticBaseListener.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the {@link JenaBase} from the given {@link IFile}.
 * 
 * @param file
 *            the {@link IFile}
 * @return the {@link JenaBase} from the given {@link IFile} if nay, <code>null</code> otherwise
 */
private JenaBase getBaseFromFile(IFile file) {
	JenaBase res = null;

	final Lang lang = EXTENSION_TO_LANG.get(file.getFileExtension());
	if (lang != null) {
		try {
			final Model model = RDFDataMgr.loadModel(file.getLocation().toFile().getAbsolutePath(), lang);
			if (!model.isEmpty()) {
				res = new JenaBase(model, file.getFullPath().toString());
			}
			// CHECKSTYLE:OFF
		} catch (Exception e) {
			// CHECKSTYLE:ON
			Activator.getDefault().getLog().log(new Status(IStatus.WARNING, Activator.PLUGIN_ID,
					UNABLE_TO_LOAD_SEMANTIC_BASE_FROM + file.getLocation().toString(), e));
		}
	}

	return res;
}
 
Example 14
Project: Processor   File: BasedModelProvider.java   Source Code and License 6 votes vote down vote up
@Override
   public Model readFrom(Class<Model> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException
   {
if (log.isTraceEnabled()) log.trace("Reading Model with HTTP headers: {} MediaType: {}", httpHeaders, mediaType);

Model model = ModelFactory.createDefaultModel();	

       MediaType formatType = new MediaType(mediaType.getType(), mediaType.getSubtype()); // discard charset param        
       Lang lang = RDFLanguages.contentTypeToLang(formatType.toString());
       if (lang == null)
       {
           if (log.isErrorEnabled()) log.error("MediaType '{}' not supported by Jena", formatType);
           throw new NoReaderForLangException("MediaType not supported: " + formatType);
       }
if (log.isDebugEnabled()) log.debug("RDF language used to read Model: {}", lang);
       
       return read(model, entityStream, lang, getUriInfo().getBaseUri().toString());
   }
 
Example 15
Project: Processor   File: BasedModelProvider.java   Source Code and License 6 votes vote down vote up
@Override
   public void writeTo(Model model, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException
   {
if (log.isTraceEnabled()) log.trace("Writing Model with HTTP headers: {} MediaType: {}", httpHeaders, mediaType);

       MediaType formatType = new MediaType(mediaType.getType(), mediaType.getSubtype()); // discard charset param        
       Lang lang = RDFLanguages.contentTypeToLang(formatType.toString());
       if (lang == null)
       {
           if (log.isErrorEnabled()) log.error("MediaType '{}' not supported by Jena", formatType);
           throw new NoWriterForLangException("MediaType not supported: " + formatType);
       }
if (log.isDebugEnabled()) log.debug("RDF language used to read Model: {}", lang);
       
write(model, entityStream, lang, getUriInfo().getBaseUri().toString());
   }
 
Example 16
Project: incubator-taverna-language   File: RDFToManifest.java   Source Code and License 6 votes vote down vote up
protected static Model jsonLdAsJenaModel(InputStream jsonIn, URI base)
		throws IOException, RiotException {
	Model model = ModelFactory.createDefaultModel();
	
	ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
	try { 
		// TAVERNA-971: set context classloader so jarcache.json is consulted
		// even through OSGi
		Thread.currentThread().setContextClassLoader(RDFToManifest.class.getClassLoader());
		
		// Now we can parse the JSON-LD without network access
		RDFDataMgr.read(model, jsonIn, base.toASCIIString(), Lang.JSONLD);
	} finally { 
		// Restore old context class loader (if any)
		Thread.currentThread().setContextClassLoader(oldCl);
	}
	return model;
}
 
Example 17
Project: jena-inf-engine   File: DevRDFS.java   Source Code and License 6 votes vote down vote up
public static void expand() throws IOException {
    boolean combined = false ;
    String DIR = "testing/Inf" ;
    String DATA_FILE = "data.ttl" ;
    String VOCAB_FILE = "vocab.ttl" ;
    String RULES_FILE = DIR+"/rdfs-min.rules" ;

    Model vocab = RDFDataMgr.loadModel(VOCAB_FILE) ;
    Model data = RDFDataMgr.loadModel(DATA_FILE) ;
    
    String rules = FileUtils.readWholeFileAsUTF8(RULES_FILE) ;
    rules = rules.replaceAll("#[^\\n]*", "") ;

    InferenceSetupRDFS setup = new InferenceSetupRDFS(vocab, combined) ;
    
    Reasoner reasoner = new GenericRuleReasoner(Rule.parseRules(rules));
    InfModel m = ModelFactory.createInfModel(reasoner, vocab, data);
    
    // Expansion Graph
    Graph graphExpanded = Factory.createDefaultGraph() ;
    StreamRDF stream = StreamRDFLib.graph(graphExpanded) ;
    // Apply inferences.
    stream = new InferenceProcessorStreamRDF(stream, setup) ;
    sendToStream(data.getGraph(), stream) ;
    RDFDataMgr.write(System.out, graphExpanded, Lang.TTL) ;
}
 
Example 18
Project: Cetus   File: ExtendedCetusSurfaceFormExtractorTest.java   Source Code and License 6 votes vote down vote up
public static List<Document> loadDataset() {
    Model nifModel = ModelFactory.createDefaultModel();
    InputStream inputStream = ExtendedCetusSurfaceFormExtractorTest.class.getClassLoader().getResourceAsStream(
            DATASET_NAME);
    if (inputStream == null) {
        LOGGER.error("Couldn't get InputStream for the dataset. Returning null");
        return null;
    }
    try {
        LocalNIFParser parser = new LocalNIFParser(Lang.TTL);
        return parser.parseNIF(inputStream, nifModel);
    } catch (Exception e) {
        LOGGER.error("Exception while parsing dataset. Returning null", e);
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 19
Project: gerbil   File: DatahubNIFConfig.java   Source Code and License 6 votes vote down vote up
/**
 * We have to synchronize this method. Otherwise every experiment thread
 * would check the file and try to download the data or try to use the file
 * even the download hasn't been completed.
 */
@Override
protected synchronized Dataset loadDataset() throws Exception {
    String nifFile = GerbilConfiguration.getInstance().getString(DATAHUB_DATASET_FILE_PROPERTY_NAME) + getName();
    logger.debug("FILE {}", nifFile);
    File f = new File(nifFile);
    if (!f.exists()) {
        logger.debug("file {} does not exist. need to download", nifFile);
        String data = rt.getForObject(datasetUrl, String.class);
        Path path = Paths.get(nifFile);
        Files.createDirectories(path.getParent());
        Path file = Files.createFile(path);
        Files.write(file, data.getBytes(), StandardOpenOption.WRITE);
    }
    FileBasedNIFDataset dataset = new FileBasedNIFDataset(nifFile, getName(), Lang.TTL);
    dataset.init();
    return dataset;
}
 
Example 20
Project: gerbil   File: NIFDatasetLoadingTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    if (args.length != 1) {
        LOGGER.error(
                "Wrong usage. Need exactly one single argument. Correct usage: 'NIFDatasetLoadingTest <path-to-nif-file>'.");
        return;
    }
    LOGGER.info("Starting loading of given test dataset \"" + args[0] + "\"...");
    FileBasedNIFDataset dataset = new FileBasedNIFDataset(args[0], "Test dataset", Lang.TTL);
    try {
        dataset.init();
    } catch (GerbilException e) {
        LOGGER.error("Got an exception while trying to load the dataset.", e);
    }
    List<Document> documents = dataset.getInstances();
    LOGGER.info("Dataset size: {} documents", documents.size());
    ObjectIntOpenHashMap<String> annotationTypes;
    for (Document document : documents) {
        annotationTypes = listAnnotationTypes(document);
        LOGGER.info("Document {} annotation types: {}", document.getDocumentURI(), annotationTypes.toString());
    }
    IOUtils.closeQuietly(dataset);
    LOGGER.info("Finished loading of given test dataset.");
}
 
Example 21
Project: cobalt   File: JsonPlannerRequestDeserializer.java   Source Code and License 6 votes vote down vote up
private Mashup getMashup(final JsonObject obj) {
  final JsonValue val = obj.get(mashup);
  if (val == null || !(val instanceof JsonObject)) {
    throw new IllegalArgumentException("expecting a mashup description");
  }
  final JsonObject mashupObj = (JsonObject) val;
  final Lang lang;
  final String data;
  if (mashupObj.containsKey(mediaType)) {
    // XXX accept any supported language, although the request schema only allows a subset (application/rdf+json,
    // application/rdf+xml, text/turtle).
    lang = RDFLanguages.nameToLang(mashupObj.getString(mediaType));
    if (lang == null) {
      throw new IllegalArgumentException("unsupported media type");
    }
    data = mashupObj.getString(content);
    if (Strings.isNullOrEmpty(data)) {
      throw new IllegalArgumentException("expecting non-empty mashup content");
    }
  } else {
    data = stringify(mashupObj);
    lang = Lang.RDFJSON;
  }
  return parseMashup(data, lang);
}
 
Example 22
Project: SolRDF   File: RdfBulkUpdateRequestHandler.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
protected Map<String, ContentStreamLoader> createDefaultLoaders(final NamedList parameters) {
	final Map<String, ContentStreamLoader> registry = new HashMap<String, ContentStreamLoader>();
	final ContentStreamLoader loader = new RdfDataLoader();
	for (final Lang language : RDFLanguages.getRegisteredLanguages()) {
		registry.put(language.getContentType().toHeaderString(), loader);
	}
	registry.put(WebContent.contentTypeSPARQLUpdate, new Sparql11UpdateRdfDataLoader());

	if (log.isDebugEnabled()) {
		prettyPrint(registry);
	}
	
	return registry;
}
 
Example 23
Project: storm-query-operators   File: RDFStreamSpout.java   Source Code and License 6 votes vote down vote up
@Override
public void open(Map conf, TopologyContext context,	SpoutOutputCollector collector) {
	this.collector = collector;
	
	//Sink<Triple> output = new SinkTripleOutput(System.out, null, SyntaxLabels.createNodeToLabel());
	iterator = new PipedRDFIterator<Triple>();
       final PipedRDFStream<Triple> inputStream = new PipedTriplesStream(iterator);

	// PipedRDFStream and PipedRDFIterator need to be on different threads
       ExecutorService executor = Executors.newSingleThreadExecutor();

       // Create a runnable for our parser thread
       Runnable parser = new Runnable() {

           @Override
           public void run() {
               // Call the parsing process.
               RDFDataMgr.parse(inputStream, filePath, Lang.TURTLE);
           }
       };

       // Start the parser on another thread
       executor.submit(parser);
}
 
Example 24
Project: tbx2rdf   File: Main.java   Source Code and License 6 votes vote down vote up
/**
     * Standard conversion
     * This is the conversion invoked from the web service. 
     * Input file is read as a whole and kept in memory.
     */
    public static boolean convertSmallFile() {
        try {
            System.err.println("Doing the standard conversion (not a big file)\n");
            //READ TBX XML
            System.err.println("Opening file " + input_file + "\n");
            BufferedReader reader = new BufferedReader(new FileReader(input_file));
            TBX2RDF_Converter converter = new TBX2RDF_Converter();
            TBX_Terminology terminology = converter.convert(reader, mappings);
            //WRITE. This one has been obtained from 
            System.err.println("Writting output to " + output_file + "\n");
//            final Model model = terminology.getModel("file:" + output_file);
            final Model model = terminology.getModel(Main.DATA_NAMESPACE);           
            RDFDataMgr.write(new FileOutputStream(output_file), model, Lang.TURTLE);
            reader.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return false;
        }
        return true;

    }
 
Example 25
Project: odrlapi   File: Example1.java   Source Code and License 6 votes vote down vote up
/**
 * @param args No arguments are needed
 */
public static void main(String[] args) {

    //We create a policy. It can be anonymous, or it can receive a name (URI)
    Policy policy = new Policy("http://example.com/policy:0099");
    
    //We create a permission to read and write
    Permission permission = new Permission();
    permission.setTarget("http://example.com/asset:9898");
    permission.setActions(Arrays.asList(new Action("http://www.w3.org/ns/odrl/2/read"), new Action("http://www.w3.org/ns/odrl/2/write")));
    policy.addRule(permission);
    
    //We create the prohibition to distribute
    Prohibition prohibition = new Prohibition();
    prohibition.setTarget("http://example.com/asset:9898");
    prohibition.setActions(Arrays.asList(new Action("http://www.w3.org/ns/odrl/2/distribute")));
    policy.addRule(prohibition);
    
    //We serialize the policy
    String rdf=ODRLRDF.getRDF(policy,Lang.TTL);
    System.out.println(rdf);
    
}
 
Example 26
Project: odrlapi   File: Example5.java   Source Code and License 6 votes vote down vote up
/**
 * @param args No arguments are needed
 */
public static void main(String[] args) {
    
    //We create a policy. It can be anonymous, or it can receive a name (URI)
    Policy policy = new Policy("http://example.com/policy:0811");
    policy.setType(Policy.POLICY_TICKET); 


    Permission permission = new Permission();
    permission.setTarget("http://example.com/game:4589");
    permission.setActions(Arrays.asList(new Action("http://www.w3.org/ns/odrl/2/play")));

    Constraint c = new Constraint("");
    c.setOperator("http://www.w3.org/ns/odrl/2/lteq");
    c.setRightOperand("http://www.w3.org/ns/odrl/2/dateTime");
    c.setValue("2010-12-31");
    permission.setConstraints(Arrays.asList(c));
    policy.addRule(permission);
    
    
    //We serialize the policy
    String rdf=ODRLRDF.getRDF(policy,Lang.TTL);
    System.out.println(rdf);

}
 
Example 27
Project: odrlapi   File: Example4.java   Source Code and License 6 votes vote down vote up
/**
 * @param args No arguments are needed
 */
public static void main(String[] args) {

    //We create a policy. It can be anonymous, or it can receive a name (URI)
    Policy policy = new Policy("http://example.com/policy:4311");
    policy.setType(Policy.POLICY_REQUEST);
    //We create a permission to read and write
    Permission permission = new Permission();
    permission.setTarget("http://example.com/news:0099");
    permission.setActions(Arrays.asList(new Action("http://www.w3.org/ns/odrl/2/display")));
    permission.setAssignee(new Party("http://example.com/guest:0589"));
    policy.addRule(permission);

    
    //We serialize the policy
    String rdf=ODRLRDF.getRDF(policy,Lang.TTL);
    System.out.println(rdf);
    
}
 
Example 28
Project: Luzzu   File: SPARQLEndPointProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Prints the quality meta-data produced by this quality assessment process onto the standard output 
 */
@SuppressWarnings("unused")
private void generateQualityMetadata(){
	Resource res = ModelFactory.createDefaultModel().createResource(EnvironmentProperties.getInstance().getBaseURI());
	QualityMetadata md = new QualityMetadata(res, false);
	
	for(String className : this.metricInstances.keySet()){
		QualityMetric m = this.metricInstances.get(className);
		md.addMetricData(m);
	}
	
	try {
		RDFDataMgr.write(System.out, md.createQualityMetadata(), Lang.TRIG);
	} catch (MetadataException e) {
		logger.error(e.getMessage());
	}
}
 
Example 29
Project: Luzzu   File: MemoryProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Prints the quality meta-data produced by this quality assessment process onto the standard output 
 */
@SuppressWarnings("unused")
private void generateQualityMetadata(){
	Resource res = ModelFactory.createDefaultModel().createResource(EnvironmentProperties.getInstance().getBaseURI());
	QualityMetadata md = new QualityMetadata(res, false);
	
	for(String className : this.metricInstances.keySet()){
		QualityMetric m = this.metricInstances.get(className);
		md.addMetricData(m);
	}
	
	try {
		RDFDataMgr.write(System.out, md.createQualityMetadata(), Lang.TRIG);
	} catch (MetadataException e) {
		logger.error(e.getMessage());
	}
}
 
Example 30
Project: Luzzu   File: LargeStreamProcessor.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void reinitialiseProcessors(){
	if (!this.executor.isShutdown()){
		this.executor.shutdownNow();
	}
	
	Lang lang  = RDFLanguages.filenameToLang(datasetURI);
	
	if ((lang == Lang.NQ) || (lang == Lang.NQUADS)){
		this.iterator = new PipedRDFIterator<Quad>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
		this.rdfStream = new PipedQuadsStream((PipedRDFIterator<Quad>) iterator);
	} else {
		this.iterator = new PipedRDFIterator<Triple>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
		this.rdfStream = new PipedTriplesStream((PipedRDFIterator<Triple>) iterator);
	}
	
	
	this.isInitalised = true;
	
	this.executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	
	lstMetricConsumers = new ArrayList<MetricProcess>();
	for(String className : this.metricInstances.keySet()) {
		this.lstMetricConsumers.add(new MetricProcess(this.metricInstances.get(className)));
	}
}
 
Example 31
Project: Luzzu   File: LargeStreamProcessor.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void setUpProcess() {
		Lang lang  = RDFLanguages.filenameToLang(datasetURI);

		if ((lang == Lang.NQ) || (lang == Lang.NQUADS)){
			this.iterator = new PipedRDFIterator<Quad>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
			this.rdfStream = new PipedQuadsStream((PipedRDFIterator<Quad>) iterator);
		} else {
			this.iterator = new PipedRDFIterator<Triple>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
			this.rdfStream = new PipedTriplesStream((PipedRDFIterator<Triple>) iterator);
		}
		logger.debug("PipedRDFIterator initialized with: Buffer Size {}, Fair Lock {}, Poll Timeout {}, Max Polls {}", 
				rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
		
		this.isInitalised = true;
		
		try {
			this.loadMetrics();
		} catch (ExternalMetricLoaderException e) {
			logger.error(e.getLocalizedMessage());
		}
		
		this.executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
}
 
Example 32
Project: Luzzu   File: LargeStreamProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Prints the quality meta-data produced by this quality assessment process onto the standard output 
 */
@SuppressWarnings("unused")
private void generateQualityMetadata(){
	Resource res = ModelFactory.createDefaultModel().createResource(EnvironmentProperties.getInstance().getBaseURI());
	QualityMetadata md = new QualityMetadata(res, false);
	
	for(String className : this.metricInstances.keySet()){
		QualityMetric m = this.metricInstances.get(className);
		md.addMetricData(m);
	}
	
	try {
		RDFDataMgr.write(System.out, md.createQualityMetadata(), Lang.TRIG);
	} catch (MetadataException e) {
		logger.error(e.getMessage());
	}
}
 
Example 33
Project: Luzzu   File: ParallelSPARQLEndPointProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Prints the quality meta-data produced by this quality assessment process onto the standard output 
 */
@SuppressWarnings("unused")
private void generateQualityMetadata(){
	Resource res = ModelFactory.createDefaultModel().createResource(EnvironmentProperties.getInstance().getBaseURI());
	QualityMetadata md = new QualityMetadata(res, false);
	
	for(String className : this.metricInstances.keySet()){
		QualityMetric m = this.metricInstances.get(className);
		md.addMetricData(m);
	}
	
	try {
		RDFDataMgr.write(System.out, md.createQualityMetadata(), Lang.TRIG);
	} catch (MetadataException e) {
		logger.error(e.getMessage());
	}
}
 
Example 34
Project: Luzzu   File: GZNTMemoryProcessor.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void setUpProcess() {

	Lang lang  = RDFLanguages.filenameToLang(datasetURI);
	
	if ((lang == Lang.NQ) || (lang == Lang.NQUADS)){
		this.iterator = new PipedRDFIterator<Quad>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
		this.rdfStream = new PipedQuadsStream((PipedRDFIterator<Quad>) iterator);
	} else {
		this.iterator = new PipedRDFIterator<Triple>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
		this.rdfStream = new PipedTriplesStream((PipedRDFIterator<Triple>) iterator);
	}
	
	this.isInitalised = true;
	
	try {
		this.loadMetrics();
	} catch (ExternalMetricLoaderException e) {
		logger.error(e.getLocalizedMessage());
	}
	
	this.executor = Executors.newSingleThreadExecutor();
}
 
Example 35
Project: Luzzu   File: GZNTMemoryProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Prints the quality meta-data produced by this quality assessment process onto the standard output 
 */
@SuppressWarnings("unused")
private void generateQualityMetadata(){
	Resource res = ModelFactory.createDefaultModel().createResource(EnvironmentProperties.getInstance().getBaseURI());
	QualityMetadata md = new QualityMetadata(res, false);
	
	for(String className : this.metricInstances.keySet()){
		QualityMetric m = this.metricInstances.get(className);
		md.addMetricData(m);
	}
	
	try {
		RDFDataMgr.write(System.out, md.createQualityMetadata(), Lang.TRIG);
	} catch (MetadataException e) {
		logger.error(e.getMessage());
	}
}
 
Example 36
Project: Luzzu   File: StreamProcessor.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void reinitialiseProcessors(){
	if (!this.executor.isShutdown()){
		this.executor.shutdownNow();
	}
	
	Lang lang  = RDFLanguages.filenameToLang(datasetURI);
	
	if ((lang == Lang.NQ) || (lang == Lang.NQUADS)){
		this.iterator = new PipedRDFIterator<Quad>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
		this.rdfStream = new PipedQuadsStream((PipedRDFIterator<Quad>) iterator);
	} else {
		this.iterator = new PipedRDFIterator<Triple>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
		this.rdfStream = new PipedTriplesStream((PipedRDFIterator<Triple>) iterator);
	}
	
	this.isInitalised = true;
	
	this.executor = Executors.newSingleThreadExecutor();
	
	lstMetricConsumers = new ArrayList<MetricProcess>();
	for(String className : this.metricInstances.keySet()) {
		this.lstMetricConsumers.add(new MetricProcess(this.metricInstances.get(className)));
	}
}
 
Example 37
Project: Luzzu   File: StreamProcessor.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void setUpProcess() {
		Lang lang  = RDFLanguages.filenameToLang(datasetURI);

		if ((lang == Lang.NQ) || (lang == Lang.NQUADS)){
			this.iterator = new PipedRDFIterator<Quad>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
			this.rdfStream = new PipedQuadsStream((PipedRDFIterator<Quad>) iterator);
		} else {
			this.iterator = new PipedRDFIterator<Triple>(rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
			this.rdfStream = new PipedTriplesStream((PipedRDFIterator<Triple>) iterator);
		}
		logger.debug("PipedRDFIterator initialized with: Buffer Size {}, Fair Lock {}, Poll Timeout {}, Max Polls {}", 
				rdfIterBufferSize, rdfIterFairBufferLock, rdfIterPollTimeout, rdfIterMaxPolls);
		
		this.isInitalised = true;
		
		try {
			this.loadMetrics();
		} catch (ExternalMetricLoaderException e) {
			logger.error(e.getLocalizedMessage());
		}
		
		this.executor = Executors.newSingleThreadExecutor();
}
 
Example 38
Project: Luzzu   File: StreamProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Prints the quality meta-data produced by this quality assessment process onto the standard output 
 */
@SuppressWarnings("unused")
private void generateQualityMetadata(){
	Resource res = ModelFactory.createDefaultModel().createResource(EnvironmentProperties.getInstance().getBaseURI());
	QualityMetadata md = new QualityMetadata(res, false);
	
	for(String className : this.metricInstances.keySet()){
		QualityMetric m = this.metricInstances.get(className);
		md.addMetricData(m);
	}
	
	try {
		RDFDataMgr.write(System.out, md.createQualityMetadata(), Lang.TRIG);
	} catch (MetadataException e) {
		logger.error(e.getMessage());
	}
}
 
Example 39
Project: Luzzu   File: SparkStreamProcessor.java   Source Code and License 6 votes vote down vote up
public void setUpProcess() {
		Lang lang  = RDFLanguages.filenameToLang(datasetURI);

		if ((lang == Lang.NQ) || (lang == Lang.NQUADS)){
		} else {
		}
		
		this.isInitalised = true;
		
//		try {
//			this.loadMetrics();
//		} catch (ExternalMetricLoaderException e) {
//			logger.error(e.getLocalizedMessage());
//		}
		
		this.executor = Executors.newSingleThreadExecutor();
	}
 
Example 40
Project: Luzzu   File: SparkStreamProcessor.java   Source Code and License 6 votes vote down vote up
private void generateQualityMetadata(){
	Resource res = ModelFactory.createDefaultModel().createResource(this.datasetURI);
	
	QualityMetadata md = new QualityMetadata(res, false);
	
	for(String className : this.metricInstances.keySet()){
		QualityMetric m = this.metricInstances.get(className);
		md.addMetricData(m);
	}
	
	try {
		RDFDataMgr.write(System.out, md.createQualityMetadata(), Lang.TRIG);
	} catch (MetadataException e) {
		logger.error(e.getMessage());
	}
}