private File findConfigFile() throws IOException {
   File configFile = resourceLoader.find(CONFIG_FILE_NAME);
   if (configFile == null) {
     configFile = new File(resourceLoader.getBaseDirectory(), CONFIG_FILE_NAME);
   }
   return configFile;
 }
  public void handle(Request request, Response response) {
    String scriptName = (String) request.getAttributes().get("script");

    if (scriptName == null) {
      File scriptDirectory = null;
      try {
        scriptDirectory = resourceLoader.find(scriptPath);
      } catch (IOException ioe) {
        // no, it's cool. we might have to handle a null return anyway.
      }

      if (scriptDirectory == null)
        throw new RestletException("No script directory", Status.CLIENT_ERROR_NOT_FOUND);

      StringBuilder out = new StringBuilder();
      for (String script :
          scriptDirectory.list(
              new FilenameFilter() {
                public boolean accept(File f, String name) {
                  return name.endsWith(".js");
                }
              })) {
        out.append(script.substring(0, script.length() - 3)).append(", ");
      }
      response.setEntity(new StringRepresentation(out.toString()));
    } else {
      File script;
      try {
        script = resourceLoader.find(scriptPath, scriptName + ".js");
      } catch (IOException ioe) {
        throw new RestletException(
            "Requested script [" + scriptName + "] does not exist", Status.CLIENT_ERROR_NOT_FOUND);
      }

      Context cx = Context.enter();
      try {
        Scriptable scope = cx.initStandardObjects();
        FileReader reader = new FileReader(script);

        Object wrappedRequest = Context.javaToJS(request, scope);
        Object wrappedResponse = Context.javaToJS(response, scope);
        Object wrappedCatalog = Context.javaToJS(catalog, scope);
        Object wrappedLoader = Context.javaToJS(resourceLoader, scope);

        ScriptableObject.putProperty(scope, "request", wrappedRequest);
        ScriptableObject.putProperty(scope, "response", wrappedResponse);
        ScriptableObject.putProperty(scope, "loader", wrappedLoader);
        ScriptableObject.putProperty(scope, "catalog", wrappedCatalog);

        cx.evaluateReader(scope, reader, script.getName(), 1, null);
      } catch (IOException e) {
        throw new RestletException(
            "I/O error while loading script...", Status.SERVER_ERROR_INTERNAL);
      } finally {
        Context.exit();
      }
    }
  }
  private Resource findUserProperties() throws IOException {
    GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class);
    Resource propFile = loader.get("security/users.properties");

    InputStream is = null;
    OutputStream os = null;
    try {
      if (propFile.getType() == Type.RESOURCE) {
        // we're probably dealing with an old data dir, create
        // the file without
        // changing the username and password if possible
        Properties p = new Properties();
        GeoServerInfo global = GeoServerExtensions.bean(GeoServer.class).getGlobal();
        if ((global != null)
            && (global.getAdminUsername() != null)
            && !global.getAdminUsername().trim().equals("")) {
          p.put(global.getAdminUsername(), global.getAdminPassword() + ",ROLE_ADMINISTRATOR");
        } else {
          p.put("admin", "geoserver,ROLE_ADMINISTRATOR");
        }

        os = propFile.out();
        p.store(os, "Format: name=password,ROLE1,...,ROLEN");
        os.close();

        // setup a sample service.properties
        Resource serviceFile = loader.get("security/service.properties");
        os = serviceFile.out();
        is = GeoServerUserDao.class.getResourceAsStream("serviceTemplate.properties");
        byte[] buffer = new byte[1024];
        int count = 0;
        while ((count = is.read(buffer)) > 0) {
          os.write(buffer, 0, count);
        }
        return propFile;
      } else {
        throw new FileNotFoundException("Unable to find security/users.properties");
      }
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException ei) {
          /* nothing to do */
        }
      }
      if (os != null) {
        try {
          os.close();
        } catch (IOException eo) {
          /* nothing to do */
        }
      }
    }
  }
