Exemplo n.º 1
0
  public static void printOperatorList() {
    OperationRegistry operationRegistry = JAI.getDefaultInstance().getOperationRegistry();
    List<OperationDescriptor> descriptors =
        (List<OperationDescriptor>) operationRegistry.getDescriptors(OperationDescriptor.class);

    Collections.sort(
        descriptors,
        new Comparator<OperationDescriptor>() {
          public int compare(OperationDescriptor descriptor1, OperationDescriptor descriptor2) {
            return descriptor1.getName().compareTo(descriptor2.getName());
          }
        });

    int columnCount = 0;
    for (OperationDescriptor descriptor : descriptors) {
      columnCount = Math.max(columnCount, descriptor.getName().length());
    }

    for (OperationDescriptor descriptor : descriptors) {
      String namePart = descriptor.getName();
      if (namePart.length() < columnCount) {
        namePart += spaces(columnCount - namePart.length());
      }
      String[][] resources = descriptor.getResources(Locale.getDefault());
      String description = resources[3][1];
      System.out.println(namePart + " - " + description);
    }
  }
  public static OperationRegistry initializeRegistry() {
    try {
      InputStream url = PropertyUtil.getFileFromClasspath(JAI_REGISTRY_FILE);

      if (url == null) {
        throw new RuntimeException("Could not find the main registry file");
      }

      OperationRegistry registry = new ConcurrentOperationRegistry();

      if (url != null) {
        registry.updateFromStream(url);
      }

      registry.registerServices(null);

      return registry;

    } catch (IOException ioe) {
      ImagingListener listener = JAI.getDefaultInstance().getImagingListener();
      String message = "Error occurred while initializing JAI";
      listener.errorOccurred(
          message, new ImagingException(message, ioe), OperationRegistry.class, false);

      return null;
    }
  }
Exemplo n.º 3
0
 private static void register() {
   OperationRegistry operationRegistry = JAI.getDefaultInstance().getOperationRegistry();
   HMPitfillerDescriptor d = new HMPitfillerDescriptor();
   HMPitfillerRIF rif = new HMPitfillerRIF();
   String productName = "eu.hydrologis.jgrass";
   operationRegistry.registerDescriptor(d);
   RIFRegistry.register(operationRegistry, OPERATIONNAME, productName, rif);
 }
 public static synchronized void register(boolean force) {
   if (!registered || force) {
     OperationRegistry registry = JAI.getDefaultInstance().getOperationRegistry();
     PropertyGenerator[] stdGenerators = new WarpDescriptor().getPropertyGenerators("rendered");
     registry.addPropertyGenerator("rendered", "Warp", new GTWarpPropertyGenerator());
     registered = true;
   }
 }
Exemplo n.º 5
0
  /**
   * A convenience method for registering XTIFF methods into JAI, for extended classes of
   * XTIFFDescriptor.
   */
  public static void register(XTIFFDescriptor odesc) {

    OperationRegistry reg = JAI.getDefaultInstance().getOperationRegistry();

    // override tiff operation
    reg.unregisterOperationDescriptor("tiff");

    // ...and register tiff with the new desc
    reg.registerOperationDescriptor(odesc, "tiff");
    reg.registerRIF("tiff", "org.libtiff.jai", odesc);

    // re-register the tiff codec
    ImageCodec.unregisterCodec("tiff");
    ImageCodec.registerCodec(new XTIFFCodec());
  }
