org.apache.jena.riot.Lang Java Examples

The following examples show how to use org.apache.jena.riot.Lang. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RDFReader.java    From marklogic-contentpump with Apache License 2.0 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 #2
Source File: QueryOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Execute a verification. Writes to STDERR.
 *
 * @deprecated previously used as test method.
 * @param queriesResults a map from files to query results and output streams
 * @return true if there are any violations
 * @throws IOException on file issues
 */
@Deprecated
public static boolean execVerify(
    Map<File, Tuple<ResultSetRewindable, OutputStream>> queriesResults) throws IOException {
  boolean isViolation = false;
  for (File outFile : queriesResults.keySet()) {
    Tuple<ResultSetRewindable, OutputStream> resultAndStream = queriesResults.get(outFile);
    ResultSetRewindable results = resultAndStream.left();
    OutputStream outStream = resultAndStream.right();
    System.out.println(
        "Rule " + outFile.getCanonicalPath() + ": " + results.size() + " violation(s)");
    if (results.size() > 0) {
      isViolation = true;
      ResultSetMgr.write(System.err, results, Lang.CSV);
      results.reset();
    }
    System.err.print('\n');
    ResultSetMgr.write(outStream, results, Lang.CSV);
  }
  return isViolation;
}
 
Example #3
Source File: DataIDGenerator.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
public String createDataIDModel(List<ExperimentTaskStatus> results, String eID) {
    // If the experiment is not existing (== there are no results), return
    // an empty String
    if (results.size() == 0) {
        return "";
    }

    Model model = generateDataIDModel();

    addToModel(model, results, eID);

    // writing dataid result to output
    OutputStream o = new ByteArrayOutputStream();

    // creating json-ld output format
    RDFDataMgr.write(o, model, Lang.JSONLD);

    return o.toString();
}
 
Example #4
Source File: ResourceBuilder.java    From LodView with MIT License 6 votes vote down vote up
public String buildRDFResource(String IRI, String sparql, Lang lang, ConfigurationBean conf) throws Exception {
	String result = "empty content";
	Model model = ModelFactory.createDefaultModel();
	model.setNsPrefixes(conf.getPrefixes());

	SPARQLEndPoint se = new SPARQLEndPoint(conf, null, null);
	model = se.extractData(model, IRI, sparql, conf.getDefaultRawDataQueries());

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	RDFWriter rdfWriter = model.getWriter(lang.getName());
	rdfWriter.setProperty("showXMLDeclaration","true");
	rdfWriter.setProperty("relativeURIs","");

	rdfWriter.write(model, baos, conf.getIRInamespace());

	byte[] resultByteArray = baos.toByteArray();
	result = new String(resultByteArray);

	return result;
}
 
Example #5
Source File: QueryOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Tests a verify with no violations.
 *
 * @throws IOException on IO error
 * @throws OWLOntologyStorageException on ontology error
 */
@Test
public void testExecVerifyNoViolations() throws IOException, OWLOntologyStorageException {

  OWLOntology ontology = loadOntology("/simple.owl");
  Dataset dataset = QueryOperation.loadOntologyAsDataset(ontology);
  String allViolations = "SELECT ?s ?p ?o\n" + "WHERE {\n" + "    \n" + "}\n" + "LIMIT 0";

  ResultSet resultSet = QueryOperation.execQuery(dataset, allViolations);
  ResultSetRewindable copy = ResultSetFactory.copyResults(resultSet);
  int resultSize = copy.size();
  copy.reset();

  ByteArrayOutputStream testOut = new ByteArrayOutputStream();
  QueryOperation.writeResult(copy, Lang.CSV, testOut);

  boolean violations = false;
  if (resultSize > 0) {
    violations = true;
  }

  assertFalse(violations);
  assertEquals(1, Lists.newArrayList(testOut.toString().split("\n")).size());
}
 
Example #6
Source File: QueryOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Tests a verify with violations.
 *
 * @throws IOException on IO error
 * @throws OWLOntologyStorageException on ontology error
 */
