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;
017
018import com.fasterxml.jackson.databind.ObjectMapper;
019import com.fasterxml.jackson.databind.node.ObjectNode;
020import com.google.common.annotations.VisibleForTesting;
021import com.hp.hpl.jena.rdf.model.Resource;
022import org.apache.commons.lang.StringUtils;
023import org.fcrepo.http.commons.AbstractResource;
024import org.fcrepo.http.commons.api.rdf.HttpResourceConverter;
025import org.fcrepo.kernel.models.FedoraResource;
026import org.fcrepo.kernel.models.Tombstone;
027import org.fcrepo.kernel.exception.TombstoneException;
028import org.fcrepo.kernel.identifiers.IdentifierConverter;
029import org.slf4j.Logger;
030
031import javax.jcr.Session;
032import javax.jcr.observation.ObservationManager;
033import javax.ws.rs.core.HttpHeaders;
034import javax.ws.rs.core.UriInfo;
035
036import static org.slf4j.LoggerFactory.getLogger;
037
038/**
039 * @author cabeer
040 * @since 10/5/14
041 */
042abstract public class FedoraBaseResource extends AbstractResource {
043
044    private static final Logger LOGGER = getLogger(FedoraBaseResource.class);
045
046    protected IdentifierConverter<Resource, FedoraResource> idTranslator;
047
048    protected abstract Session session();
049
050    protected IdentifierConverter<Resource, FedoraResource> translator() {
051        if (idTranslator == null) {
052            idTranslator = new HttpResourceConverter(session(),
053                    uriInfo.getBaseUriBuilder().clone().path(FedoraLdp.class));
054        }
055
056        return idTranslator;
057    }
058
059    /**
060     * Get the FedoraResource for the resource at the external path
061     * @param externalPath the external path
062     * @return the fedora resource at the external path
063     */
064    @VisibleForTesting
065    public FedoraResource getResourceFromPath(final String externalPath) {
066        final Resource resource = translator().toDomain(externalPath);
067        final FedoraResource fedoraResource = translator().convert(resource);
068
069        if (fedoraResource instanceof Tombstone) {
070            throw new TombstoneException(fedoraResource, resource.getURI() + "/fcr:tombstone");
071        }
072
073        return fedoraResource;
074    }
075
076    /**
077     * Set the baseURL for JMS events.
078     * @param uriInfo the uri info
079     * @param headers HTTP headers
080     **/
081    protected void setUpJMSInfo(final UriInfo uriInfo, final HttpHeaders headers) {
082        try {
083            String baseURL = getBaseUrlProperty();
084            if (baseURL.length() == 0) {
085                baseURL = uriInfo.getBaseUri().toString();
086            }
087            LOGGER.debug("setting baseURL = " + baseURL);
088            final ObservationManager obs = session().getWorkspace().getObservationManager();
089            final ObjectMapper mapper = new ObjectMapper();
090            final ObjectNode json = mapper.createObjectNode();
091            json.put("baseURL", baseURL);
092            if (!StringUtils.isBlank(headers.getHeaderString("user-agent"))) {
093                json.put("userAgent", headers.getHeaderString("user-agent"));
094            }
095            obs.setUserData(mapper.writeValueAsString(json));
096        } catch ( final Exception ex ) {
097            LOGGER.warn("Error setting baseURL", ex);
098        }
099    }
100
101    /**
102     * Produce a baseURL for JMS events using the system property fcrepo.jms.baseUrl of the form http[s]://host[:port],
103     * if it exists.
104     *
105     * @return String the base Url
106     */
107    protected String getBaseUrlProperty() {
108        final String propBaseURL = System.getProperty("fcrepo.jms.baseUrl", "");
109        if (propBaseURL.length() > 0 && propBaseURL.startsWith("http")) {
110            return uriInfo.getBaseUriBuilder().uri(propBaseURL).toString();
111        }
112        return "";
113    }
114}