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.api; 017 018import static org.slf4j.LoggerFactory.getLogger; 019 020import java.util.Map; 021import javax.servlet.http.HttpServletResponse; 022import javax.ws.rs.core.UriInfo; 023 024import org.fcrepo.kernel.api.models.FedoraResource; 025 026import org.slf4j.Logger; 027import org.springframework.beans.BeansException; 028import org.springframework.context.ApplicationContext; 029import org.springframework.context.support.ApplicationObjectSupport; 030import org.springframework.stereotype.Component; 031 032import com.google.common.collect.Multimap; 033 034/** 035 * Inject optional headers from external processes 036 * 037 * @author whikloj 038 * @since 2015-10-30 039 */ 040@Component 041public class HttpHeaderInjector extends ApplicationObjectSupport { 042 043 private static final Logger LOGGER = getLogger(HttpHeaderInjector.class); 044 045 private ApplicationContext applicationContext; 046 047 @Override 048 protected void initApplicationContext() throws BeansException { 049 applicationContext = getApplicationContext(); 050 } 051 052 @Override 053 protected boolean isContextRequired() { 054 return true; 055 } 056 057 /** 058 * Add additional Http Headers 059 * 060 * @param servletResponse the response 061 * @param uriInfo the URI context 062 * @param resource the resource 063 */ 064 public void addHttpHeaderToResponseStream(final HttpServletResponse servletResponse, 065 final UriInfo uriInfo, 066 final FedoraResource resource) { 067 068 getUriAwareHttpHeaderFactories().forEach((bean, factory) -> { 069 LOGGER.debug("Adding HTTP headers using: {}", bean); 070 final Multimap<String, String> h = factory.createHttpHeadersForResource(uriInfo, resource); 071 072 h.entries().forEach(entry -> { 073 servletResponse.addHeader(entry.getKey(), entry.getValue()); 074 }); 075 }); 076 } 077 078 private Map<String, UriAwareHttpHeaderFactory> getUriAwareHttpHeaderFactories() { 079 return applicationContext.getBeansOfType(UriAwareHttpHeaderFactory.class); 080 } 081 082}