static {
   ImageIO.scanForPlugins();
 }
  public void contextInitialized(ServletContextEvent sce) {
    // start up tctool - remove it before committing!!!!
    // new tilecachetool.TCTool().setVisible(true);

    // Register logging, and bridge to JAI logging
    GeoTools.init((Hints) null);

    // Custom GeoTools ImagingListener used to ignore common warnings
    JAI.getDefaultInstance()
        .setImagingListener(
            new ImagingListener() {
              final Logger LOGGER = Logging.getLogger("javax.media.jai");

              @Override
              public boolean errorOccurred(
                  String message, Throwable thrown, Object where, boolean isRetryable)
                  throws RuntimeException {
                if (isSerializableRenderedImageFinalization(where, thrown)) {
                  LOGGER.log(Level.FINEST, message, thrown);
                } else if (message.contains("Continuing in pure Java mode")) {
                  LOGGER.log(Level.FINE, message, thrown);
                } else {
                  LOGGER.log(Level.INFO, message, thrown);
                }
                return false; // we are not trying to recover
              }

              private boolean isSerializableRenderedImageFinalization(Object where, Throwable t) {
                if (!(where instanceof SerializableRenderedImage)) {
                  return false;
                }

                // check if it's the finalizer
                StackTraceElement[] elements = t.getStackTrace();
                for (StackTraceElement element : elements) {
                  if (element.getMethodName().equals("finalize")
                      && element.getClassName().endsWith("SerializableRenderedImage")) return true;
                }

                return false;
              }
            });

    // setup concurrent operation registry
    JAI jaiDef = JAI.getDefaultInstance();
    if (!(jaiDef.getOperationRegistry() instanceof ConcurrentOperationRegistry
        || jaiDef.getOperationRegistry()
            instanceof it.geosolutions.jaiext.ConcurrentOperationRegistry)) {
      jaiDef.setOperationRegistry(ConcurrentOperationRegistry.initializeRegistry());
    }

    // setup the concurrent tile cache (has proper memory limit handling also for small tiles)
    if (!(jaiDef.getTileCache() instanceof ConcurrentTileCacheMultiMap)) {
      jaiDef.setTileCache(new ConcurrentTileCacheMultiMap());
    }

    // make sure we remember if GeoServer controls logging or not
    String strValue =
        GeoServerExtensions.getProperty(
            LoggingUtils.RELINQUISH_LOG4J_CONTROL, sce.getServletContext());
    relinquishLoggingControl = Boolean.valueOf(strValue);

    // if the server admin did not set it up otherwise, force X/Y axis
    // ordering
    // This one is a good place because we need to initialize this property
    // before any other opeation can trigger the initialization of the CRS
    // subsystem
    if (System.getProperty("org.geotools.referencing.forceXY") == null) {
      System.setProperty("org.geotools.referencing.forceXY", "true");
    }
    if (Boolean.TRUE.equals(Hints.getSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER))) {
      Hints.putSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING, "http");
    }
    Hints.putSystemDefault(Hints.LENIENT_DATUM_SHIFT, true);

    // setup the referencing tolerance to make it more tolerant to tiny differences
    // between projections (increases the chance of matching a random prj file content
    // to an actual EPSG code
    String comparisonToleranceProperty =
        GeoServerExtensions.getProperty(COMPARISON_TOLERANCE_PROPERTY);
    double comparisonTolerance = DEFAULT_COMPARISON_TOLERANCE;
    if (comparisonToleranceProperty != null) {
      try {
        comparisonTolerance = Double.parseDouble(comparisonToleranceProperty);
      } catch (NumberFormatException nfe) {
        if (LOGGER.isLoggable(Level.WARNING)) {
          LOGGER.warning(
              "Unable to parse the specified COMPARISON_TOLERANCE "
                  + "system property: "
                  + comparisonToleranceProperty
                  + " which should be a number. Using Default: "
                  + DEFAULT_COMPARISON_TOLERANCE);
        }
      }
    }
    Hints.putSystemDefault(Hints.COMPARISON_TOLERANCE, comparisonTolerance);

    final Hints defHints = GeoTools.getDefaultHints();

    // Initialize GridCoverageFactory so that we don't make a lookup every time a factory is needed
    Hints.putSystemDefault(
        Hints.GRID_COVERAGE_FACTORY, CoverageFactoryFinder.getGridCoverageFactory(defHints));

    // don't allow the connection to the EPSG database to time out. This is a server app,
    // we can afford keeping the EPSG db always on
    System.setProperty("org.geotools.epsg.factory.timeout", "-1");

    // HACK: java.util.prefs are awful. See
    // http://www.allaboutbalance.com/disableprefs. When the site comes
    // back up we should implement their better way of fixing the problem.
    System.setProperty("java.util.prefs.syncInterval", "5000000");

    // Fix issue with tomcat and JreMemoryLeakPreventionListener causing issues with
    // IIORegistry leading to imageio plugins not being properly initialized
    ImageIO.scanForPlugins();

    // in any case, the native png reader is worse than the pure java ones, so
    // let's disable it (the native png writer is on the other side faster)...
    ImageIOExt.allowNativeCodec("png", ImageReaderSpi.class, false);
    ImageIOExt.allowNativeCodec("png", ImageWriterSpi.class, true);

    // initialize GeoTools factories so that we don't make a SPI lookup every time a factory is
    // needed
    Hints.putSystemDefault(Hints.FILTER_FACTORY, CommonFactoryFinder.getFilterFactory2(null));
    Hints.putSystemDefault(Hints.STYLE_FACTORY, CommonFactoryFinder.getStyleFactory(null));
    Hints.putSystemDefault(Hints.FEATURE_FACTORY, CommonFactoryFinder.getFeatureFactory(null));

    // initialize the default executor service
    final ThreadPoolExecutor executor =
        new ThreadPoolExecutor(
            CoverageAccessInfoImpl.DEFAULT_CorePoolSize,
            CoverageAccessInfoImpl.DEFAULT_MaxPoolSize,
            CoverageAccessInfoImpl.DEFAULT_KeepAliveTime,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    Hints.putSystemDefault(Hints.EXECUTOR_SERVICE, executor);
  }