⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 geoserver.java

📁 电子地图服务器,搭建自己的地图服务
💻 JAVA
📖 第 1 页 / 共 3 页
字号:

    /**
    * getLoggingLevel purpose.
    *
    * <p>
    * Returns the Logging Level.
    * </p>
    *
    * @return String the Logging Level.
    */
    public String getLog4jConfigFile() {
        return log4jConfigFile;
    }

    /**
     * getMaxFeatures purpose.
     *
     * <p>
     * Returns the max number of features supported.
     * </p>
     *
     * @return String the max number of features supported.
     */
    public int getMaxFeatures() {
        return maxFeatures;
    }

    /**
     * getMimeType purpose.
     *
     * <p>
     * Returns the server default mimetype.
     * </p>
     *
     * @return String the server default mimetype.
     */
    public String getMimeType() {
        return "text/xml; charset=" + getCharSet().name();
    }

    /**
     * getNumDecimals purpose.
     *
     * <p>
     * The default number of decimals allowed in the data.
     * </p>
     *
     * @return int the default number of decimals allowed in the data.
     */
    public int getNumDecimals() {
        return numDecimals;
    }

    /**
     * getSchemaBaseUrl purpose.
     *
     * <p>
     * The Schema Base URL for this instance.  This should generally be a local
     * reference, as GeoServer by default puts up the schemas that it needs
     * and references them.  It could be used to specify an alternate site for
     * the schemas, however, for example if a user didn't want their servlet
     * container hit every time someone did a validation, they could instead
     * store it on another machine.  I don't really know if this is useful to
     * anyone...
     * </p>
     *
     * @return String the Schema Base URL for this instance.
     *
     * @task TODO: Right now this is broken, and I'm not quite sure if there's
     *       an elegant way to have this return the local schemas.  Perhaps we
     *       should just have it return 'local', and then the users of this
     *       method can do the local referencing themselves.  For now no one
     *       is using this  method, perhaps we should just leave it out for
     *       1.2.0, as it's very  obscure.  I think I only added it originally
     *       because I didn't want to  go through the busy work of cleaning up
     *       and figuring out how to copy over the ogc schemas.
     */
    public String getSchemaBaseUrl() {
        return schemaBaseUrl;
    }

    /**
     * Used when Geoserver is running behind a reverse-proxy so that url
     * in getCapabilities documents are fine
     * @return
     */
    public String getProxyBaseUrl() {
        return proxyBaseUrl;
    }

    /**
     * whether xml documents should be pretty formatted
     *
     * @return true when verbose
     */
    public boolean isVerbose() {
        return verbose;
    }

    /**
     * <p>
     * Loads the GeoServerDTO into the current instance as a GeoServer object
     * </p>
     *
     * @param dto
     * @throws ConfigurationException
     */
    public void load(GeoServerDTO dto) throws ConfigurationException {
        if (dto != null) {
            address = dto.getContact().getAddress();
            addressCity = dto.getContact().getAddressCity();
            addressCountry = dto.getContact().getAddressCountry();
            addressPostalCode = dto.getContact().getAddressPostalCode();
            addressState = dto.getContact().getAddressState();
            addressType = dto.getContact().getAddressType();
            charSet = dto.getCharSet();
            contactEmail = dto.getContact().getContactEmail();
            contactFacsimile = dto.getContact().getContactFacsimile();
            contactOrganization = dto.getContact().getContactOrganization();
            contactPerson = dto.getContact().getContactPerson();
            contactPosition = dto.getContact().getContactPosition();
            contactVoice = dto.getContact().getContactVoice();
            
            log4jConfigFile = dto.getLog4jConfigFile();
            suppressStdOutLogging = dto.getSuppressStdOutLogging();
            logLocation = dto.getLogLocation();
            try {
                configureGeoServerLogging(log4jConfigFile, suppressStdOutLogging, logLocation);
            } catch (IOException ioe) {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.log(Level.FINE,"",ioe);
                }
                throw new ConfigurationException("", ioe);
            }
            
            memoryCapacity = dto.getJaiMemoryCapacity();
            memoryThreshold = dto.getJaiMemoryThreshold();
            tileThreads = dto.getJaiTileThreads();
            tilePriority = dto.getJaiTilePriority();
            tileCache = dto.getTileCache();
            recycling = dto.getJaiRecycling();
            imageIOCache = dto.getImageIOCache();
            JPEGnativeAcc = dto.getJaiJPEGNative();
            PNGnativeAcc = dto.getJaiPNGNative();

            initJAI(memoryCapacity, memoryThreshold, recycling, imageIOCache);

            maxFeatures = dto.getMaxFeatures();
            numDecimals = dto.getNumDecimals();
            onlineResource = dto.getContact().getOnlineResource();
            schemaBaseUrl = dto.getSchemaBaseUrl();
            proxyBaseUrl = dto.getProxyBaseUrl();
            verbose = dto.isVerbose();
            adminUserName = dto.getAdminUserName();
            adminPassword = dto.getAdminPassword();
            verboseExceptions = dto.isVerboseExceptions();
        } else {
            throw new ConfigurationException("load(GeoServerDTO) expected a non-null value");
        }
    }

    /**
     *
     * load purpose.
     *
     * <p>
     * Loads the GeoServerDTO into the current instance as a GeoServer object.
     * As GeoServer moves to Spring, we want to move away from storing state
     * in the servlet context, so this method is deprecated.
     * </p>
     *
     * @param dto GeoServerDTO
     *
     * @throws ConfigurationException If an error occurs
     *
     * @deprecated use {@link #load(GeoServerDTO)}
     */
    public final void load(GeoServerDTO dto, ServletContext context)
        throws ConfigurationException {
        load(dto);
    }

    /**
     * Convenience method for determining the actual location on the local file
     * system of the log file based an arbirtrary path. Relative paths are
     * appended to the geoserver data directory.
     *
     * @param location The log file path, this can be an absolute or relative
     * path.
     * @param context The servlet context
     *
     * @return The file containing the absolute path to the log file.
     * @throws IOException
     */
    public static File getLogLocation(String logLocation)
        throws IOException {
        File f = new File(logLocation);

        if (f.exists()) {
            if (f.isDirectory()) {
                //attach a file to the end of the directory
                if (!logLocation.endsWith(File.separator)) {
                    logLocation += File.separator;
                }

                logLocation += "geoserver.log";
            }
        } else {
            //could be a relative path
            if (!f.isAbsolute()) {
                //append to data dir
                File data = GeoserverDataDirectory.getGeoserverDataDirectory();
                f = new File(data, f.getPath());
            }

            //make sure parent directory exists
            if ((f.getParentFile() != null) && !f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            f.createNewFile();
        }

        return f;
    }
    
    public static void configureGeoServerLogging(String log4jConfigFileStr, boolean suppressStdOutLogging, String logFileName) throws IOException, ConfigurationException {
        
        //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.
        LOGGER.fine("CONFIGURING GEOSERVER LOGGING -------------------------");
        
        if (log4jConfigFileStr == null) {
            log4jConfigFileStr = "DEFAULT_LOGGING.properties";
            LOGGER.warning("No log4jConfigFile defined in services.xml:  using 'DEFAULT_LOGGING.properties'");
        }
        
        File log4jConfigFile = GeoserverDataDirectory.findConfigFile("logs"+ File.separator + log4jConfigFileStr);
        
        if (log4jConfigFile == null) {
            //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.
            LOGGER.warning("log4jConfigFile '" + log4jConfigFileStr + "' 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.");
            
            //this forces the data_dir/logs directory to be present (if it wasn't already)
            File lcdir = GeoserverDataDirectory.findCreateConfigDir("logs");
            
            //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",
                    "VERBOSE_LOGGING.properties",
                    "PRODUCTION_LOGGING.properties",
                    "GEOTOOLS_DEVELOPER_LOGGING.properties",
                    "GEOSERVER_DEVELOPER_LOGGING.properties" };
            
            for (int i = 0; i < lcfiles.length; i++) {
                File target = new File(lcdir.getAbsolutePath(), lcfiles[i]);
                if (!target.exists()) {
                    copyResourceToFile(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?
            log4jConfigFile = GeoserverDataDirectory.findConfigFile("logs" + File.separator + log4jConfigFileStr);
            if (log4jConfigFile == null) {
                LOGGER.warning("Still couldn't find log4jConfigFile '" + log4jConfigFileStr + "'.  Using DEFAULT_LOGGING.properties instead.");
            }
            
            log4jConfigFile = GeoserverDataDirectory.findConfigFile("logs" + File.separator + "DEFAULT_LOGGING.properties");
        }

        if (log4jConfigFile == null) {
            throw new ConfigurationException("Unable to load logging configuration '" + log4jConfigFileStr + "'.  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 = new FileInputStream(log4jConfigFile);
        if (loggingConfigStream == null) {
            LOGGER.warning("Couldn't find Log4J configuration file '" + log4jConfigFileStr + "' in the 'loggingConfigs' directory.");
            return;
        } else {
            LOGGER.fine("GeoServer logging profile '" + log4jConfigFile.getName() + "' enabled.");
        }

        Properties lprops = new Properties();
        lprops.load(loggingConfigStream);
        LogManager.resetConfiguration();
        PropertyConfigurator.configure(lprops);
        
        // configuring the log4j file logger
        Appender gslf = org.apache.log4j.Logger.getRootLogger().getAppender("geoserverlogfile");
        if (gslf instanceof org.apache.log4j.RollingFileAppender) {
            if (logFileName == null ) {
                logFileName = new File(GeoserverDataDirectory.findCreateConfigDir("logs"),  "geoserver.log").getAbsolutePath();
            } else { 
                if (!new File(logFileName).isAbsolute()) {
                    logFileName = new File(GeoserverDataDirectory.getGeoserverDataDirectory(), logFileName).getAbsolutePath();
                    LOGGER.fine("Non-absolute pathname detected for logfile.  Setting logfile relative to data dir.");
                }
            }
            lprops.setProperty("log4j.appender.geoserverlogfile.File", logFileName);
            PropertyConfigurator.configure(lprops);
            LOGGER.fine("Logging output to file '" + logFileName + "'");
        } else if (gslf != null) {
            LOGGER.warning("'log4j.appender.geoserverlogfile' appender is defined, but isn't a RollingFileAppender.  GeoServer won't control the file-based logging.");
        } else {
            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) {
            LOGGER.warning("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);
                }
            }
        } else {
            LOGGER.info("StdOut logging enabled.  Log file also output to '" + logFileName + "'");
        }
        LOGGER.fine("FINISHED CONFIGURING GEOSERVER LOGGING -------------------------");
    }

    private static void copyResourceToFile(String resource, File target) throws ConfigurationException {
        InputStream is = null; 
        OutputStream os = null;
        byte[] buffer = new byte[4096];
        int read;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
            os = new FileOutputStream(target);
            while((read = is.read(buffer)) > 0)
                os.write(buffer, 0, read);
        } catch (FileNotFoundException targetException) {
            throw new ConfigurationException("Can't write to file " + target.getAbsolutePath() + 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -