001/*
002 * #%L
003 * HAPI FHIR - Core Library
004 * %%
005 * Copyright (C) 2014 - 2025 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.util.rdf;
021
022import org.apache.commons.io.IOUtils;
023import org.apache.commons.io.output.WriterOutputStream;
024import org.apache.jena.rdf.model.Model;
025import org.apache.jena.rdf.model.ModelFactory;
026import org.apache.jena.riot.Lang;
027import org.apache.jena.riot.RDFDataMgr;
028
029import java.io.IOException;
030import java.io.InputStreamReader;
031import java.io.OutputStream;
032import java.io.Reader;
033import java.io.StringReader;
034import java.io.Writer;
035
036public class RDFUtil {
037
038        public static Model initializeRDFModel() {
039                // Create the model
040                return ModelFactory.createDefaultModel();
041        }
042
043        public static Model readRDFToModel(final Reader reader, final Lang lang) throws IOException {
044                // Jena has removed methods that use a generic Reader.
045                // reads only from InputStream, StringReader, or String
046                // Reader must be explicitly cast to StringReader
047                Model rdfModel = initializeRDFModel();
048                if (reader instanceof StringReader) {
049                        RDFDataMgr.read(rdfModel, (StringReader) reader, null, lang);
050                } else if (reader instanceof InputStreamReader) {
051                        String content = IOUtils.toString(reader);
052                        RDFDataMgr.read(rdfModel, new StringReader(content), null, lang);
053                }
054                return rdfModel;
055        }
056
057        public static void writeRDFModel(Writer writer, Model rdfModel, Lang lang) throws IOException {
058                // Jena has removed methods that use a generic Writer.
059                // Writer must be explicitly cast to StringWriter or OutputStream
060                // in order to hit a write method.
061                OutputStream outputStream = WriterOutputStream.builder()
062                                .setWriter(writer)
063                                .setCharset("UTF-8")
064                                .get();
065                RDFDataMgr.write(outputStream, rdfModel, lang);
066        }
067}