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.commons.domain;
017
018import static org.fcrepo.http.commons.domain.PreferTag.emptyTag;
019
020import java.text.ParseException;
021import java.util.Set;
022import java.util.TreeSet;
023
024import org.glassfish.jersey.message.internal.HttpHeaderReader;
025
026/**
027 * JAX-RS HTTP parameter parser for the Prefer header
028 *
029 * @author cabeer
030 * @author ajs6f
031 * @author acoburn
032 */
033public class SinglePrefer {
034
035    private final Set<PreferTag> preferTags = new TreeSet<>();
036
037    /**
038     * Parse a Prefer: header
039     *
040     * @param header the header
041     * @throws ParseException if parse exception occurred
042     */
043    public SinglePrefer(final String header) throws ParseException {
044        preferTags.addAll(HttpHeaderReader.readList(PreferTag::new, header));
045    }
046
047    /**
048     * Does the Prefer: header have a return tag
049     *
050     * @return true if the header has a return tag
051     */
052    public Boolean hasReturn() {
053        return preferTags().stream().map(PreferTag::getTag).anyMatch("return"::equals);
054    }
055
056    /**
057     * Does the Prefer: header have a return tag
058     *
059     * @return true if the header has a return tag
060     */
061    public Boolean hasHandling() {
062        return preferTags().stream().map(PreferTag::getTag).anyMatch("handling"::equals);
063    }
064
065    /**
066     * Get the return tag, or a blank default, if none exists.
067     *
068     * @return return tag, or a blank default, if none exists
069     */
070    public PreferTag getReturn() {
071        return preferTags().stream()
072                .filter(x -> x.getTag().equals("return"))
073                .findFirst().orElse(emptyTag());
074    }
075
076    /**
077     * Get the return tag, or a blank default, if none exists.
078     *
079     * @return return tag, or a blank default, if none exists
080     */
081    public PreferTag getHandling() {
082        return preferTags().stream()
083                .filter(x -> x.getTag().equals("handling"))
084                .findFirst().orElse(emptyTag());
085    }
086
087    protected Set<PreferTag> preferTags() {
088        return preferTags;
089    }
090}