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 org.fcrepo.http.commons.domain.RDFMediaType.APPLICATION_LINK_FORMAT;
021
022import java.io.OutputStream;
023import java.io.PrintWriter;
024import java.lang.annotation.Annotation;
025import java.lang.reflect.Type;
026import java.nio.charset.StandardCharsets;
027
028import javax.ws.rs.Produces;
029import javax.ws.rs.WebApplicationException;
030import javax.ws.rs.core.MediaType;
031import javax.ws.rs.core.MultivaluedMap;
032import javax.ws.rs.ext.MessageBodyWriter;
033import javax.ws.rs.ext.Provider;
034
035/**
036 * Writer for application/link-format bodies.
037 *
038 * @author whikloj
039 * @since 2017-10-25
040 */
041@Provider
042@Produces(APPLICATION_LINK_FORMAT)
043public class LinkFormatProvider implements MessageBodyWriter<LinkFormatStream> {
044
045    @Override
046    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
047        final MediaType mediaType) {
048        return LinkFormatStream.class.isAssignableFrom(type);
049    }
050
051    @Override
052    public long getSize(final LinkFormatStream links, final Class<?> type, final Type genericType,
053        final Annotation[] annotations, final MediaType mediaType) {
054        return -1;
055    }
056
057    @Override
058    public void writeTo(final LinkFormatStream links, final Class<?> type, final Type genericType,
059        final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
060        final OutputStream entityStream)
061            throws WebApplicationException {
062
063        final PrintWriter writer = new PrintWriter(entityStream, false, StandardCharsets.UTF_8);
064        links.getStream().forEach(l -> {
065            writer.println(l.toString() + ",");
066        });
067        writer.close();
068    }
069
070}