@Test
public void testExecVerifyWithViolations() throws IOException, OWLOntologyStorageException {

  OWLOntology ontology = loadOntology("/simple.owl");
  Dataset dataset = QueryOperation.loadOntologyAsDataset(ontology);
  String allViolations =
      "SELECT ?s ?p ?o\n" + "WHERE {\n" + "    ?s ?p ?o .\n" + "}\n" + "LIMIT 10";

  ResultSet resultSet = QueryOperation.execQuery(dataset, allViolations);
  ResultSetRewindable copy = ResultSetFactory.copyResults(resultSet);
  int resultSize = copy.size();
  copy.reset();

  ByteArrayOutputStream testOut = new ByteArrayOutputStream();
  QueryOperation.writeResult(copy, Lang.CSV, testOut);

  boolean violations = false;
  if (resultSize > 0) {
    violations = true;
  }

  assertTrue(violations);
  assertEquals(7, Lists.newArrayList(testOut.toString().split("\n")).size());
}
 
Example #7
Source File: NIFDatasetLoadingTest.java    From gerbil with GNU Affero General Public License v3.0 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 #8
Source File: ExRIOT_out2.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
{
    Model model = RDFDataMgr.loadModel("D.ttl") ;
    System.out.println() ;
    System.out.println("#### ---- Write as TriG") ;
    System.out.println() ;
    // This wil be the default graph of the dataset written.
    RDFDataMgr.write(System.out, model, Lang.TRIG) ;
    
    // Loading Turtle as Trig reads into the default graph.
    Dataset dataset = RDFDataMgr.loadDataset("D.ttl") ;
    System.out.println() ;
    System.out.println("#### ---- Write as NQuads") ;
    System.out.println() ;
    RDFDataMgr.write(System.out, dataset, Lang.NQUADS) ;
}
 
Example #9
Source File: QueryOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Run a SELECT query over the union of named graphs in a dataset and write the result to a file.
 * Prints violations to STDERR.
 *
 * @param dataset The dataset to query over.
 * @param ruleName The name of the rule to verify.
 * @param query The SPARQL query string.
 * @param outputPath The file path to write to, if there are results
 * @param outputFormat The file format.
 * @throws IOException if output file is not found or query cannot be parsed
 * @return true if the are results (so file is written), false otherwise
 */
public static boolean runVerify(
    Dataset dataset, String ruleName, String query, Path outputPath, Lang outputFormat)
    throws IOException {
  if (outputFormat == null) {
    outputFormat = Lang.CSV;
  }
  ResultSetRewindable results = ResultSetFactory.copyResults(execQuery(dataset, query));
  if (results.size() == 0) {
    System.out.println("PASS Rule " + ruleName + ": 0 violation(s)");
    return false;
  } else {
    System.out.println("FAIL Rule " + ruleName + ": " + results.size() + " violation(s)");
    ResultSetMgr.write(System.err, results, Lang.CSV);
    results.reset();
    FileOutputStream csvFile = new FileOutputStream(outputPath.toFile());
    writeResult(results, outputFormat, csvFile);
    return true;
  }
}
 
Example #10
Source File: FormatService.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
public static String getFormatFromExtension(String filename) {
    String format = "TURTLE";
    try {
        // try to get if from Jena first
        String extension;
        Lang jenaLang = RDFLanguages.filenameToLang(filename);
        if (jenaLang != null) {
            extension = jenaLang.getFileExtensions().get(0);
        } else {
            int index = filename.lastIndexOf('.');
            extension = filename.substring(index + 1, filename.length());
        }
        SerializationFormat f = FormatService.getInputFormat(extension);
        if (f != null) {
            format = f.getName();
        }
    } catch (Exception e) {
        log.debug("No format found, using the default one", e);
        return "TURTLE";
    }
    return format;
}
 
Example #11
Source File: RDFStar2RDFTest.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
protected Graph convertAndLoadIntoGraph( String filename )
{
    final String fullFilename = getClass().getResource("/TurtleStar/"+filename).getFile();
    String result;
    try( ByteArrayOutputStream os = new ByteArrayOutputStream() ) {
        new RDFStar2RDF().convert(fullFilename, os);
        result = os.toString();
    }
    catch ( IOException e ) {
        fail( "Closing the output stream failed: " + e.getMessage() );
        return null;
    }

	final StringReader reader = new StringReader(result);
       final Graph g = ModelFactory.createDefaultModel().getGraph();
       final StreamRDF dest = StreamRDFLib.graph(g);

       RDFParser.create()
                .source(reader)
                .lang(Lang.TURTLE)
                .parse(dest);

	return g;
}
 
