001/*
002 * Licensed to DuraSpace under one or more contributor license agreements.
003 * See the NOTICE file distributed with this work for additional information
004 * regarding copyright ownership.
005 *
006 * DuraSpace licenses this file to you under the Apache License,
007 * Version 2.0 (the "License"); you may not use this file except in
008 * compliance with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.fcrepo.http.commons.responses;
019
020import static java.util.stream.Stream.of;
021import static com.google.common.util.concurrent.Futures.addCallback;
022import static javax.ws.rs.core.MediaType.valueOf;
023import static org.apache.jena.datatypes.xsd.XSDDatatype.XSDdateTime;
024import static org.apache.jena.graph.NodeFactory.createLiteral;
025import static org.apache.jena.graph.NodeFactory.createURI;
026import static org.apache.jena.graph.Triple.create;
027import static org.apache.jena.rdf.model.ModelFactory.createDefaultModel;
028import static org.apache.jena.rdf.model.ResourceFactory.createProperty;
029import static org.apache.jena.rdf.model.ResourceFactory.createResource;
030import static org.apache.jena.rdf.model.ResourceFactory.createTypedLiteral;
031import static org.fcrepo.http.commons.domain.RDFMediaType.TURTLE_TYPE;
032import static org.junit.Assert.assertTrue;
033import static org.mockito.Mockito.mock;
034import static org.slf4j.LoggerFactory.getLogger;
035
036import java.io.ByteArrayInputStream;
037import java.io.ByteArrayOutputStream;
038import java.io.IOException;
039import java.io.InputStream;
040import java.io.OutputStream;
041import java.util.HashMap;
042import java.util.Map;
043import java.util.stream.Stream;
044
045import javax.jcr.Session;
046import javax.ws.rs.WebApplicationException;
047import javax.ws.rs.core.MediaType;
048
049import com.google.common.util.concurrent.FutureCallback;
050import org.apache.jena.rdf.model.RDFNode;
051import org.apache.jena.riot.RiotException;
052import org.fcrepo.kernel.api.rdf.DefaultRdfStream;
053import org.fcrepo.kernel.api.RdfStream;
054import org.junit.Before;
055import org.junit.Test;
056import org.mockito.Mock;
057import org.mockito.stubbing.Answer;
058import org.slf4j.Logger;
059
060import org.apache.jena.graph.Node;
061import org.apache.jena.graph.Triple;
062import org.apache.jena.rdf.model.Model;
063
064import org.junit.runner.RunWith;
065import org.mockito.runners.MockitoJUnitRunner;
066
067/**
068 * <p>RdfStreamStreamingOutputTest class.</p>
069 *
070 * @author ajs6f
071 */
072@RunWith(MockitoJUnitRunner.class)
073public class RdfStreamStreamingOutputTest {
074
075    private RdfStreamStreamingOutput testRdfStreamStreamingOutput;
076
077    private static final Triple triple = create(createURI("info:testSubject"),
078            createURI("info:testPredicate"), createURI("info:testObject"));
079
080    @Mock
081    private Node mockNode;
082
083    private final RdfStream testRdfStream = new DefaultRdfStream(triple.getSubject(), of(triple));
084
085    private final Map<String, String> testNamespaces = new HashMap<>();
086
087    @Mock
088    private RdfStream mockRdfStream;
089
090    @Mock
091    private Session mockSession;
092
093    private final MediaType testMediaType = valueOf("application/rdf+xml");
094
095    private static final Logger LOGGER =
096            getLogger(RdfStreamStreamingOutputTest.class);
097
098    @Before
099    public void setUp() {
100        testRdfStreamStreamingOutput =
101            new RdfStreamStreamingOutput(testRdfStream, testNamespaces, testMediaType);
102    }
103
104    @Test
105    public void testWrite() throws IOException {
106        assertOutputContainsTriple(triple);
107    }
108
109    public void assertOutputContainsTriple(final Triple expected) throws IOException {
110        try (final RdfStream input = new DefaultRdfStream(expected.getSubject(), of(expected));
111                final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
112            new RdfStreamStreamingOutput(input, testNamespaces, testMediaType).write(output);
113            try ( final InputStream resultStream = new ByteArrayInputStream(output.toByteArray())) {
114                final Model result = createDefaultModel().read(resultStream, null);
115                assertTrue("Didn't find our test triple!", result.contains(result.asStatement(expected)));
116            }
117        }
118    }
119
120    @Test
121    public void testWriteWithNamespace() throws IOException {
122        final Map<String, String> namespaces = new HashMap<>();
123        namespaces.put("a", "info:a");
124        try (final RdfStream input = new DefaultRdfStream(triple.getSubject(), of(triple));
125                final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
126            new RdfStreamStreamingOutput(input, namespaces, TURTLE_TYPE).write(output);
127            final String s = output.toString("UTF-8");
128            assertTrue(s.replaceAll("\\s+", " ").contains("@prefix a: <info:a>"));
129        }
130    }
131
132    @Test
133    public void testWriteWithTypedObject() throws IOException {
134        assertOutputContainsTriple(create(createURI("info:testSubject"),
135                createURI("info:testPredicate"),
136                createTypedLiteral(0).asNode()));
137    }
138
139    @Test
140    public void testWriteWithBlankSubject() throws IOException {
141        try (final RdfStream input = new DefaultRdfStream(createResource().asNode(), of(create(createResource()
142                .asNode(), createURI("info:testPredicate"), createTypedLiteral(0).asNode())));
143                final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
144            new RdfStreamStreamingOutput(input, testNamespaces, testMediaType).write(output);
145            try (final InputStream resultStream = new ByteArrayInputStream(output.toByteArray())) {
146                final Model result = createDefaultModel().read(resultStream, null);
147                assertTrue(result.contains(null, createProperty("info:testPredicate"), createTypedLiteral(0)));
148            }
149        }
150    }
151
152
153    @Test
154    public void testWriteWithBlankObject() throws IOException {
155        final Stream<Triple> triples =
156                of(create(createResource().asNode(), createURI("info:testPredicate"), createResource().asNode()));
157        try (final RdfStream input = new DefaultRdfStream(createResource().asNode(), triples);
158                final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
159            new RdfStreamStreamingOutput(input, testNamespaces, testMediaType).write(output);
160            try (final InputStream resultStream = new ByteArrayInputStream(output.toByteArray())) {
161                final Model result = createDefaultModel().read(resultStream, null);
162                assertTrue(result.contains(null, createProperty("info:testPredicate"), (RDFNode) null));
163            }
164        }
165    }
166
167    @Test
168    public void testWriteWithDatetimeObject() throws IOException {
169        assertOutputContainsTriple(create(createURI("info:testSubject"),
170                createURI("info:testPredicate"), createLiteral("2014-01-01T01:02:03Z", XSDdateTime)));
171    }
172
173    @Test
174    public void testWriteWithLanguageLiteral() throws IOException {
175        assertOutputContainsTriple(create(createURI("info:testSubject"),
176                createURI("info:testPredicate"),
177                createLiteral("french string", "fr")));
178    }
179
180    @Test(expected = WebApplicationException.class)
181    public void testWriteWithException() throws IOException {
182
183        final FutureCallback<Void> callback = new FutureCallback<Void>() {
184
185            @Override
186            public void onSuccess(final Void v) {
187                throw new AssertionError("Should never happen!");
188            }
189
190            @Override
191            public void onFailure(final Throwable e) {
192                LOGGER.info("Got exception:", e.getMessage());
193                assertTrue("Got wrong kind of exception!", e instanceof RiotException);
194            }
195        };
196        addCallback(testRdfStreamStreamingOutput, callback);
197        try (final OutputStream mockOutputStream = mock(OutputStream.class, (Answer<Object>) invocation -> {
198            throw new RiotException("Expected.");
199        })) {
200            testRdfStreamStreamingOutput.write(mockOutputStream);
201        }
202    }
203}