001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * 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 */
018
019package org.apache.hadoop.security;
020
021import java.util.HashMap;
022import java.util.Map;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.apache.hadoop.conf.Configuration;
027import org.apache.hadoop.http.FilterContainer;
028import org.apache.hadoop.http.FilterInitializer;
029import org.apache.hadoop.security.http.CrossOriginFilter;
030
031public class HttpCrossOriginFilterInitializer extends FilterInitializer {
032
033  public static final String PREFIX = "hadoop.http.cross-origin.";
034  public static final String ENABLED_SUFFIX = "enabled";
035
036  private static final Log LOG =
037      LogFactory.getLog(HttpCrossOriginFilterInitializer.class);
038
039  @Override
040  public void initFilter(FilterContainer container, Configuration conf) {
041
042    String key = getEnabledConfigKey();
043    boolean enabled = conf.getBoolean(key, false);
044    if (enabled) {
045      container.addGlobalFilter("Cross Origin Filter",
046          CrossOriginFilter.class.getName(),
047          getFilterParameters(conf, getPrefix()));
048    } else {
049      LOG.info("CORS filter not enabled. Please set " + key
050          + " to 'true' to enable it");
051    }
052  }
053
054  protected static Map<String, String> getFilterParameters(Configuration conf,
055      String prefix) {
056    Map<String, String> filterParams = new HashMap<String, String>();
057    for (Map.Entry<String, String> entry : conf.getValByRegex(prefix)
058        .entrySet()) {
059      String name = entry.getKey();
060      String value = entry.getValue();
061      name = name.substring(prefix.length());
062      filterParams.put(name, value);
063    }
064    return filterParams;
065  }
066
067  protected String getPrefix() {
068    return HttpCrossOriginFilterInitializer.PREFIX;
069  }
070
071  protected String getEnabledConfigKey() {
072    return getPrefix() + HttpCrossOriginFilterInitializer.ENABLED_SUFFIX;
073  }
074}