Example #12
Source File: UpdateReadFromFile.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String []args)
{
    // Create an empty GraphStore (has an empty default graph and no named graphs) 
    Dataset dataset = DatasetFactory.createTxnMem() ;
    
    // ---- Read and update script in one step.
    UpdateAction.readExecute("update.ru", dataset) ;
    
    // ---- Reset.
    UpdateAction.parseExecute("DROP ALL", dataset) ;
    
    // ---- Read the update script, then execute, in separate two steps
    UpdateRequest request = UpdateFactory.read("update.ru") ;
    UpdateAction.execute(request, dataset) ;

    // Write in debug format.
    System.out.println("# Debug format");
    SSE.write(dataset) ;
    
    System.out.println();
    
    System.out.println("# N-Quads: S P O G") ;
    RDFDataMgr.write(System.out, dataset, Lang.NQUADS) ;
}
 
Example #13
Source File: UpdateProgrammatic.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String []args)
{
    Dataset dataset = DatasetFactory.createTxnMem() ;
    
    UpdateRequest request = UpdateFactory.create() ;
    
    request.add(new UpdateDrop(Target.ALL)) ;
    request.add(new UpdateCreate("http://example/g2")) ;
    request.add(new UpdateLoad("file:etc/update-data.ttl", "http://example/g2")) ;
    UpdateAction.execute(request, dataset) ;
    
    System.out.println("# Debug format");
    SSE.write(dataset) ;
    
    System.out.println();
    
    System.out.println("# N-Quads: S P O G") ;
    RDFDataMgr.write(System.out, dataset, Lang.NQUADS) ;
}
 
Example #14
Source File: BasedModelProvider.java    From Processor with Apache License 2.0 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 #15
Source File: DatahubNIFConfig.java    From gerbil with GNU Affero General Public License v3.0 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 #16
Source File: SparqlDataSourceTest.java    From Server.Java with MIT License 6 votes vote down vote up
/**
 *
 * @throws Exception
 */
@BeforeClass
public static void setUpClass() throws Exception {
    final String typeName = "SparqlSourceType";
    if ( ! DataSourceTypesRegistry.isRegistered(typeName) ) {
        DataSourceTypesRegistry.register( typeName,
                                          new SparqlDataSourceType() );
    }

    String tmpdir = System.getProperty("java.io.tmpdir");
    jena = new File(tmpdir, "ldf-sparql-test");
    jena.mkdir();
    
    dataset = TDBFactory.createDataset(jena.getAbsolutePath());

    Model model = dataset.getDefaultModel();
    InputStream in = ClassLoader.getSystemResourceAsStream("demo.nt");
    RDFDataMgr.read(model, in, Lang.NTRIPLES);

    // Dynamically-generated port comes from pom.xml configuration: build-helper-maven-plugin
    int fusekiPort = Integer.parseInt(System.getProperty("fuseki.port"));

    // Create Fuseki, loaded with the test dataset
    fuseki = FusekiServer.create().setPort(fusekiPort).add("/ds", dataset).build();
    fuseki.start();

    // Everything is in place, now create the LDF datasource                
    JsonObject config = createConfig("sparql test", "sparql test",
                                     typeName);
    
    JsonObject settings = new JsonObject();
    settings.addProperty("endpoint", "http://localhost:" + fusekiPort + "/ds");
    config.add("settings", settings);

    setDatasource(DataSourceFactory.create(config));
}
 
Example #17
Source File: TestRDFChangesGraph.java    From rdf-delta with Apache License 2.0 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 #18
Source File: ResourceBuilder.java    From LodView with MIT License 6 votes vote down vote up
public String buildRDFResource(String IRI, Model m, Lang lang, ConfigurationBean conf) throws Exception {
	String result = "empty content";
	Model model = ModelFactory.createDefaultModel();
	model.setNsPrefixes(conf.getPrefixes());

	SPARQLEndPoint se = new SPARQLEndPoint(conf, null, null);
	model = se.extractLocalData(model, IRI, m, conf.getDefaultRawDataQueries());

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	RDFWriter rdfWriter = model.getWriter(lang.getName());
	rdfWriter.setProperty("showXMLDeclaration","true");
	rdfWriter.setProperty("relativeURIs","");

	rdfWriter.write(model, baos, conf.getIRInamespace());
	rdfWriter.setProperty("showXMLDeclaration","true");
	rdfWriter.setProperty("relativeURIs","");

	byte[] resultByteArray = baos.toByteArray();
	result = new String(resultByteArray);

	return result;
}
 
