Example usage for java.io IOException getClass

List of usage examples for java.io IOException getClass

Introduction

In this page you can find the example usage for java.io IOException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:de.innovationgate.wgpublisher.WGACore.java

@SuppressWarnings({ "deprecation", "deprecation" })
private void initReadGeneralConfig(boolean update) throws CacheException, OptionConversionException {

    logCategoryInfo("General Configuration", 1);

    OptionReader cacheOptions = OptionReader.create(_wgaConfiguration.getServerOptions(),
            new CacheModuleDefinition());

    // WebTML Cache
    int tmlCache = _wgaConfiguration.getWebtmlCacheSize();
    if (_webTMLCache == null) {
        _webTMLCache = new WebTMLCache(this, _wgaConfiguration);
    } else {/*from www.  j a v  a  2  s  .  c o m*/
        if (_webTMLCache.configure(_wgaConfiguration)) {
            getLog().info(
                    "WebTML Cache configuration updated. Will not be effective until next WebTML cache reset.");
        }
    }

    _webserviceEnabled = _wgaConfiguration.isWebservicesEnabled();

    _characterEncoding = _wgaConfiguration.getCharacterEncoding();
    if (_characterEncoding == null) {
        _characterEncoding = "UTF-8";
    }
    log.info("Using default output encoding '" + _characterEncoding + "'.");

    tmlBuffer = _wgaConfiguration.getTmlBuffer();
    if (_wgaConfiguration.getTmlHeader() != null) {
        tmlHeader = _wgaConfiguration.getTmlHeader();
    } else {
        tmlHeader = "";
    }

    // determine if character encoding changed
    // this is used for SC_NOT_MODIFIED in WGPDispatcher
    if (_characterEncoding != null && getLastCharacterEncoding() == null
            || !getLastCharacterEncoding().equals(_characterEncoding)) {
        // character encoding was not yet set or has changed           
        setLastCharacterEncoding(_characterEncoding);
    }

    // application log
    this.log.setLevel(org.apache.log4j.Level.toLevel(_wgaConfiguration.getApplicationLogLevel()));
    if (_wgaConfiguration.getApplicationLogDirectory() != null) {
        File loggingDir = new File(_wgaConfiguration.getApplicationLogDirectory());
        if (loggingDir.exists()) {
            try {
                Appender fileAppender = new DailyRollingFileAppender(new PatternLayout("%d{HH:mm:ss} %p %m\n"),
                        loggingDir.getAbsolutePath() + "/" + "wga.log", "yyyy-MM-dd");
                this.log.addAppender(fileAppender);
            } catch (IOException e) {
                this.log.error("Error creating application log file", e);
                _problemRegistry.addProblem(Problem.create(new UpdateConfigOccasion(),
                        "updateConfigProblem.invalidApplicationLog", ProblemSeverity.HIGH, e));
            }
        } else {
            this.log.error("Logging directory " + loggingDir.getAbsolutePath() + " does not exist");
            _problemRegistry
                    .addProblem(Problem.create(new UpdateConfigOccasion(), "updateConfigProblem.missingLogDir",
                            ProblemSeverity.HIGH, Problem.var("dir", loggingDir.getAbsolutePath())));
        }
    }

    // Lucene
    if (update == false && _wgaConfiguration.getLuceneManagerConfiguration().isEnabled()) {
        try {
            this.luceneManager = LuceneManager.retrieve(this,
                    _wgaConfiguration.getLuceneManagerConfiguration());
            log.debug("Lucene option 'maxBooleanClauseCount' set to '"
                    + this.luceneManager.getBooleanQueryMaxClauseCount() + "'.");
            log.debug("Lucene option 'maxDocsPerDBSession' set to '"
                    + this.luceneManager.getMaxDocsPerDBSession() + "'.");
            log.info("Lucene fulltext index enabled using index directory "
                    + this.luceneManager.getIndexDirectory().getAbsolutePath());
        } catch (Exception e) {
            log.error("Unable to initialize Lucene fulltext index: " + e.getClass().getName() + " - ", e);
            _problemRegistry.addProblem(Problem.create(new UpdateConfigOccasion(),
                    "updateConfigProblem.invalidLuceneIndex", ProblemSeverity.HIGH, e));
        }
    }

    // File derivates
    if (update == false) {
        this.fileDerivateManager = new FileDerivateManager(this); // Will be inited later on startup
    } else {
        this.fileDerivateManager.init(_wgaConfiguration);
    }

    // Personalisation
    userAgentVerifier = new UserAgentVerifier(_wgaConfiguration.getPersonalisationConfiguration(), this);

    // Design
    DesignConfiguration designConfig = _wgaConfiguration.getDesignConfiguration();
    designFileValidator = new DesignFileValidator(designConfig, this);
    if (designConfig.getDefaultEncoding() == null) {
        designConfig.setDefaultEncoding(DEFAULT_FILE_ENCODING);
        getLog().info("No default design file encoding configured. Using '" + DEFAULT_FILE_ENCODING + "'.");
    }

    if (designFileCache == null) {
        String designFileCacheSizeStr = _wgaConfiguration.getServerOptions()
                .get(WGAConfiguration.SERVEROPTION_CACHE_DESIGN_SIZE);
        if (designFileCacheSizeStr == null) {
            designFileCacheSizeStr = String.valueOf(designConfig.getDesignFileCacheSize());
        }
        designFileCache = CacheFactory.createCache(CACHENAME_DESIGNFILES,
                Integer.parseInt(designFileCacheSizeStr), null);
    }

    // Custom core listeners - Get names here, instantiate later when
    // library loader is inited       
    if (update == false) {
        customCoreListenerClassnames = new HashSet(_wgaConfiguration.getCoreEventListeners());
    }

    // init mail configuration
    _mailConfig = WGAMailConfiguration.create(_wgaConfiguration.getMailConfiguration());
    WGFactory.setHttpClientFactory(new DefaultHttpClientFactory(_wgaConfiguration));

}