Example #4
0
  /** Copies a well known style out to the data directory and adds a catalog entry for it. */
  void initializeStyle(Catalog catalog, String styleName, String sld) throws IOException {

    // copy the file out to the data directory if necessary
    if (resourceLoader.find("styles", sld) == null) {
      FileUtils.copyURLToFile(
          GeoServerLoader.class.getResource(sld),
          new File(resourceLoader.findOrCreateDirectory("styles"), sld));
    }

    // create a style for it
    StyleInfo s = catalog.getFactory().createStyle();
    s.setName(styleName);
    s.setFilename(sld);
    catalog.add(s);
  }
Example #5
0
  protected void readCatalog(Catalog catalog, XStreamPersister xp) throws Exception {
    // we are going to synch up the catalogs and need to preserve listeners,
    // but these two fellas are attached to the new catalog as well
    catalog.removeListeners(ResourcePool.CacheClearingListener.class);
    catalog.removeListeners(GeoServerPersister.class);
    List<CatalogListener> listeners = new ArrayList<CatalogListener>(catalog.getListeners());

    // look for catalog.xml, if it exists assume we are dealing with
    // an old data directory
    File f = resourceLoader.find("catalog.xml");
    if (f == null) {
      // assume 2.x style data directory
      CatalogImpl catalog2 = (CatalogImpl) readCatalog(xp);
      // make to remove the old resource pool catalog listener
      ((CatalogImpl) catalog).sync(catalog2);
    } else {
      // import old style catalog, register the persister now so that we start
      // with a new version of the catalog
      CatalogImpl catalog2 = (CatalogImpl) readLegacyCatalog(f, xp);
      ((CatalogImpl) catalog).sync(catalog2);
    }

    // attach back the old listeners
    for (CatalogListener listener : listeners) {
      catalog.addListener(listener);
    }
  }
Example #6
0
 public LegendSampleImpl(Catalog catalog, GeoServerResourceLoader loader) {
   super();
   this.catalog = catalog;
   this.loader = loader;
   this.baseDir = loader.getBaseDirectory();
   this.clean();
   this.catalog.addListener(this);
 }
Example #7
0
 /**
  * Gets an SLD resource for the given style.
  *
  * @param style
  * @return
  */
 private Resource getStyleResource(StyleInfo style) {
   String[] prefix = new String[0];
   if (style.getWorkspace() != null) {
     prefix = new String[] {"workspaces", style.getWorkspace().getName()};
   }
   String fileName = style.getFilename();
   String[] pathParts = (String[]) ArrayUtils.addAll(prefix, new String[] {"styles", fileName});
   String path = Paths.path(pathParts);
   return loader.get(path);
 }
Example #8
0
  public static boolean writeConfigToDisk(ProxyConfig pc) {
    Resource.Lock lock = null;
    try {
      GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class);
      Resource configFile = loader.get("proxy/proxy.xml");

      XStream xs = new XStream();
      String xml = xs.toXML(pc);
      FileWriter fw = new FileWriter(configFile.file(), false); // false means overwrite old file
      // Take the write lock on the file & lock it
      lock = configFile.lock();
      fw.write(xml);
      fw.close();
      return true;
    } catch (Exception e) {
      LOG.warning("Failed to save configuration for Proxy module. Exception:" + e.toString());
      return false;
    } finally {
      if (lock != null) lock.release();
    }
  }
Example #9
0
  /* this is pretty unappealingly hackish */
  public static ProxyConfig loadConfFromDisk() {
    ProxyConfig retval;
    Resource.Lock lock = null;
    try {
      GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class);
      Resource configFile = loader.get("proxy/proxy.xml");
      lock = configFile.lock();

      InputStream proxyConfStream = configFile.in();
      XStream xs = new XStream();
      // Take the read lock, then read the file
      retval = (ProxyConfig) (xs.fromXML(proxyConfStream));
    } catch (Exception e) {
      LOG.warning(
          "Failed to open configuration for Proxy module. Using default. Exception:"
              + e.toString());
      // writeConfigToDisk(DEFAULT);
      retval = DEFAULT;
    } finally {
      if (lock != null) lock.release();
    }
    return retval;
  }
Example #10
0
  protected void readConfiguration(GeoServer geoServer, XStreamPersister xp) throws Exception {
    // look for services.xml, if it exists assume we are dealing with
    // an old data directory
    File f = resourceLoader.find("services.xml");
    if (f == null) {
      // assume 2.x style
      f = resourceLoader.find("global.xml");
      if (f != null) {
        GeoServerInfo global = depersist(xp, f, GeoServerInfo.class);
        geoServer.setGlobal(global);
      }

      // load logging
      f = resourceLoader.find("logging.xml");
      if (f != null) {
        LoggingInfo logging = depersist(xp, f, LoggingInfo.class);
        geoServer.setLogging(logging);
      }

      // load workspace specific settings
      File workspaces = resourceLoader.find("workspaces");
      if (workspaces != null) {
        for (File dir : workspaces.listFiles()) {
          if (!dir.isDirectory() && !dir.isHidden()) continue;

          f = resourceLoader.find(dir, "settings.xml");
          if (f != null) {
            SettingsInfo settings = depersist(xp, f, SettingsInfo.class);
            geoServer.add(settings);
          }
        }
      }

      // load services
      final List<XStreamServiceLoader> loaders =
          GeoServerExtensions.extensions(XStreamServiceLoader.class);
      loadServices(null, loaders, geoServer);

      // load services specific to workspace
      if (workspaces != null) {
        for (File dir : workspaces.listFiles()) {
          if (!dir.isDirectory() && !dir.isHidden()) continue;

          loadServices(dir, loaders, geoServer);
        }
      }

    } else {
      // add listener now as a converter which will convert from the old style
      // data directory to the new
      GeoServerPersister p = new GeoServerPersister(resourceLoader, xp);
      geoServer.addListener(p);

      // import old style services.xml
      new LegacyConfigurationImporter(geoServer).imprt(resourceLoader.getBaseDirectory());

      geoServer.removeListener(p);

      // rename the services.xml file
      f.renameTo(new File(f.getParentFile(), "services.xml.old"));
    }
  }
Example #11
0
  /** Reads the legacy (1.x) catalog from disk. */
  Catalog readLegacyCatalog(File f, XStreamPersister xp) throws Exception {
    Catalog catalog2 = new CatalogImpl();
    catalog2.setResourceLoader(resourceLoader);

    // add listener now as a converter which will convert from the old style
    // data directory to the new
    GeoServerPersister p = new GeoServerPersister(resourceLoader, xp);
    if (!legacy) {
      catalog2.addListener(p);
    }

    LegacyCatalogImporter importer = new LegacyCatalogImporter(catalog2);
    importer.setResourceLoader(resourceLoader);
    importer.imprt(resourceLoader.getBaseDirectory());

    if (!legacy) {
      catalog2.removeListener(p);
    }

    if (!legacy) {
      // copy files from old feature type directories to new
      File featureTypesDir = resourceLoader.find("featureTypes");
      if (featureTypesDir != null) {
        LegacyCatalogReader creader = new LegacyCatalogReader();
        creader.read(f);
        Map<String, Map<String, Object>> dataStores = creader.dataStores();

        for (File featureTypeDir : featureTypesDir.listFiles()) {
          if (!featureTypeDir.isDirectory()) {
            continue;
          }

          File featureTypeInfo = new File(featureTypeDir, "info.xml");
          if (!featureTypeInfo.exists()) {
            continue;
          }

          LegacyFeatureTypeInfoReader reader = new LegacyFeatureTypeInfoReader();
          reader.read(featureTypeInfo);

          Map<String, Object> dataStore = dataStores.get(reader.dataStore());
          if (dataStore == null) {
            continue;
          }

          String namespace = (String) dataStore.get("namespace");
          File destFeatureTypeDir =
              resourceLoader.find("workspaces", namespace, reader.dataStore(), reader.name());
          if (destFeatureTypeDir != null) {
            // copy all the files over
            for (File file : featureTypeDir.listFiles()) {
              if (file.isFile() && !featureTypeInfo.equals(file)) {
                FileUtils.copyFile(file, new File(destFeatureTypeDir, file.getName()));
              }
            }
          }
        }
      }

      // rename catalog.xml
      f.renameTo(new File(f.getParentFile(), "catalog.xml.old"));
    }

    return catalog2;
  }