Example #19
Source File: JenaIOService.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Override
public Stream<Triple> read(final InputStream input, final RDFSyntax syntax, final String base) {
    requireNonNull(input, "The input stream may not be null!");
    requireNonNull(syntax, "The syntax value may not be null!");

    try {
        final org.apache.jena.graph.Graph graph = createDefaultGraph();
        final Lang lang = JenaCommonsRDF.toJena(syntax).orElseThrow(() ->
                new TrellisRuntimeException("Unsupported RDF Syntax: " + syntax.mediaType()));

        RDFParser.source(input).lang(lang).base(base).parse(graph);

        // Check the graph for any new namespace definitions
        final Set<String> namespaces = new HashSet<>(nsService.getNamespaces().values());
        graph.getPrefixMapping().getNsPrefixMap().forEach((prefix, namespace) -> {
            if (shouldAddNamespace(namespaces, namespace, base)) {
                LOGGER.debug("Setting prefix ({}) for namespace {}", prefix, namespace);
                nsService.setPrefix(prefix, namespace);
            }
        });
        return JenaCommonsRDF.fromJena(graph).stream().map(Triple.class::cast);
    } catch (final RiotException | AtlasException | IllegalArgumentException ex) {
        throw new TrellisRuntimeException(ex);
    }
}
 
Example #20
Source File: ContextUtils.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
public static void loadGraph(Context context, String sourceURI, String baseURI, StreamRDF dest) {
	if(getDataset(context).containsNamedModel(sourceURI)) {
		final Model model = getDataset(context).getNamedModel(sourceURI);
		StreamRDFOps.sendGraphToStream(model.getGraph(), dest);
		return;
	}
	if(!isRootContext(context)) {
		Context parentContext = (Context) context.get(PARENT_CONTEXT);
		loadGraph(parentContext, sourceURI, baseURI, dest);
		return;
	}
	final SPARQLExtStreamManager sm = (SPARQLExtStreamManager) context.get(SysRIOT.sysStreamManager);
	final String acceptHeader = "text/turtle;q=1.0,application/rdf+xml;q=0.9,*/*;q=0.1";
	final LookUpRequest request = new LookUpRequest(sourceURI, acceptHeader);
	try (TypedInputStream tin = sm.open(request);) {
		if(tin == null) {
			LOG.warn("Could not locate graph " + request);
			return;
		}
		Lang lang = RDFLanguages.contentTypeToLang(tin.getMediaType());
		RDFParser.create().source(tin).base(baseURI).context(context).lang(lang).parse(dest);
	} catch (RiotException ex) {
		LOG.warn("Error while loading graph " + sourceURI, ex);
	}
}
 
Example #21
Source File: RdflintParserRdfxmlTest.java    From rdflint with MIT License 6 votes vote down vote up
@Test
public void testValidator() throws Exception {
  String rootPath = getTestRdfsPath() + "rdfxml/needtrim.rdf";

  List<RdfValidator> validators = new LinkedList<>();
  validators.add(new TrimValidator());
  Graph g = Factory.createGraphMem();
  List<LintProblem> problems = new LinkedList<>();
  RdflintParser.source(Paths.get(rootPath))
      .lang(Lang.RDFXML)
      .base("http://example.com/")
      .validators(validators)
      .parse(g, problems);

  assertFalse(g.size() == 0);
  g.close();
  assertFalse(problems.size() == 0);
  assertEquals(
      "com.github.imas.rdflint.validator.impl.needTrimLiteral",
      problems.get(0).getKey());
}
 
Example #22
Source File: RdflintParserRdfxmlTest.java    From rdflint with MIT License 6 votes vote down vote up
@Test
public void testInvalidWhitespace() throws Exception {
  String rootPath = getTestRdfsPath() + "rdfxml/invalid_whitespace.rdf";

  Graph g = Factory.createGraphMem();
  List<LintProblem> problems = new LinkedList<>();
  RdflintParser.source(Paths.get(rootPath))
      .lang(Lang.RDFXML)
      .base("http://example.com/")
      .parse(g, problems);

  g.close();
  assertFalse(problems.size() == 0);
  assertEquals(
      "com.github.imas.rdflint.validator.impl.parseWarning",
      problems.get(0).getKey());
  System.out.println(problems.get(0).getArguments()[0]);
}
 
