Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.apache.sling.security.impl;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import  org.osgi.service.component.ComponentContext;
 
 @Component(metatype = true,
 description = "Request filter adding Content Disposition attachment for certain paths/content types",
 label=" Apache Sling Content Disposition Filter")
 @Service(value = Filter.class)
         @Property(name = "sling.filter.scope", value = { "request" }, propertyPrivate = true),
         @Property(name = "service.ranking", intValue = -25000, propertyPrivate = true) })
 public class ContentDispositionFilter implements Filter {
    
    
Logger.
 
     private final Logger logger = LoggerFactory.getLogger(this.getClass());
     
     @Property(label = "Content Disposition Paths"
             description = "These paths are filtered by the filter. "+
                     "Each entry is of the form 'path [ \":\" CSV of excluded content types ]'. " +
                     "Invalid entries are logged and ignored."
                     , unbounded = ., value = { "" })
     private static final String PROP_CONTENT_DISPOSTION_PATHS = "sling.content.disposition.paths";
   
    
Set of paths
 
     Set<StringcontentDispositionPaths;

    
Array of prefixes of paths
 
     private String[] contentDispositionPathsPfx;
 
     private Map<StringSet<String>> contentTypesMapping;
     
     @Activate
     private void activate(final ComponentContext ctx) {
         final Dictionary props = ctx.getProperties();
         
         String[] contentDispostionProps = PropertiesUtil.toStringArray(props.get());
         
         Set<Stringpaths = new HashSet<String>();
         List<Stringpfxs = new ArrayList<String>();
         Map<StringSet<String>> contentTypesMap = new HashMap<StringSet<String>>();
         
         for (String path : contentDispostionProps) {
             path = path.trim();
             if (path.length() > 0) {
                 int idx = path.indexOf('*');
                 int colonIdx = path.indexOf(":");
                 
                 if (colonIdx > -1 && colonIdx < idx) {
                     // ':'  in paths is not allowed
                     .info("':' in paths is not allowed.");
                 } else {
                     String p = null;
                    if (idx >= 0) {
                        if (idx > 0) {
                            p = path.substring(0, idx);
                            pfxs.add(p);
                        } else {
                            // we don't allow "*" - that would defeat the
                            // purpose.
                            .info("catch-all wildcard for paths not allowed.");
                        }
                    } else {
                        if (colonIdx > -1) {
                            p = path.substring(0, colonIdx);
                        } else {
                            p = path;
                        }
                        paths.add(p);
                    }                   
                    if (colonIdx != -1 && p != null) {
                        Set <StringcontentTypes = getContentTypes(path.substring(colonIdx+1));
                        contentTypesMap.put(pcontentTypes);
                    }
                }
            }
        }
        
         = paths.isEmpty() ? Collections.<String>emptySet() : paths;
         = pfxs.toArray(new String[pfxs.size()]);
         = contentTypesMap.isEmpty()?Collections.<StringSet<String>>emptyMap(): contentTypesMap;
        
        .info("Initialized. content disposition paths: {}, content disposition paths-pfx {}"new Object[]{
                }
        );
    }
    
    public void init(FilterConfig filterConfigthrows ServletException {
        // nothing to do
    }
    public void destroy() {
        // nothing to do
    }
    public void doFilter(ServletRequest requestServletResponse response,
            FilterChain chainthrows IOExceptionServletException {
  
        final SlingHttpServletRequest slingRequest = (SlingHttpServletRequestrequest;
        final SlingHttpServletResponse slingResponse = (SlingHttpServletResponseresponse;
        final RewriterResponse rewriterResponse = new RewriterResponse(slingRequestslingResponse);
        chain.doFilter(requestrewriterResponse);
    }
    
    //---------- PRIVATE METHODS ---------
    
    private static Set<StringgetContentTypes(String contentTypes) {
        Set<StringcontentTypesSet = new HashSet<String>();
        if (contentTypes != null && contentTypes.length() > 0) {
            String[] contentTypesArray = contentTypes.split(",");
            for (String contentType : contentTypesArray) {
                contentTypesSet.add(contentType);
            }
        }
        return contentTypesSet;
    }
    
    //----------- INNER CLASSES ------------ 
    protected class RewriterResponse extends SlingHttpServletResponseWrapper {
        
        private static final String CONTENT_DISPOSTION = "Content-Disposition";
        private static final String CONTENT_DISPOSTION_ATTACHMENT = "attachment";
        
        
The current request.
        private final SlingHttpServletRequest request;
        public RewriterResponse(SlingHttpServletRequest requestSlingHttpServletResponse wrappedResponse) {
            super(wrappedResponse);            
            this. = request;
        }
        
        

See also:
javax.servlet.ServletResponseWrapper.setContentType(java.lang.String)
        public void setContentType(String type) { 
            String pathInfo = .getPathInfo();
            if (.contains(pathInfo)) {
                if (.containsKey(pathInfo)) {
                    Set exceptions = .get(pathInfo);
                    if (!exceptions.contains(type)) {
                        setContentDisposition();
                    }
                } else {
                    setContentDisposition();
                }
            }
            
            for (String path : ) {
                if (.getPathInfo().startsWith(path)) {
                    if (.containsKey(path)) {
                        Set exceptions = .get(path);
                        if (!exceptions.contains(type)) {
                            setContentDisposition();
                            break;
                        }
                    } else {
                        setContentDisposition();
                        break;
                    }
                }
            }
            super.setContentType(type);
        }    
        
        private void setContentDisposition() {
        }
    }
New to GrepCode? Check out our FAQ X