Exemplo n.º 6
0
 /**
  * Register the "RecodeNoData" image operation to the operation registry of the specified JAI
  * instance.
  */
 public static void register(final JAI jai) {
   final OperationRegistry registry = jai.getOperationRegistry();
   try {
     registry.registerDescriptor(new Descriptor());
     registry.registerFactory(
         RenderedRegistryMode.MODE_NAME, OPERATION_NAME, "geotools.org", new CRIF());
   } catch (IllegalArgumentException exception) {
     final LogRecord record =
         Loggings.format(Level.SEVERE, LoggingKeys.CANT_REGISTER_JAI_OPERATION_$1, OPERATION_NAME);
     record.setSourceMethodName("<classinit>");
     record.setThrown(exception);
     record.setLoggerName(LOGGER.getName());
     LOGGER.log(record);
   }
 }
 public void registerDescriptor(RegistryElementDescriptor descriptor) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.registerDescriptor(descriptor);
   } finally {
     writeLock.unlock();
   }
 }
 public void writeExternal(ObjectOutput out) throws IOException {
   Lock readLock = lock.readLock();
   try {
     readLock.lock();
     super.writeExternal(out);
   } finally {
     readLock.unlock();
   }
 }
 public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.readExternal(in);
   } finally {
     writeLock.unlock();
   }
 }
 public void initializeFromStream(InputStream in) throws IOException {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.initializeFromStream(in);
   } finally {
     writeLock.unlock();
   }
 }
 public void writeToStream(OutputStream out) throws IOException {
   Lock readLock = lock.readLock();
   try {
     readLock.lock();
     super.writeToStream(out);
   } finally {
     readLock.unlock();
   }
 }
 public void unregisterOperationDescriptor(String operationName) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.unregisterOperationDescriptor(operationName);
   } finally {
     writeLock.unlock();
   }
 }
 public void clearOperationPreferences(String operationName, String productName) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.clearOperationPreferences(operationName, productName);
   } finally {
     writeLock.unlock();
   }
 }
 public void clearPropertyState(String modeName) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.clearPropertyState(modeName);
   } finally {
     writeLock.unlock();
   }
 }
 public void registerServices(ClassLoader cl) throws IOException {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.registerServices(cl);
   } finally {
     writeLock.unlock();
   }
 }
 public void clearFactoryPreferences(String modeName, String descriptorName, String productName) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.clearFactoryPreferences(modeName, descriptorName, productName);
   } finally {
     writeLock.unlock();
   }
 }
 public void suppressAllProperties(String modeName, String descriptorName) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.suppressAllProperties(modeName, descriptorName);
   } finally {
     writeLock.unlock();
   }
 }
 public void copyPropertyFromSource(
     String modeName, String descriptorName, String propertyName, int sourceIndex) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.copyPropertyFromSource(modeName, descriptorName, propertyName, sourceIndex);
   } finally {
     writeLock.unlock();
   }
 }
  public void removeRegistryMode(String modeName) {

    Lock writeLock = lock.writeLock();
    try {
      writeLock.lock();
      super.removeRegistryMode(modeName);
    } finally {
      writeLock.unlock();
    }
  }
 public void removePropertyGenerator(
     String modeName, String descriptorName, PropertyGenerator generator) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.removePropertyGenerator(modeName, descriptorName, generator);
   } finally {
     writeLock.unlock();
   }
 }
 public void unregisterFactory(
     String modeName, String descriptorName, String productName, Object factory) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.unregisterFactory(modeName, descriptorName, productName, factory);
   } finally {
     writeLock.unlock();
   }
 }
 public void setProductPreference(
     String modeName,
     String descriptorName,
     String preferredProductName,
     String otherProductName) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.setProductPreference(modeName, descriptorName, preferredProductName, otherProductName);
   } finally {
     writeLock.unlock();
   }
 }
 public void unsetFactoryPreference(
     String modeName,
     String descriptorName,
     String productName,
     Object preferredOp,
     Object otherOp) {
   Lock writeLock = lock.writeLock();
   try {
     writeLock.lock();
     super.unsetFactoryPreference(modeName, descriptorName, productName, preferredOp, otherOp);
   } finally {
     writeLock.unlock();
   }
 }
Exemplo n.º 24
0
 private void construct() {
   final OperationRegistry operationRegistry = JAI.getDefaultInstance().getOperationRegistry();
   final List<OperationDescriptor> operationDescriptors =
       (List<OperationDescriptor>) operationRegistry.getDescriptors(OperationDescriptor.class);
   for (OperationDescriptor operationDescriptor : operationDescriptors) {
     final JsJaiFunction jaiFunction = new JsJaiFunction(operationDescriptor);
     defineProperty(jaiFunction.getClassName(), jaiFunction, ScriptableObject.READONLY);
     final Field[] fields = operationDescriptor.getClass().getFields();
     for (Field field : fields) {
       final int modifiers = field.getModifiers();
       if (Modifier.isPublic(modifiers)
           && Modifier.isStatic(modifiers)
           && Modifier.isFinal(modifiers)) {
         try {
           defineProperty(field.getName(), field.get(operationDescriptor), READONLY);
         } catch (IllegalAccessException e) {
           System.out.println(
               "Error: operationDescriptor="
                   + operationDescriptor
                   + ", field="
                   + field
                   + ", e="
                   + e);
         }
       }
     }
   }
   defineProperty(
       "INTERP_NEAREST", Interpolation.getInstance(Interpolation.INTERP_NEAREST), READONLY);
   defineProperty(
       "INTERP_BILINEAR", Interpolation.getInstance(Interpolation.INTERP_BILINEAR), READONLY);
   defineProperty(
       "INTERP_BICUBIC", Interpolation.getInstance(Interpolation.INTERP_BICUBIC), READONLY);
   defineProperty(
       "INTERP_BICUBIC_2", Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2), READONLY);
   defineFunctionProperties(new String[] {"show", "help"}, JsJai.class, ScriptableObject.DONTENUM);
 }