Example #12
0
  /** Reads the catalog from disk. */
  Catalog readCatalog(XStreamPersister xp) throws Exception {
    CatalogImpl catalog = new CatalogImpl();
    catalog.setResourceLoader(resourceLoader);
    xp.setCatalog(catalog);
    xp.setUnwrapNulls(false);

    CatalogFactory factory = catalog.getFactory();

    // global styles
    loadStyles(resourceLoader.find("styles"), catalog, xp);

    // workspaces, stores, and resources
    File workspaces = resourceLoader.find("workspaces");
    if (workspaces != null) {
      // do a first quick scan over all workspaces, setting the default
      File dws = new File(workspaces, "default.xml");
      WorkspaceInfo defaultWorkspace = null;
      if (dws.exists()) {
        try {
          defaultWorkspace = depersist(xp, dws, WorkspaceInfo.class);
          LOGGER.info("Loaded default workspace " + defaultWorkspace.getName());
        } catch (Exception e) {
          LOGGER.log(Level.WARNING, "Failed to load default workspace", e);
        }
      } else {
        LOGGER.warning("No default workspace was found.");
      }

      for (File wsd : list(workspaces, DirectoryFileFilter.INSTANCE)) {
        File f = new File(wsd, "workspace.xml");
        if (!f.exists()) {
          continue;
        }

        WorkspaceInfo ws = null;
        try {
          ws = depersist(xp, f, WorkspaceInfo.class);
          catalog.add(ws);
        } catch (Exception e) {
          LOGGER.log(Level.WARNING, "Failed to load workspace '" + wsd.getName() + "'", e);
          continue;
        }

        LOGGER.info("Loaded workspace '" + ws.getName() + "'");

        // load the namespace
        File nsf = new File(wsd, "namespace.xml");
        NamespaceInfo ns = null;
        if (nsf.exists()) {
          try {
            ns = depersist(xp, nsf, NamespaceInfo.class);
            catalog.add(ns);
          } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Failed to load namespace for '" + wsd.getName() + "'", e);
          }
        }

        // set the default workspace, this value might be null in the case of coming from a
        // 2.0.0 data directory. See http://jira.codehaus.org/browse/GEOS-3440
        if (defaultWorkspace != null) {
          if (ws.getName().equals(defaultWorkspace.getName())) {
            catalog.setDefaultWorkspace(ws);
            if (ns != null) {
              catalog.setDefaultNamespace(ns);
            }
          }
        } else {
          // create the default.xml file
          defaultWorkspace = catalog.getDefaultWorkspace();
          if (defaultWorkspace != null) {
            try {
              persist(xp, defaultWorkspace, dws);
            } catch (Exception e) {
              LOGGER.log(
                  Level.WARNING, "Failed to persist default workspace '" + wsd.getName() + "'", e);
            }
          }
        }

        // load the styles for the workspace
        File styles = resourceLoader.find(wsd, "styles");
        if (styles != null) {
          loadStyles(styles, catalog, xp);
        }
      }

      for (File wsd : list(workspaces, DirectoryFileFilter.INSTANCE)) {

        // load the stores for this workspace
        for (File sd : list(wsd, DirectoryFileFilter.INSTANCE)) {
          File f = new File(sd, "datastore.xml");
          if (f.exists()) {
            // load as a datastore
            DataStoreInfo ds = null;
            try {
              ds = depersist(xp, f, DataStoreInfo.class);
              catalog.add(ds);

              LOGGER.info("Loaded data store '" + ds.getName() + "'");

              if (ds.isEnabled()) {
                // connect to the datastore to determine if we should disable it
                try {
                  ds.getDataStore(null);
                } catch (Throwable t) {
                  LOGGER.warning("Error connecting to '" + ds.getName() + "'. Disabling.");
                  LOGGER.log(Level.INFO, "", t);

                  ds.setError(t);
                  ds.setEnabled(false);
                }
              }
            } catch (Exception e) {
              LOGGER.log(Level.WARNING, "Failed to load data store '" + sd.getName() + "'", e);
              continue;
            }

            // load feature types
            for (File ftd : list(sd, DirectoryFileFilter.INSTANCE)) {
              f = new File(ftd, "featuretype.xml");
              if (f.exists()) {
                FeatureTypeInfo ft = null;
                try {
                  ft = depersist(xp, f, FeatureTypeInfo.class);
                } catch (Exception e) {
                  LOGGER.log(
                      Level.WARNING, "Failed to load feature type '" + ftd.getName() + "'", e);
                  continue;
                }

                catalog.add(ft);

                LOGGER.info("Loaded feature type '" + ds.getName() + "'");

                f = new File(ftd, "layer.xml");
                if (f.exists()) {
                  try {
                    LayerInfo l = depersist(xp, f, LayerInfo.class);
                    catalog.add(l);

                    LOGGER.info("Loaded layer '" + l.getName() + "'");
                  } catch (Exception e) {
                    LOGGER.log(
                        Level.WARNING,
                        "Failed to load layer for feature type '" + ft.getName() + "'",
                        e);
                  }
                }
              } else {
                LOGGER.warning("Ignoring feature type directory " + ftd.getAbsolutePath());
              }
            }
          } else {
            // look for a coverage store
            f = new File(sd, "coveragestore.xml");
            if (f.exists()) {
              CoverageStoreInfo cs = null;
              try {
                cs = depersist(xp, f, CoverageStoreInfo.class);
                catalog.add(cs);

                LOGGER.info("Loaded coverage store '" + cs.getName() + "'");
              } catch (Exception e) {
                LOGGER.log(
                    Level.WARNING, "Failed to load coverage store '" + sd.getName() + "'", e);
                continue;
              }

              // load coverages
              for (File cd : list(sd, DirectoryFileFilter.INSTANCE)) {
                f = new File(cd, "coverage.xml");
                if (f.exists()) {
                  CoverageInfo c = null;
                  try {
                    c = depersist(xp, f, CoverageInfo.class);
                    catalog.add(c);

                    LOGGER.info("Loaded coverage '" + cs.getName() + "'");
                  } catch (Exception e) {
                    LOGGER.log(Level.WARNING, "Failed to load coverage '" + cd.getName() + "'", e);
                    continue;
                  }

                  f = new File(cd, "layer.xml");
                  if (f.exists()) {
                    try {
                      LayerInfo l = depersist(xp, f, LayerInfo.class);
                      catalog.add(l);

                      LOGGER.info("Loaded layer '" + l.getName() + "'");
                    } catch (Exception e) {
                      LOGGER.log(
                          Level.WARNING, "Failed to load layer coverage '" + c.getName() + "'", e);
                    }
                  }
                } else {
                  LOGGER.warning("Ignoring coverage directory " + cd.getAbsolutePath());
                }
              }
            } else {
              f = new File(sd, "wmsstore.xml");
              if (f.exists()) {
                WMSStoreInfo wms = null;
                try {
                  wms = depersist(xp, f, WMSStoreInfo.class);
                  catalog.add(wms);

                  LOGGER.info("Loaded wmsstore '" + wms.getName() + "'");
                } catch (Exception e) {
                  LOGGER.log(Level.WARNING, "Failed to load wms store '" + sd.getName() + "'", e);
                  continue;
                }

                // load wms layers
                for (File cd : list(sd, DirectoryFileFilter.INSTANCE)) {
                  f = new File(cd, "wmslayer.xml");
                  if (f.exists()) {
                    WMSLayerInfo wl = null;
                    try {
                      wl = depersist(xp, f, WMSLayerInfo.class);
                      catalog.add(wl);

                      LOGGER.info("Loaded wms layer'" + wl.getName() + "'");
                    } catch (Exception e) {
                      LOGGER.log(
                          Level.WARNING, "Failed to load wms layer '" + cd.getName() + "'", e);
                      continue;
                    }

                    f = new File(cd, "layer.xml");
                    if (f.exists()) {
                      try {
                        LayerInfo l = depersist(xp, f, LayerInfo.class);
                        catalog.add(l);

                        LOGGER.info("Loaded layer '" + l.getName() + "'");
                      } catch (Exception e) {
                        LOGGER.log(
                            Level.WARNING,
                            "Failed to load cascaded wms layer '" + wl.getName() + "'",
                            e);
                      }
                    }
                  } else {
                    LOGGER.warning("Ignoring coverage directory " + cd.getAbsolutePath());
                  }
                }
              } else if (!isConfigDirectory(sd)) {
                LOGGER.warning("Ignoring store directory '" + sd.getName() + "'");
                continue;
              }
            }
          }
        }

        // load hte layer groups for this workspace
        File layergroups = resourceLoader.find(wsd, "layergroups");
        if (layergroups != null) {
          loadLayerGroups(layergroups, catalog, xp);
        }
      }
    } else {
      LOGGER.warning("No 'workspaces' directory found, unable to load any stores.");
    }

    // namespaces

    // layergroups
    File layergroups = resourceLoader.find("layergroups");
    if (layergroups != null) {
      loadLayerGroups(layergroups, catalog, xp);
    }
    xp.setUnwrapNulls(true);
    catalog.resolve();
    return catalog;
  }
 public void initialize(H2DataStoreFactory factory) {
   factory.setBaseDirectory(resourceLoader.getBaseDirectory());
 }
 public ResumableUploadResourceManager(String tmpFolder) {
   GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class);
   tmpUploadFolder = loader.get(tmpFolder);
 }
