001/**
002 * Copyright 2015 DuraSpace, Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.fcrepo.http.api.responses;
017
018import static javax.ws.rs.core.MediaType.APPLICATION_XHTML_XML;
019import static javax.ws.rs.core.MediaType.APPLICATION_XHTML_XML_TYPE;
020import static javax.ws.rs.core.MediaType.TEXT_HTML;
021import static javax.ws.rs.core.MediaType.TEXT_HTML_TYPE;
022import static com.google.common.collect.ImmutableMap.builder;
023import static com.hp.hpl.jena.graph.Node.ANY;
024import static com.hp.hpl.jena.rdf.model.ResourceFactory.createProperty;
025import static com.hp.hpl.jena.rdf.model.ResourceFactory.createResource;
026import static org.apache.commons.lang.StringUtils.isBlank;
027import static org.fcrepo.kernel.api.RdfLexicon.JCR_NAMESPACE;
028import static org.fcrepo.kernel.modeshape.rdf.JcrRdfTools.getRDFNamespaceForJcrNamespace;
029import static org.slf4j.LoggerFactory.getLogger;
030
031import java.io.IOException;
032import java.io.InputStream;
033import java.io.OutputStream;
034import java.io.OutputStreamWriter;
035import java.io.Writer;
036import java.lang.annotation.Annotation;
037import java.lang.reflect.Type;
038import java.net.URL;
039import java.util.ArrayList;
040import java.util.Arrays;
041import java.util.List;
042import java.util.Map;
043import java.util.Optional;
044import java.util.Properties;
045
046import javax.annotation.PostConstruct;
047import javax.jcr.RepositoryException;
048import javax.jcr.Session;
049import javax.jcr.nodetype.NodeType;
050import javax.jcr.nodetype.NodeTypeIterator;
051import javax.ws.rs.Produces;
052import javax.ws.rs.WebApplicationException;
053import javax.ws.rs.core.MediaType;
054import javax.ws.rs.core.MultivaluedMap;
055import javax.ws.rs.core.UriInfo;
056import javax.ws.rs.ext.MessageBodyWriter;
057import javax.ws.rs.ext.Provider;
058
059import com.google.common.collect.ImmutableList;
060import com.google.common.collect.ImmutableMap;
061import com.hp.hpl.jena.graph.Node;
062import com.hp.hpl.jena.rdf.model.Model;
063import org.apache.velocity.Template;
064import org.apache.velocity.VelocityContext;
065import org.apache.velocity.app.VelocityEngine;
066import org.apache.velocity.context.Context;
067import org.apache.velocity.tools.generic.EscapeTool;
068import org.apache.velocity.tools.generic.FieldTool;
069import org.fcrepo.http.commons.responses.HtmlTemplate;
070import org.fcrepo.http.commons.responses.ViewHelpers;
071import org.fcrepo.http.commons.session.SessionFactory;
072import org.fcrepo.kernel.api.RdfLexicon;
073import org.fcrepo.kernel.api.exception.RepositoryRuntimeException;
074import org.fcrepo.kernel.api.utils.iterators.RdfStream;
075import org.fcrepo.kernel.modeshape.rdf.impl.NamespaceRdfContext;
076import org.slf4j.Logger;
077import org.springframework.beans.factory.annotation.Autowired;
078
079/**
080 * Simple HTML provider for RdfStreams
081 *
082 * @author ajs6f
083 * @since Nov 19, 2013
084 */
085@Provider
086@Produces({TEXT_HTML, APPLICATION_XHTML_XML})
087public class StreamingBaseHtmlProvider implements MessageBodyWriter<RdfStream> {
088
089
090    @Autowired
091    SessionFactory sessionFactory;
092
093    @javax.ws.rs.core.Context
094    UriInfo uriInfo;
095
096    private static EscapeTool escapeTool = new EscapeTool();
097
098    protected VelocityEngine velocity = new VelocityEngine();
099
100    /**
101     * Location in the classpath where Velocity templates are to be found.
102     */
103    public static final String templatesLocation = "/views";
104
105    /**
106     * Location in the classpath where the common css file is to be found.
107     */
108    public static final String commonCssLocation = "/views/common.css";
109
110    /**
111     * Location in the classpath where the common javascript file is to be found.
112     */
113    public static final String commonJsLocation = "/views/common.js";
114
115    /**
116     * A map from String names for primary node types to the Velocity templates
117     * that should be used for those node types.
118     */
119    protected Map<String, Template> templatesMap;
120
121    public static final String templateFilenameExtension = ".vsl";
122
123    public static final String velocityPropertiesLocation =
124            "/velocity.properties";
125
126    private static final Logger LOGGER =
127        getLogger(StreamingBaseHtmlProvider.class);
128
129    @PostConstruct
130    void init() throws IOException {
131
132        LOGGER.trace("Velocity engine initializing...");
133        final Properties properties = new Properties();
134        final URL propertiesUrl =
135                getClass().getResource(velocityPropertiesLocation);
136        LOGGER.debug("Using Velocity configuration from {}", propertiesUrl);
137        try (final InputStream propertiesStream = propertiesUrl.openStream()) {
138            properties.load(propertiesStream);
139        }
140        velocity.init(properties);
141        LOGGER.trace("Velocity engine initialized.");
142
143        LOGGER.trace("Assembling a map of node primary types -> templates...");
144        final ImmutableMap.Builder<String, Template> templatesMapBuilder = builder();
145        final Session session = sessionFactory.getInternalSession();
146        try {
147            // we search all of the possible node primary types and mixins
148            for (final NodeTypeIterator primaryNodeTypes =
149                         session.getWorkspace().getNodeTypeManager()
150                                 .getPrimaryNodeTypes(); primaryNodeTypes.hasNext();) {
151                final NodeType primaryNodeType =
152                    primaryNodeTypes.nextNodeType();
153                final String primaryNodeTypeName =
154                    primaryNodeType.getName();
155
156                // Create a list of the primary type and all its parents
157                final List<NodeType> nodeTypesList = new ArrayList<>();
158                nodeTypesList.add(primaryNodeType);
159                nodeTypesList.addAll(Arrays.asList(primaryNodeType.getSupertypes()));
160
161                // Find a template that matches the primary type or one of its parents
162                nodeTypesList.stream()
163                             .map(NodeType::getName)
164                             .filter(x -> !isBlank(x) && velocity.resourceExists(getTemplateLocation(x)))
165                             .findFirst()
166                             .ifPresent(x -> addTemplate(primaryNodeTypeName, x, templatesMapBuilder));
167            }
168
169            final List<String> otherTemplates =
170                    ImmutableList.of("jcr:nodetypes", "node", "fcr:versions", "fcr:fixity");
171
172            for (final String key : otherTemplates) {
173                final Template template =
174                    velocity.getTemplate(getTemplateLocation(key));
175                templatesMapBuilder.put(key, template);
176            }
177
178            templatesMap = templatesMapBuilder.build();
179
180        } catch (final RepositoryException e) {
181            throw new RepositoryRuntimeException(e);
182        }
183        LOGGER.trace("Assembled template map.");
184        LOGGER.trace("HtmlProvider initialization complete.");
185    }
186
187    @Override
188    public void writeTo(final RdfStream rdfStream, final Class<?> type,
189                        final Type genericType, final Annotation[] annotations,
190                        final MediaType mediaType,
191                        final MultivaluedMap<String, Object> httpHeaders,
192                        final OutputStream entityStream) throws IOException {
193
194        try {
195            final RdfStream nsRdfStream = new NamespaceRdfContext(rdfStream.session());
196
197            rdfStream.namespaces(nsRdfStream.namespaces());
198
199            final Node subject = rdfStream.topic();
200
201            final Model model = rdfStream.asModel();
202
203            final Template nodeTypeTemplate = getTemplate(model, subject, Arrays.asList(annotations));
204
205            final Context context = getContext(model, subject);
206
207            // the contract of MessageBodyWriter<T> is _not_ to close the stream
208            // after writing to it
209            final Writer outWriter = new OutputStreamWriter(entityStream);
210            nodeTypeTemplate.merge(context, outWriter);
211            outWriter.flush();
212
213        } catch (final RepositoryException e) {
214            throw new WebApplicationException(e);
215        }
216
217    }
218
219    protected Context getContext(final Model model, final Node subject) {
220        final FieldTool fieldTool = new FieldTool();
221
222        final Context context = new VelocityContext();
223        context.put("rdfLexicon", fieldTool.in(RdfLexicon.class));
224        context.put("helpers", ViewHelpers.getInstance());
225        context.put("esc", escapeTool);
226        context.put("rdf", model.getGraph());
227
228        context.put("model", model);
229        context.put("subjects", model.listSubjects());
230        context.put("nodeany", ANY);
231        context.put("topic", subject);
232        context.put("uriInfo", uriInfo);
233        return context;
234    }
235
236    private Template getTemplate(final Model rdf, final Node subject,
237                                 final List<Annotation> annotations) {
238
239        Optional<Template> template = annotations.stream()
240                                  .filter(x -> x instanceof HtmlTemplate)
241                                  .map(x -> ((HtmlTemplate) x).value())
242                                  .filter(templatesMap::containsKey)
243                                  .map(templatesMap::get)
244                                  .findFirst();
245
246        if (!template.isPresent()) {
247            LOGGER.trace("Attempting to discover the mixin types of the node for the resource in question...");
248            template = rdf.listObjectsOfProperty(createResource(subject.getURI()),
249                                                 createProperty(getRDFNamespaceForJcrNamespace(JCR_NAMESPACE) +
250                                                     "mixinTypes"))
251                          .toList().stream()
252                          .map(x -> x.asLiteral().getLexicalForm())
253                          .filter(templatesMap::containsKey)
254                          .map(templatesMap::get)
255                          .findFirst();
256        }
257
258        if (template.isPresent()) {
259            LOGGER.debug("Choosing template: {}", template.get().getName());
260            return template.get();
261        } else {
262            LOGGER.trace("Attempting to discover the primary type of the node for the resource in question...");
263            return rdf.listObjectsOfProperty(createResource(subject.getURI()),
264                                             createProperty(getRDFNamespaceForJcrNamespace(JCR_NAMESPACE) +
265                                                     "primaryType"))
266                          .toList().stream()
267                          .map(x -> x.asLiteral().getLexicalForm())
268                          .filter(templatesMap::containsKey)
269                          .map(templatesMap::get)
270                          .findFirst()
271                          .orElse(templatesMap.get("node"));
272        }
273    }
274
275    @Override
276    public boolean isWriteable(final Class<?> type, final Type genericType,
277                               final Annotation[] annotations, final MediaType mediaType) {
278        LOGGER.debug(
279                "Checking to see if type: {} is serializable to mimeType: {}",
280                type.getName(), mediaType);
281        return (mediaType.equals(TEXT_HTML_TYPE) || mediaType
282                .equals(APPLICATION_XHTML_XML_TYPE))
283                && RdfStream.class.isAssignableFrom(type);
284    }
285
286    @Override
287    public long getSize(final RdfStream t, final Class<?> type,
288                        final Type genericType, final Annotation[] annotations,
289                        final MediaType mediaType) {
290        // we don't know in advance how large the result might be
291        return -1;
292    }
293
294    private void addTemplate(final String primaryNodeTypeName, final String templateNodeTypeName,
295                             final ImmutableMap.Builder<String, Template> templatesMapBuilder) {
296        final String templateLocation = getTemplateLocation(templateNodeTypeName);
297        final Template template =
298            velocity.getTemplate(templateLocation);
299        template.setName(templateLocation);
300        LOGGER.debug("Found template: {}", templateLocation);
301        templatesMapBuilder.put(primaryNodeTypeName, template);
302        LOGGER.debug("which we will use for nodes with primary type: {}",
303                     primaryNodeTypeName);
304    }
305
306    private static String getTemplateLocation(final String nodeTypeName) {
307        return templatesLocation + "/" +
308            nodeTypeName.replace(':', '-') + templateFilenameExtension;
309    }
310}