Example usage for javax.imageio.spi IIORegistry getDefaultInstance

List of usage examples for javax.imageio.spi IIORegistry getDefaultInstance

Introduction

In this page you can find the example usage for javax.imageio.spi IIORegistry getDefaultInstance.

Prototype

public static IIORegistry getDefaultInstance() 

Source Link

Document

Returns the default IIORegistry instance used by the Image I/O API.

Usage

From source file:ddf.catalog.transformer.input.tika.TikaInputTransformer.java

public TikaInputTransformer(BundleContext bundleContext) {
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {/*from w w  w  .  ja v a  2  s. com*/
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        templates = TransformerFactory
                .newInstance(net.sf.saxon.TransformerFactoryImpl.class.getName(),
                        net.sf.saxon.TransformerFactoryImpl.class.getClassLoader())
                .newTemplates(
                        new StreamSource(TikaMetadataExtractor.class.getResourceAsStream("/metadata.xslt")));
    } catch (TransformerConfigurationException e) {
        LOGGER.warn("Couldn't create XML transformer", e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    if (bundleContext == null) {
        LOGGER.error("Bundle context is null. Unable to register {} as an osgi service.",
                TikaInputTransformer.class.getSimpleName());
        return;
    }

    registerService(bundleContext);
    IIORegistry.getDefaultInstance().registerServiceProvider(new J2KImageReaderSpi());
    IIORegistry.getDefaultInstance().registerServiceProvider(new TIFFImageReaderSpi());
}

From source file:org.jboss.as.capedwarf.extension.CapedwarfSubsystemAdd.java

protected static void addTiffSupport() {
    IIORegistry registry = IIORegistry.getDefaultInstance();
    registry.registerServiceProvider(new TIFFImageReaderSpi(), ImageReaderSpi.class);
    registry.registerServiceProvider(new RawTiffImageReader.Spi(), ImageReaderSpi.class);
}

From source file:org.dcm4che2.tool.dcm2dcm.Dcm2Dcm.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    System.setProperty("org.dcm4che2.imageio.ImageReaderFactory",
            "com/dicomgrid/imageio/ImageReaderFactory.properties");
    System.setProperty("org.dcm4che2.imageio.ImageWriterFactory",
            "com/dicomgrid/imageio/ImageWriterFactory.properties");

    IIORegistry.getDefaultInstance().registerServiceProvider(new CLibFragmentedJPEGImageReaderSpi(),
            ImageReaderSpi.class);

    CommandLine cl = parse(args);/*w w  w  .j ava 2 s .c om*/
    Dcm2Dcm dcm2dcm = new Dcm2Dcm();
    dcm2dcm.setNoFileMetaInformation(cl.hasOption("no-fmi"));
    dcm2dcm.setTransferSyntax(transferSyntax(cl));
    if (cl.hasOption("buffer")) {
        dcm2dcm.setTranscoderBufferSize(
                parseInt(cl.getOptionValue("buffer"), "illegal argument of option --buffer", 1, 10000) * KB);
    }
    if (cl.hasOption("s")) {
        dcm2dcm.overwriteObject = new BasicDicomObject();
        String[] matchingKeys = cl.getOptionValues("s");
        for (int i = 1; i < matchingKeys.length; i++, i++) {
            int[] tag = Tag.toTagPath(matchingKeys[i - 1]);
            String svalue = matchingKeys[i];
            dcm2dcm.overwriteObject.putString(tag, null, svalue);
        }

    }

    List<String> argList = cl.getArgList();
    int argc = argList.size();

    File dest = new File(argList.get(argc - 1));
    long t1 = System.currentTimeMillis();
    int count;
    if (dest.isDirectory()) {
        count = dcm2dcm.mconvert(argList, 0, dest);
    } else {
        File src = new File(argList.get(0));
        if (argc > 2 || src.isDirectory()) {
            exit("dcm2dcm: when converting several files, " + "last argument must be a directory\n");
        }
        count = dcm2dcm.mconvert(src, dest);
    }
    long t2 = System.currentTimeMillis();
    System.out.println("\nconverted " + count + " file(s) in " + (t2 - t1) / 1000f + " s.");
}

From source file:org.deegree.enterprise.servlet.OGCServletController.java

@Override
public void destroy() {
    super.destroy();
    Enumeration<Driver> e = DriverManager.getDrivers();
    while (e.hasMoreElements()) {
        Driver driver = e.nextElement();
        try {//  w  w w.j  ava  2s  . c  om
            if (driver.getClass().getClassLoader() == getClass().getClassLoader())
                DriverManager.deregisterDriver(driver);
        } catch (SQLException e1) {
            LOG.logError("Cannot unload driver: " + driver);
        }
    }
    LogFactory.releaseAll();
    LogManager.shutdown();
    // SLF4JLogFactory.releaseAll(); // should be the same as the LogFactory.releaseAll call
    Iterator<Class<?>> i = IIORegistry.getDefaultInstance().getCategories();
    while (i.hasNext()) {
        Class<?> c = i.next();
        Iterator<?> k = IIORegistry.getDefaultInstance().getServiceProviders(c, false);
        while (k.hasNext()) {
            Object o = k.next();
            if (o.getClass().getClassLoader() == getClass().getClassLoader()) {
                IIORegistry.getDefaultInstance().deregisterServiceProvider(o);
                LOG.logDebug("Deregistering JAI driver ", o.getClass());
            }
        }
    }
    Introspector.flushCaches();
    // just clear the configurations for now, it does not hurt
    CRSConfiguration.DEFINED_CONFIGURATIONS.clear();
}

From source file:org.deegree.services.controller.OGCFrontController.java

/**
 * Apply workarounds for classloader leaks, see eg. <a
 * href="http://java.jiderhamn.se/2012/02/26/classloader-leaks-v-common-mistakes-and-known-offenders/">this blog
 * post</a>./*from  ww  w.ja  v  a 2s.c o  m*/
 */
private void plugClassLoaderLeaks() {
    // if the feature store manager does this, it breaks
    try {
        ThreadedFeatureInputStream.shutdown();
    } catch (Throwable e) {
        // just eat it
    }
    Executor.getInstance().shutdown();

    LogFactory.releaseAll();
    LogManager.shutdown();

    // image io
    Iterator<Class<?>> i = IIORegistry.getDefaultInstance().getCategories();
    while (i.hasNext()) {
        Class<?> c = i.next();
        Iterator<?> k = IIORegistry.getDefaultInstance().getServiceProviders(c, false);
        while (k.hasNext()) {
            Object o = k.next();
            if (o.getClass().getClassLoader() == getClass().getClassLoader()) {
                IIORegistry.getDefaultInstance().deregisterServiceProvider(o);
                LOG.debug("Deregistering " + o);
                k = IIORegistry.getDefaultInstance().getServiceProviders(c, false);
            }
        }
    }

    // JSF
    Introspector.flushCaches();

    // Batik
    try {
        Class<?> cls = Class.forName("org.apache.batik.util.CleanerThread");
        if (cls != null) {
            Field field = cls.getDeclaredField("thread");
            field.setAccessible(true);
            Object obj = field.get(null);
            if (obj != null) {
                // interrupt is ignored by the thread
                ((Thread) obj).stop();
            }
        }
    } catch (Exception ex) {
        LOG.warn("Problem when trying to fix batik class loader leak.");
    }
}

From source file:org.geoserver.GeoserverInitStartupListener.java

/**
 * This method tries hard to stop all threads and remove all references to classes in GeoServer
 * so that we can avoid permgen leaks on application undeploy.
 * What happes is that, if any JDK class references to one of the classes loaded by the
 * webapp classloader, then the classloader cannot be collected and neither can all the
 * classes loaded by it (since each class keeps a back reference to the classloader that
 * loaded it). The same happens for any residual thread launched by the web app.
 */// w  w w .jav a2  s .c  o m
public void contextDestroyed(ServletContextEvent sce) {
    try {
        LOGGER.info("Beginning GeoServer cleanup sequence");

        // the dreaded classloader
        ClassLoader webappClassLoader = getClass().getClassLoader();

        // unload all of the jdbc drivers we have loaded. We need to store them and unregister
        // later to avoid concurrent modification exceptions
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        Set<Driver> driversToUnload = new HashSet<Driver>();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                // the driver class loader can be null if the driver comes from the JDK, such as the 
                // sun.jdbc.odbc.JdbcOdbcDriver
                ClassLoader driverClassLoader = driver.getClass().getClassLoader();
                if (driverClassLoader != null && webappClassLoader.equals(driverClassLoader)) {
                    driversToUnload.add(driver);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
        for (Driver driver : driversToUnload) {
            try {
                DriverManager.deregisterDriver(driver);
                LOGGER.info("Unregistered JDBC driver " + driver);
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, "Could now unload driver " + driver.getClass(), e);
            }
        }
        drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
        }
        try {
            Class h2Driver = Class.forName("org.h2.Driver");
            Method m = h2Driver.getMethod("unload");
            m.invoke(null);
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Failed to unload the H2 driver", e);
        }

        // unload all deferred authority factories so that we get rid of the timer tasks in them
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCoordinateOperationAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCRSAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCSAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }

        // kill the threads created by referencing
        WeakCollectionCleaner.DEFAULT.exit();
        DeferredAuthorityFactory.exit();
        CRS.reset("all");
        LOGGER.info("Shut down GT referencing threads ");
        // reset 
        ReferencingFactoryFinder.reset();
        CommonFactoryFinder.reset();
        DataStoreFinder.reset();
        DataAccessFinder.reset();
        LOGGER.info("Shut down GT  SPI ");

        LOGGER.info("Shut down coverage thread pool ");
        Object o = Hints.getSystemDefault(Hints.EXECUTOR_SERVICE);
        if (o != null && o instanceof ExecutorService) {
            final ThreadPoolExecutor executor = (ThreadPoolExecutor) o;
            try {
                executor.shutdown();
            } finally {
                try {
                    executor.shutdownNow();
                } finally {

                }
            }
        }

        // unload everything that JAI ImageIO can still refer to
        // We need to store them and unregister later to avoid concurrent modification exceptions
        final IIORegistry ioRegistry = IIORegistry.getDefaultInstance();
        Set<IIOServiceProvider> providersToUnload = new HashSet();
        for (Iterator<Class<?>> cats = ioRegistry.getCategories(); cats.hasNext();) {
            Class<?> category = cats.next();
            for (Iterator it = ioRegistry.getServiceProviders(category, false); it.hasNext();) {
                final IIOServiceProvider provider = (IIOServiceProvider) it.next();
                if (webappClassLoader.equals(provider.getClass().getClassLoader())) {
                    providersToUnload.add(provider);
                }
            }
        }
        for (IIOServiceProvider provider : providersToUnload) {
            ioRegistry.deregisterServiceProvider(provider);
            LOGGER.info("Unregistering Image I/O provider " + provider);
        }

        // unload everything that JAI can still refer to
        final OperationRegistry opRegistry = JAI.getDefaultInstance().getOperationRegistry();
        for (String mode : RegistryMode.getModeNames()) {
            for (Iterator descriptors = opRegistry.getDescriptors(mode).iterator(); descriptors != null
                    && descriptors.hasNext();) {
                RegistryElementDescriptor red = (RegistryElementDescriptor) descriptors.next();
                int factoryCount = 0;
                int unregisteredCount = 0;
                // look for all the factories for that operation
                for (Iterator factories = opRegistry.getFactoryIterator(mode, red.getName()); factories != null
                        && factories.hasNext();) {
                    Object factory = factories.next();
                    if (factory == null) {
                        continue;
                    }
                    factoryCount++;
                    if (webappClassLoader.equals(factory.getClass().getClassLoader())) {
                        boolean unregistered = false;
                        // we need to scan against all "products" to unregister the factory
                        Vector orderedProductList = opRegistry.getOrderedProductList(mode, red.getName());
                        if (orderedProductList != null) {
                            for (Iterator products = orderedProductList.iterator(); products != null
                                    && products.hasNext();) {
                                String product = (String) products.next();
                                try {
                                    opRegistry.unregisterFactory(mode, red.getName(), product, factory);
                                    LOGGER.info("Unregistering JAI factory " + factory.getClass());
                                } catch (Throwable t) {
                                    // may fail due to the factory not being registered against that product
                                }
                            }
                        }
                        if (unregistered) {
                            unregisteredCount++;
                        }

                    }
                }

                // if all the factories were unregistered, get rid of the descriptor as well
                if (factoryCount > 0 && unregisteredCount == factoryCount) {
                    opRegistry.unregisterDescriptor(red);
                }
            }
        }

        // flush all javabean introspection caches as this too can keep a webapp classloader from being unloaded
        Introspector.flushCaches();
        LOGGER.info("Cleaned up javabean caches");

        // unload the logging framework
        if (!relinquishLoggingControl)
            LogManager.shutdown();
        LogFactory.release(Thread.currentThread().getContextClassLoader());

        // GeoTools/GeoServer have a lot of finalizers and until they are run the JVM
        // itself wil keepup the class loader...
        try {
            System.gc();
            System.runFinalization();
            System.gc();
            System.runFinalization();
            System.gc();
            System.runFinalization();
        } catch (Throwable t) {
            System.out.println("Failed to perform closing up finalization");
            t.printStackTrace();
        }
    } catch (Throwable t) {
        // if anything goes south during the cleanup procedures I want to know what it is
        t.printStackTrace();
    }
}

From source file:org.paxle.tools.icon.impl.FaviconReader.java

@Activate
void activate() {
    this.serviceProvider = new ICOImageReaderSPI();

    // registering the ICO lib as new provider
    IIORegistry.getDefaultInstance().registerServiceProvider(this.serviceProvider);
}

From source file:org.paxle.tools.icon.impl.FaviconReader.java

@Deactivate
void deactivate() {
    // unregister service provider
    IIORegistry.getDefaultInstance().deregisterServiceProvider(this.serviceProvider);
}