Example #15
0
  public static void configureGeoServerLogging(
      GeoServerResourceLoader loader,
      InputStream loggingConfigStream,
      boolean suppressStdOutLogging,
      boolean suppressFileLogging,
      String logFileName)
      throws FileNotFoundException, IOException, ConfigurationException {
    // JD: before we wipe out the logging configuration, save any appenders that are not
    // console or file based. This allows for other types of appenders to remain in tact
    // when geoserver is reloaded.
    List<Appender> appenders = new ArrayList();
    Enumeration a = LogManager.getRootLogger().getAllAppenders();
    while (a.hasMoreElements()) {
      Appender appender = (Appender) a.nextElement();
      if (!(appender instanceof ConsoleAppender || appender instanceof FileAppender)) {
        // save it
        appenders.add(appender);
      }
    }

    Properties lprops = new Properties();
    lprops.load(loggingConfigStream);
    LogManager.resetConfiguration();
    //        LogLog.setQuietMode(true);
    PropertyConfigurator.configure(lprops);
    //        LogLog.setQuietMode(false);

    // configuring the log4j file logger
    if (!suppressFileLogging) {
      Appender gslf = org.apache.log4j.Logger.getRootLogger().getAppender("geoserverlogfile");
      if (gslf instanceof org.apache.log4j.FileAppender) {
        if (logFileName == null) {
          logFileName =
              new File(loader.findOrCreateDirectory("logs"), "geoserver.log").getAbsolutePath();
        } else {
          if (!new File(logFileName).isAbsolute()) {
            logFileName = new File(loader.getBaseDirectory(), logFileName).getAbsolutePath();
            LoggingInitializer.LOGGER.fine(
                "Non-absolute pathname detected for logfile.  Setting logfile relative to data dir.");
          }
        }
        lprops.setProperty("log4j.appender.geoserverlogfile.File", logFileName);
        PropertyConfigurator.configure(lprops);
        LoggingInitializer.LOGGER.fine("Logging output to file '" + logFileName + "'");
      } else if (gslf != null) {
        LoggingInitializer.LOGGER.warning(
            "'log4j.appender.geoserverlogfile' appender is defined, but isn't a FileAppender.  GeoServer won't control the file-based logging.");
      } else {
        LoggingInitializer.LOGGER.warning(
            "'log4j.appender.geoserverlogfile' appender isn't defined.  GeoServer won't control the file-based logging.");
      }
    }

    // ... and the std output logging too
    if (suppressStdOutLogging) {
      LoggingInitializer.LOGGER.info(
          "Suppressing StdOut logging.  If you want to see GeoServer logs, be sure to look in '"
              + logFileName
              + "'");
      Enumeration allAppenders = org.apache.log4j.Logger.getRootLogger().getAllAppenders();
      Appender curApp;
      while (allAppenders.hasMoreElements()) {
        curApp = (Appender) allAppenders.nextElement();
        if (curApp instanceof org.apache.log4j.ConsoleAppender) {
          org.apache.log4j.Logger.getRootLogger().removeAppender(curApp);
        }
      }
    }

    // add the appenders we saved above
    for (Appender appender : appenders) {
      LogManager.getRootLogger().addAppender(appender);
    }
    LoggingInitializer.LOGGER.fine(
        "FINISHED CONFIGURING GEOSERVER LOGGING -------------------------");
  }