From source file:net.yacy.yacy.java

/**
* Starts up the whole application. Sets up all datastructures and starts
* the main threads./*ww w  . j av a 2  s.  co m*/
*
* @param homePath Root-path where all information is to be found.
* @param startupFree free memory at startup time, to be used later for statistics
*/
private static void startup(final File dataHome, final File appHome, final long startupMemFree,
        final long startupMemTotal, final boolean gui) {
    String tmpdir = null;
    try {
        // start up
        System.out.println(copyright);
        System.out.println(hline);

        // ensure that there is a DATA directory, if not, create one and if that fails warn and die
        mkdirsIfNeseccary(dataHome);
        mkdirsIfNeseccary(appHome);
        File f = new File(dataHome, "DATA/");
        mkdirsIfNeseccary(f);
        if (!(f.exists())) {
            System.err.println("Error creating DATA-directory in " + dataHome.toString()
                    + " . Please check your write-permission for this folder. YaCy will now terminate.");
            System.exit(-1);
        }

        // set jvm tmpdir to a subdir for easy cleanup (as extensive use file.deleteonexit waists memory during long runs, as todelete files names are collected and never cleaned up during runtime)
        // keep this as earlier as possible, as any other class can use the "java.io.tmpdir" property, even the log manager, when the log file pattern uses "%t" as an alias for the tmp directory 
        try {
            tmpdir = java.nio.file.Files.createTempDirectory("yacy-tmp-").toString(); // creates sub dir in jvm's temp (see System.property "java.io.tempdir")
            System.setProperty("java.io.tmpdir", tmpdir);
        } catch (IOException ex) {
        }

        // setting up logging
        f = new File(dataHome, "DATA/LOG/");
        mkdirsIfNeseccary(f);
        f = new File(dataHome, "DATA/LOG/yacy.logging");
        final File f0 = new File(appHome, "defaults/yacy.logging");
        if (!f.exists() || f0.lastModified() > f.lastModified())
            try {
                Files.copy(f0, f);
            } catch (final IOException e) {
                System.out.println("could not copy yacy.logging");
            }
        try {
            ConcurrentLog.configureLogging(dataHome, new File(dataHome, "DATA/LOG/yacy.logging"));
        } catch (final IOException e) {
            System.out.println("could not find logging properties in homePath=" + dataHome);
            ConcurrentLog.logException(e);
        }
        ConcurrentLog.config("STARTUP", "YaCy version: " + yacyBuildProperties.getVersion() + "/"
                + yacyBuildProperties.getSVNRevision());
        ConcurrentLog.config("STARTUP",
                "Java version: " + System.getProperty("java.version", "no-java-version"));
        ConcurrentLog.config("STARTUP", "Operation system: " + System.getProperty("os.name", "unknown"));
        ConcurrentLog.config("STARTUP", "Application root-path: " + appHome);
        ConcurrentLog.config("STARTUP", "Data root-path: " + dataHome);
        ConcurrentLog.config("STARTUP", "Time zone: UTC" + GenericFormatter.UTCDiffString() + "; UTC+0000 is "
                + System.currentTimeMillis());
        ConcurrentLog.config("STARTUP", "Maximum file system path length: " + OS.maxPathLength);

        f = new File(dataHome, "DATA/yacy.running");
        final String conf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator);
        if (!f.createNewFile())
            ConcurrentLog.severe("STARTUP", "WARNING: the file " + f + " can not be created!");
        try {
            new FileOutputStream(f).write(Integer.toString(OS.getPID()).getBytes());
        } catch (final Exception e) {
        } // write PID
        f.deleteOnExit();
        FileChannel channel = null;
        FileLock lock = null;
        try {
            channel = new RandomAccessFile(f, "rw").getChannel();
            lock = channel.tryLock(); // lock yacy.running
        } catch (final Exception e) {
        }

        try {
            sb = new Switchboard(dataHome, appHome, "defaults/yacy.init".replace("/", File.separator), conf);
        } catch (final RuntimeException e) {
            ConcurrentLog.severe("STARTUP", "YaCy cannot start: " + e.getMessage(), e);
            System.exit(-1);
        }
        //sbSync.V(); // signal that the sb reference was set

        // switch the memory strategy
        MemoryControl.setStandardStrategy(sb.getConfigBool("memory.standardStrategy", true));

        // save information about available memory at startup time
        sb.setConfig("memoryFreeAfterStartup", startupMemFree);
        sb.setConfig("memoryTotalAfterStartup", startupMemTotal);

        // start gui if wanted
        if (gui)
            YaCyApp.start("localhost", sb.getLocalPort());

        // hardcoded, forced, temporary value-migration
        sb.setConfig("htTemplatePath", "htroot/env/templates");

        double oldVer;
        try {
            String tmpversion = sb.getConfig(Seed.VERSION, "");
            if (tmpversion.isEmpty()) { // before 1.83009737 only the svnRevision nr was in config (like 9737)
                tmpversion = yacyBuildProperties.getVersion();
                int oldRev = Integer.parseInt(sb.getConfig("svnRevision", "0"));
                if (oldRev > 1) {
                    oldVer = Double.parseDouble(tmpversion) + oldRev / 100000000.0;
                } else {
                    oldVer = Double.parseDouble(yacyBuildProperties.getLongVersion()); // failsafe (assume current version = no migration)
                }
            } else {
                oldVer = Double.parseDouble(tmpversion);
            }
        } catch (final NumberFormatException e) {
            oldVer = 0.0d;
        }
        final double newRev = Double.parseDouble(yacyBuildProperties.getLongVersion());
        sb.setConfig(Seed.VERSION, yacyBuildProperties.getLongVersion());
        sb.setConfig("applicationRoot", appHome.toString());
        sb.setConfig("dataRoot", dataHome.toString());

        // create some directories
        final File htRootPath = new File(appHome,
                sb.getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT));
        mkdirIfNeseccary(htRootPath);
        htDocsPath = sb.getDataPath(SwitchboardConstants.HTDOCS_PATH, SwitchboardConstants.HTDOCS_PATH_DEFAULT);
        mkdirIfNeseccary(htDocsPath);
        //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs"));

        // copy the donate iframe (better to copy this once here instead of doing this in an actual iframe in the search result)
        importDonationIFrame(sb, htDocsPath);

        // create default notifier picture
        File notifierFile = new File(htDocsPath, "notifier.gif");
        if (!notifierFile.exists())
            try {
                Files.copy(new File(htRootPath, "env/grafics/empty.gif"), notifierFile);
            } catch (final IOException e) {
            }

        final File htdocsReadme = new File(htDocsPath, "readme.txt");
        if (!(htdocsReadme.exists()))
            try {
                FileUtils.copy(("This is your root directory for individual Web Content\r\n" + "\r\n"
                        + "Please place your html files into the www subdirectory.\r\n"
                        + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy    or\r\n"
                        + "http://<your-ip>:<your-port>/www\r\n" + "\r\n"
                        + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n"
                        + "This directory shares it's content with the applications htroot path, so you\r\n"
                        + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n"
                        + "\r\n").getBytes(), htdocsReadme);
            } catch (final IOException e) {
                System.out.println("Error creating htdocs readme: " + e.getMessage());
            }

        shareDefaultPath = new File(htDocsPath, "share");
        mkdirIfNeseccary(shareDefaultPath);
        shareDumpDefaultPath = new File(shareDefaultPath, "dump");
        mkdirIfNeseccary(shareDumpDefaultPath);

        migration.migrate(sb, oldVer, newRev);

        // delete old release files
        final int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30);
        yacyRelease.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays);

        // set user-agent
        HTTPClient.setDefaultUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent);

        // start main threads
        final int port = sb.getLocalPort();
        try {
            // start http server
            YaCyHttpServer httpServer;
            httpServer = new Jetty9HttpServerImpl(port);
            httpServer.startupServer();
            sb.setHttpServer(httpServer);
            // TODO: this has no effect on Jetty (but needed to reflect configured value and limit is still used)
            ConnectionInfo.setServerMaxcount(sb.getConfigInt("connectionsMax", ConnectionInfo.getMaxcount()));

            ConcurrentLog.info("STARTUP", httpServer.getVersion());

            // open the browser window
            final boolean browserPopUpTrigger = sb
                    .getConfig(SwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true");
            if (browserPopUpTrigger)
                try {
                    final String browserPopUpPage = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_PAGE,
                            "ConfigBasic.html");
                    //boolean properPW = (sb.getConfig(SwitchboardConstants.ADMIN_ACCOUNT, "").isEmpty()) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0);
                    //if (!properPW) browserPopUpPage = "ConfigBasic.html";
                    /* YaCy main startup process must not hang because browser opening is long or fails. 
                     * Let's open try opening the browser in a separate thread */
                    new Thread("Browser opening") {
                        @Override
                        public void run() {
                            Browser.openBrowser(("http://localhost:" + port) + "/" + browserPopUpPage);
                        }
                    }.start();
                    // Browser.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage);
                } catch (final Throwable e) {
                    // cannot open browser. This may be normal in headless environments
                    //Log.logException(e);
                }

            // enable browser popup, http server is ready now
            sb.tray.setReady();

            //regenerate Locales from Translationlist, if needed
            final File locale_source = sb.getAppPath("locale.source", "locales");
            final String lang = sb.getConfig("locale.language", "");
            // on lang=browser all active translation should be checked (because any could be requested by client)
            List<String> langlist;
            if (lang.endsWith("browser"))
                langlist = Translator.activeTranslations(); // get all translated languages
            else {
                langlist = new ArrayList<String>();
                langlist.add(lang);
            }
            for (String tmplang : langlist) {
                if (!tmplang.equals("") && !tmplang.equals("default") && !tmplang.equals("browser")) { //locale is used
                    String currentRev = null;
                    BufferedReader br = null;
                    try {
                        br = new BufferedReader(new InputStreamReader(new FileInputStream(
                                new File(sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"),
                                        tmplang + "/version"))));
                        currentRev = br.readLine(); // may return null
                    } catch (final IOException e) {
                        //Error
                    } finally {
                        try {
                            br.close();
                        } catch (IOException ioe) {
                            ConcurrentLog.warn("STARTUP", "Could not close " + tmplang + " version file");
                        }
                    }

                    if (currentRev == null || !currentRev.equals(sb.getConfig(Seed.VERSION, ""))) {
                        try { //is this another version?!
                            final File sourceDir = new File(sb.getConfig(SwitchboardConstants.HTROOT_PATH,
                                    SwitchboardConstants.HTROOT_PATH_DEFAULT));
                            final File destDir = new File(
                                    sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"), tmplang);
                            if (new TranslatorXliff().translateFilesRecursive(sourceDir, destDir,
                                    new File(locale_source, tmplang + ".lng"), "html,template,inc", "locale")) { //translate it
                                //write the new Versionnumber
                                final BufferedWriter bw = new BufferedWriter(
                                        new PrintWriter(new FileWriter(new File(destDir, "version"))));
                                bw.write(sb.getConfig(Seed.VERSION, "Error getting Version"));
                                bw.close();
                            }
                        } catch (final IOException e) {
                        }
                    }
                }
            }
            // initialize number formatter with this locale
            if (!lang.equals("browser")) // "default" is handled by .setLocale()
                Formatter.setLocale(lang);

            // registering shutdown hook
            ConcurrentLog.config("STARTUP", "Registering Shutdown Hook");
            final Runtime run = Runtime.getRuntime();
            run.addShutdownHook(new shutdownHookThread(sb, shutdownSemaphore));

            // save information about available memory after all initializations
            //try {
            sb.setConfig("memoryFreeAfterInitBGC", MemoryControl.free());
            sb.setConfig("memoryTotalAfterInitBGC", MemoryControl.total());
            System.gc();
            sb.setConfig("memoryFreeAfterInitAGC", MemoryControl.free());
            sb.setConfig("memoryTotalAfterInitAGC", MemoryControl.total());
            //} catch (final ConcurrentModificationException e) {}

            // wait for server shutdown
            try {
                sb.waitForShutdown();
            } catch (final Exception e) {
                ConcurrentLog.severe("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(), e);
            }
            // shut down
            Array.terminate();
            ConcurrentLog.config("SHUTDOWN", "caught termination signal");
            httpServer.stop();

            ConcurrentLog.config("SHUTDOWN", "server has terminated");
            sb.close();
        } catch (final Exception e) {
            ConcurrentLog.severe("STARTUP", "Unexpected Error: " + e.getClass().getName(), e);
            //System.exit(1);
        }
        if (lock != null)
            lock.release();
        if (channel != null)
            channel.close();
    } catch (final Exception ee) {
        ConcurrentLog.severe("STARTUP", "FATAL ERROR: " + ee.getMessage(), ee);
    } finally {
    }

    if (tmpdir != null)
        FileUtils.deletedelete(new File(tmpdir)); // clean up temp dir (set at startup as subdir of system.propery "java.io.tmpdir")

    ConcurrentLog.config("SHUTDOWN", "goodbye. (this is the last line)");
    ConcurrentLog.shutdown();
    shutdownSemaphore.release(1000);
    try {
        System.exit(0);
    } catch (final Exception e) {
    } // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790)
}