Java Code Examples for org.apache.jena.riot.RDFLanguages#contentTypeToLang()

The following examples show how to use org.apache.jena.riot.RDFLanguages#contentTypeToLang() . 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: 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 2
Source File: BasedModelProvider.java    From Processor with Apache License 2.0 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 3
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 4
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 5
Source File: WorkflowBundleParser.java    From incubator-taverna-language with Apache License 2.0 4 votes vote down vote up
/**
 * Workaround for TAVERNA-71 to find annotations in WorkflowBundle
 * <p>
 * FIXME: The annotation links should instead be stored in the 
 * {@link Manifest} using taverna-robundle - see TAVERNA-71
 * 
 * @param wb
 * @throws IOException
 */
private void parseAnnotations(final WorkflowBundle wb) throws IOException {
	if (! wb.getAnnotations().isEmpty()) {
		// Assume already parsed
		return;
	}
	URITools uriTools = new URITools();		
	for (ResourceEntry resource : wb.getResources().listResources("annotation").values()) {
		Lang lang = RDFLanguages.contentTypeToLang(resource.getMediaType());
		if (lang == null) {
			// Not a semantic annotation
			continue;
		}
		//System.out.println(resource.getPath());
		//System.out.println(resource.getMediaType());
		Annotation ann = new Annotation();
		// Hackish way to generate a name from the annotation filename
		// as these typically are UUIDs
		String name = resource.getPath().replace("annotation/", "").replaceAll("\\..*", ""); // strip extension
		ann.setName(name);
		ann.setParent(wb);
		
		String path = resource.getPath();
		ann.setBody(URI.create("/" + path));		
		URI base = wb.getGlobalBaseURI().resolve(path);
		Model model = ModelFactory.createDefaultModel();			
		InputStream inputStream = resource.getUcfPackage().getResourceAsInputStream(path);
		if (inputStream == null) {
			// Not found!
			continue;
		}
		RDFDataMgr.read(model, inputStream, 
				base.toASCIIString(), lang);
		ResIterator subjs = model.listSubjects();			
		while (subjs.hasNext()) { 
			Resource r = subjs.next();
			//System.out.println(r);
			WorkflowBean b = uriTools.resolveUri(URI.create(r.getURI()), wb);
			//System.out.println(b);
			if (b != null) {
				ann.setTarget(b);
			}
			break;
		}
	}
}
 
Example 6
Source File: AnnotationTools.java    From incubator-taverna-language with Apache License 2.0 4 votes vote down vote up
public Dataset annotationDatasetFor(Child<?> workflowBean) {
	Dataset dataset = DatasetFactory.createMem();
	for (Annotation ann : scufl2Tools.annotationsFor(workflowBean)) {
		WorkflowBundle bundle = ann.getParent();
		URI annUri = uritools.uriForBean(ann);
		String bodyUri = bundle.getGlobalBaseURI().resolve(ann.getBody())
				.toASCIIString();

		if (ann.getBody().isAbsolute()) {
			logger.info("Skipping absolute annotation body URI: "
					+ ann.getBody());
			// TODO: Optional loading of external annotation bodies
			continue;
		}
		String path = ann.getBody().getPath();

		ResourceEntry resourceEntry = bundle.getResources()
				.getResourceEntry(path);
		if (resourceEntry == null) {
			logger.warning("Can't find annotation body: " + path);
			continue;
		}
		String contentType = resourceEntry.getMediaType();
		Lang lang = RDFLanguages.contentTypeToLang(contentType);
		if (lang == null) {
			lang = RDFLanguages.filenameToLang(path);
		}
		if (lang == null) {
			logger.warning("Can't find media type of annotation body: "
					+ ann.getBody());
			continue;
		}
		Model model = ModelFactory.createDefaultModel();
		try (InputStream inStream = bundle.getResources()
				.getResourceAsInputStream(path)) {
			RDFDataMgr.read(model, inStream, bodyUri, lang);
		} catch (IOException e) {
			logger.warning("Can't read annotation body: " + path);
			continue;
		}
		dataset.addNamedModel(annUri.toString(), model);
	}

	return dataset;
}
 
Example 7
Source File: RdfBulkUpdateRequestHandler.java    From SolRDF with Apache License 2.0 4 votes vote down vote up
@Override
public void load(
		final SolrQueryRequest request, 
		final SolrQueryResponse response,
		final ContentStream stream, 
		final UpdateRequestProcessor processor) throws Exception {
	
	// Default ContentStream implementation starts reading the stream and
	// if it starts with '<' then it assumes a content type of "application/xml", 
	// if it starts with '{' then it assumes a content type of "application/json" 			
	// This behaviour is wrong is SolRDF and maybe we need a custom ContentStream here
	// At the moment this is just a workaround:
	final String contentType = stream.getContentType() != null 
			&& !"application/xml".equals(stream.getContentType())
			&& !"application/json".equals(stream.getContentType()) 
				? stream.getContentType() 
				: request.getParams().get(UpdateParams.ASSUME_CONTENT_TYPE);
	
	log.debug(MessageCatalog._00094_BULK_LOADER_CT, contentType);			
				
	final Lang lang = RDFLanguages.contentTypeToLang(contentType);
	if (lang == null) {
		final String message = MessageFactory.createMessage(MessageCatalog._00095_INVALID_CT, contentType);
		log.error(message);							
		throw new SolrException(ErrorCode.BAD_REQUEST, message);
	}
	
	final ContentStreamLoader delegate = 
			(lang == Lang.NQ || lang == Lang.NQUADS || lang == Lang.TRIG)
				? quadsLoader
				: triplesLoader;
	
	log.debug(MessageCatalog._00096_SELECTED_BULK_LOADER, contentType, delegate);
	
	delegate.load(
			request, 
			response, 
			new ContentStream() {	
				@Override
				public InputStream getStream() throws IOException {
					return stream.getStream();
				}
				
				@Override
				public String getSourceInfo() {
					return stream.getSourceInfo();
				}
				
				@Override
				public Long getSize() {
					return stream.getSize();
				}
				
				@Override
				public Reader getReader() throws IOException {
					return stream.getReader();
				}
				
				@Override
				public String getName() {
					return stream.getName();
				}
				
				@Override
				public String getContentType() {
					return contentType;
				}
			}, 
		processor);
}
 
Example 8
Source File: RdfWriterImpl.java    From Server.Java with MIT License 4 votes vote down vote up
public RdfWriterImpl(Map<String, String> prefixes, HashMap<String, IDataSource> datasources, String mimeType) {
    super(prefixes, datasources);
    this.contentType = RDFLanguages.contentTypeToLang(mimeType);
    ARQ.init();
}