Example #16
0
  public static void initLogging(
      GeoServerResourceLoader resourceLoader,
      String configFileName,
      boolean suppressStdOutLogging,
      String logFileName)
      throws Exception {
    // to initialize logging we need to do a couple of things:
    // 1)  Figure out whether the user has 'overridden' some configuration settings
    // in the logging system (not using log4j in commons-logging.properties or perhaps
    // has set up their own 'custom' log4j.properties file.
    // 2)  If they *have*, then we don't worry about configuring logging
    // 3)  If they haven't, then we configure logging to use the log4j config file
    // specified, and remove console appenders if the suppressstdoutlogging is true.
    LoggingInitializer.LOGGER.fine("CONFIGURING GEOSERVER LOGGING -------------------------");

    if (configFileName == null) {
      configFileName = "DEFAULT_LOGGING.properties";
      LoggingInitializer.LOGGER.warning(
          "No log4jConfigFile defined in services.xml:  using 'DEFAULT_LOGGING.properties'");
    }
    Resource resource = resourceLoader.get(Paths.path("logs", configFileName));
    if (resource == null || resource.getType() == Type.UNDEFINED) {
      // hmm, well, we don't have a log4j config file and this could be due to the fact
      // that this is a data-dir upgrade.  We can count on the DEFAULT_LOGGING.properties file
      // being present on the classpath, so we'll upgrade their data_dir and then use the
      // default DEFAULT_LOGGING.properties configuration.
      LoggingInitializer.LOGGER.warning(
          "log4jConfigFile '"
              + configFileName
              + "' couldn't be found in the data dir, so GeoServer will "
              + "install the various logging config file into the data dir, and then try to find it again.");

      Resource logs = resourceLoader.get("logs");
      File lcdir = logs.dir();

      // now we copy in the various logging config files from the base repo location on the
      // classpath
      final String[] lcfiles =
          new String[] {
            "DEFAULT_LOGGING.properties",
            "GEOSERVER_DEVELOPER_LOGGING.properties",
            "GEOTOOLS_DEVELOPER_LOGGING.properties",
            "PRODUCTION_LOGGING.properties",
            "QUIET_LOGGING.properties",
            "TEST_LOGGING.properties",
            "VERBOSE_LOGGING.properties"
          };

      for (int i = 0; i < lcfiles.length; i++) {
        File target = new File(lcdir.getAbsolutePath(), lcfiles[i]);
        if (!target.exists()) {
          resourceLoader.copyFromClassPath(lcfiles[i], target);
        }
      }

      // ok, the possibly-new 'logs' directory is in-place, with all the various configs there.
      // Is the originally configured log4jconfigfile there now?
      if (resource.getType() != Type.RESOURCE) {
        LoggingInitializer.LOGGER.warning(
            "Still couldn't find log4jConfigFile '"
                + configFileName
                + "'.  Using DEFAULT_LOGGING.properties instead.");
      }

      resource = resourceLoader.get(Paths.path("logs", "DEFAULT_LOGGING.properties"));
    }

    if (resource == null || resource.getType() != Type.RESOURCE) {
      throw new ConfigurationException(
          "Unable to load logging configuration '"
              + configFileName
              + "'.  In addition, an attempt "
              + "was made to create the 'logs' directory in your data dir, and to use the DEFAULT_LOGGING configuration, but"
              + "this failed as well.  Is your data dir writeable?");
    }

    // reconfiguring log4j logger levels by resetting and loading a new set of configuration
    // properties
    InputStream loggingConfigStream = resource.in();
    if (loggingConfigStream == null) {
      LoggingInitializer.LOGGER.warning("Couldn't open Log4J configuration file '" + resource);
      return;
    } else {
      LoggingInitializer.LOGGER.fine(
          "GeoServer logging profile '" + resource.name() + "' enabled.");
    }

    configureGeoServerLogging(
        resourceLoader, loggingConfigStream, suppressStdOutLogging, false, logFileName);
  }