Example #23
Source File: RdflintParserRdfxmlTest.java    From rdflint with MIT License 6 votes vote down vote up
@Test
public void testInvalid() throws Exception {
  String rootPath = getTestRdfsPath() + "rdfxml/invalid.rdf";

  Graph g = Factory.createGraphMem();
  List<LintProblem> problems = new LinkedList<>();
  RdflintParser.source(Paths.get(rootPath))
      .lang(Lang.RDFXML)
      .base("http://example.com/")
      .parse(g, problems);

  g.close();
  assertFalse(problems.size() == 0);
  assertEquals(
      "com.github.imas.rdflint.validator.impl.parseWarning",
      problems.get(0).getKey());
  System.out.println(problems.get(0).getArguments()[0]);
}
 
Example #24
Source File: RdfBulkUpdateRequestHandler.java    From SolRDF with Apache License 2.0 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 #25
Source File: RdflintParserTurtleTest.java    From rdflint with MIT License 6 votes vote down vote up
@Test
public void testValidator() throws Exception {
  String rootPath = getTestRdfsPath() + "turtle/needtrim.ttl";

  List<RdfValidator> validators = new LinkedList<>();
  validators.add(new TrimValidator());
  Graph g = Factory.createGraphMem();
  List<LintProblem> problems = new LinkedList<>();
  RdflintParser.source(Paths.get(rootPath))
      .lang(Lang.TURTLE)
      .validators(validators)
      .parse(g, problems);

  assertFalse(g.size() == 0);
  g.close();
  assertFalse(problems.size() == 0);
  assertEquals(
      "com.github.imas.rdflint.validator.impl.needTrimLiteral",
      problems.get(0).getKey());
}
 
Example #26
Source File: RDFToManifest.java    From incubator-taverna-language with Apache License 2.0 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 #27
Source File: LangUtilsTest.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@Test
void should_accept_turtle() {

    assertEquals(Lang.TURTLE, LangUtils.forName("ttl"));
    assertEquals(Lang.TURTLE, LangUtils.forName("TTL"));
    assertEquals(Lang.TURTLE, LangUtils.forName("turtle"));
    assertEquals(Lang.TURTLE, LangUtils.forName("TURTLE"));
    assertEquals(Lang.TURTLE, LangUtils.forName("n3"));
    assertEquals(Lang.TURTLE, LangUtils.forName("N3"));
}
 
Example #28
Source File: ModelImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Resolves an RDF2Go {@Link Syntax} to a Jena {@link Lang}.
 * 
 * @param syntax
 *            The RDF2Go Syntax to resolve.
 * @return A {@link Lang} for the specified syntax.
 * @throws SyntaxNotSupportedException
 *             When the Syntax could not be resolved to a {@link Lang}.
 */
public static Lang getJenaLang(Syntax syntax) throws SyntaxNotSupportedException {
    for (String mimeType : syntax.getMimeTypes()) {
        Lang lang = RDFLanguages.contentTypeToLang(mimeType);
        if (lang != null) {
            return lang;
        }
    }
    throw new SyntaxNotSupportedException("This version of Jena seems to have no "
            + "support for " + syntax);
}
 
Example #29
Source File: ModelSetImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
	public void writeTo(OutputStream out, Syntax syntax) throws IOException,
			ModelRuntimeException, SyntaxNotSupportedException {
		
		if (syntax == null) {
			throw new NullPointerException("syntax may not be null");
		}
		
		Lang jenaLang = getJenaLang(syntax);

//		if (RDFLanguages.isTriples(jenaLang)) {
//			/*
//			 * NB: Writing a ModelSet to a triple serialization loses the
//			 * context of any quads if present.
//			 */
//			Iterator<Model> it = this.getModels();
//			while (it.hasNext()) {
//				Model model = it.next();
//				model.writeTo(out, syntax);
//			}
//			this.getDefaultModel().writeTo(out, syntax);
//		}
// FIXME stuehmer: write unit test to see if this can be removed
//		else {
		try {
			RDFDataMgr.write(out, this.dataset, jenaLang);
		}
		catch (RiotException e) {
			throw new SyntaxNotSupportedException(
					"error writing syntax " + syntax + ": " + e.getMessage());
		}
	}
 
Example #30
Source File: Config.java    From fcrepo-import-export with Apache License 2.0 5 votes vote down vote up
/**
 * Get extension for the RDF language provided
 *
 * @param language RDF language mimetype
 * @return string of file extension
 */
private static String getRDFExtension(final String language) {
    final Lang lang = contentTypeToLang(language);
    if (lang == null) {
        throw new RuntimeException(language + " is not a recognized RDF language");
    }

    return "." + lang.getFileExtensions().get(0);

}