001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket.csp; 018 019import java.util.List; 020import java.util.stream.Collectors; 021 022import org.apache.wicket.request.cycle.RequestCycle; 023import org.apache.wicket.util.lang.Args; 024 025/** 026 * A CSP value that renders the same value as rendered for the specified directive. 027 * 028 * @author papegaaij 029 */ 030public class ClonedCSPValue implements CSPRenderable 031{ 032 private final CSPHeaderConfiguration headerConfiguration; 033 034 private final CSPDirective sourceDirective; 035 036 /** 037 * Creates a new {@code ClonedCSPValue} for the given directive. 038 * 039 * @param headerConfiguration 040 * the header to clone from; 041 * @param sourceDirective 042 * the directive to clone; 043 */ 044 public ClonedCSPValue(CSPHeaderConfiguration headerConfiguration, CSPDirective sourceDirective) 045 { 046 this.headerConfiguration = Args.notNull(headerConfiguration, "headerConfiguration"); 047 this.sourceDirective = Args.notNull(sourceDirective, "sourceDirective"); 048 } 049 050 @Override 051 public String render(ContentSecurityPolicySettings settings, RequestCycle cycle) 052 { 053 List<CSPRenderable> values = headerConfiguration.getDirectives().get(sourceDirective); 054 if (values == null) 055 { 056 throw new IllegalStateException( 057 "CSP directive " + sourceDirective + " not set, cannot clone its value."); 058 } 059 return values.stream().map(r -> r.render(settings, cycle)).collect(Collectors.joining(" ")); 060 } 061 062 @Override 063 public String toString() 064 { 065 return "clone(" + sourceDirective.getValue() + ")"; 066 } 067}