Set a CORSConfiguration object programmatically

Create issue
Issue #31 new
MG created an issue

It would be nice to have a way to set the CORSConfiguration on the CORSFilter programmatically, e.g.

final FilterRegistration.Dynamic corsFilter = servletContext.addFilter( "CORS", new CORSFilter( new CORSConfiguration( corsProperties ) ) );
corsFilter.addMappingForUrlPatterns( REQUESTS_ONLY, false, "/*" );

Currently the configuration passed in the constructor gets overwritten on servlet initialization, i.e. method init() of CORSFilter. Thus I need to subclass CORSFilter:

new CORSFilter() {
   @Override
   public void init( FilterConfig filterConfig ) throws ServletException
   {
      try {
         setConfiguration( new CORSConfiguration( corsProperties ) );
      }
      catch( CORSConfigurationException e ) {
         throw new ServletException( e.getMessage(), e );
      }
   }
};

Why do we need a configuration from other sources than the servlet init parameters or a properties file? We have lots of configuration options from different sources in a CompositeConfiguration (Commons Configuration). From here we'd like to extract the CORS configuration:

Iterator< String > keys = globalConfiguration.getKeys( "cors" );
Properties corsProperties = new Properties();
while( keys.hasNext() ) {
   String key = keys.next();
   String[] stringArray = globalConfiguration.getStringArray( key );
   corsProperties.setProperty( key, StringUtils.join( stringArray, ',' ) );
}
CORSConfiguration corsConfiguration = new CORSConfiguration( corsProperties );

Comments (1)

  1. MG reporter

    Hmm, after typing it I just realized that for the given use case I could set the servlet init parameters instead. :-)

    final FilterRegistration.Dynamic corsFilter = servletContext.addFilter( "CORS", new CORSFilter( new CORSConfiguration( corsProperties ) ) );
    corsFilter.addMappingForUrlPatterns( REQUESTS_ONLY, false, "/*" );
    corsFilter.setInitParameters( ... );
    

    But using a programmatic CORSConfiguration object might be a way to make settings dynamically changeable?

  2. Log in to comment