Exemplo n.º 25
0
 private static void initJAI(ClassLoader cl) {
   System.setProperty(
       "com.sun.media.jai.disableMediaLib", "true"); // disable native libraries for JAI
   // Must use a new operation registry in order to register JAI operators defined in Ceres and
   // BEAM
   OperationRegistry operationRegistry = OperationRegistry.getThreadSafeOperationRegistry();
   InputStream is = SystemUtils.class.getResourceAsStream(JAI_REGISTRY_PATH);
   if (is != null) {
     // Suppress ugly (and harmless) JAI error messages saying that a descriptor is already
     // registered.
     final PrintStream oldErr = System.err;
     try {
       setSystemErr(new PrintStream(new ByteArrayOutputStream()));
       operationRegistry.updateFromStream(is);
       operationRegistry.registerServices(cl);
       JAI.getDefaultInstance().setOperationRegistry(operationRegistry);
     } catch (IOException e) {
       BeamLogManager.getSystemLogger()
           .log(
               Level.SEVERE,
               MessageFormat.format("Error loading {0}: {1}", JAI_REGISTRY_PATH, e.getMessage()),
               e);
     } finally {
       setSystemErr(oldErr);
     }
   } else {
     BeamLogManager.getSystemLogger()
         .warning(MessageFormat.format("{0} not found", JAI_REGISTRY_PATH));
   }
   Integer parallelism =
       Integer.getInteger(
           BEAM_PARALLELISM_PROPERTY_NAME, Runtime.getRuntime().availableProcessors());
   JAI.getDefaultInstance().getTileScheduler().setParallelism(parallelism);
   BeamLogManager.getSystemLogger()
       .info(MessageFormat.format("JAI tile scheduler parallelism set to {0}", parallelism));
 }
  /**
   * 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.
   */
  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) {
        LOGGER.severe("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();
    }
  }
Exemplo n.º 27
0
  private static void printOperatorUsage(String name) {
    OperationRegistry operationRegistry = JAI.getDefaultInstance().getOperationRegistry();
    OperationDescriptor descriptor =
        (OperationDescriptor) operationRegistry.getDescriptor(OperationDescriptor.class, name);
    if (descriptor == null) {
      System.out.println("Unknown operation '" + name + "'");
      return;
    }

    String[][] resources = descriptor.getResources(Locale.getDefault());
    String globalName = resources[0][1];
    String description = resources[3][1];

    String[] sourceNames = descriptor.getSourceNames();
    Class[] sourceTypes = descriptor.getSourceClasses("rendered");
    ParameterListDescriptor parameterListDescriptor =
        descriptor.getParameterListDescriptor("rendered");
    String[] paramNames = parameterListDescriptor.getParamNames();
    Class[] paramTypes = parameterListDescriptor.getParamClasses();

    StringBuilder text = new StringBuilder();
    text.append("Usage: ");
    text.append(globalName);
    text.append('(');
    StringBuilder paramListText = new StringBuilder();
    if (sourceNames != null) {
      for (String sourceName : sourceNames) {
        if (paramListText.length() > 0) {
          paramListText.append(", ");
        }
        paramListText.append(sourceName);
      }
    }
    if (paramNames != null) {
      for (String paramName : paramNames) {
        if (paramListText.length() > 0) {
          paramListText.append(", ");
        }
        paramListText.append(paramName);
        Object defaultValue = parameterListDescriptor.getParamDefaultValue(paramName);
        if (defaultValue != ParameterListDescriptor.NO_PARAMETER_DEFAULT) {
          paramListText.append("=");
          paramListText.append(format(defaultValue));
        }
      }
    }
    text.append(paramListText);
    text.append(')');
    text.append('\n');
    text.append("Description: ");
    text.append(description);
    text.append('\n');
    text.append("Arguments:\n");
    if (sourceNames != null) {
      for (int i = 0; i < sourceNames.length; i++) {
        String sourceName = sourceNames[i];
        Class sourceType = sourceTypes[i];
        text.append("  ");
        text.append(sourceName);
        text.append(": ");
        text.append("A source.");
        text.append(" (" + sourceType.getName() + ")");
        text.append('\n');
      }
    }

    if (paramNames != null) {
      for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        Class paramType = paramTypes[i];

        text.append("  ");
        text.append(paramName);

        text.append(": ");
        text.append(resources[6 + i][1]);
        text.append(" (" + paramType.getName() + ")");
        text.append('\n');
      }
    }

    System.out.println(text);
  }