Example usage for java.lang SecurityException getMessage

List of usage examples for java.lang SecurityException getMessage

Introduction

In this page you can find the example usage for java.lang SecurityException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.openremote.modeler.cache.LocalFileCache.java

/**
 * Compresses a set of files into a target zip archive. The file instances should be relative
 * paths used to structure the archive into directories. The relative paths will be resolved
 * to actual file paths in the current account's file cache.
 *
 * @param target    Target file path where the zip archive will be stored.
 * @param files     Set of <b>relative</b> file paths to include in the zip archive. The file
 *                  paths should be set to match the expected directory structure in the final
 *                  archive (therefore should not reflect the absolute file paths expected to
 *                  be included in the archive).
 *
 * @throws CacheOperationException//from  ww w  . ja va 2 s  .  c  om
 *            if any of the zip file operations fail
 *
 * @throws ConfigurationException
 *            if there are any security restrictions about reading the set of included files
 *            or writing the target zip archive file
 */
private void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException {
    ZipOutputStream zipOutput = null;

    try {
        zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)));

        for (File file : files) {
            BufferedInputStream fileInput = null;

            // translate the relative zip archive directory path to existing user cache absolute path...

            File cachePathName = new File(cacheFolder, file.getPath());

            try {
                if (!cachePathName.exists()) {
                    throw new CacheOperationException(
                            "Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it "
                                    + "has gone missing (cause unknown). This can indicate implementation or deployment "
                                    + "error. Aborting export operation as a safety precaution.",
                            cachePathName.getPath(), target.getAbsolutePath(),
                            currentUserAccount.getAccount().getOid());
                }

                fileInput = new BufferedInputStream(new FileInputStream(cachePathName));

                ZipEntry entry = new ZipEntry(file.getPath());

                entry.setSize(cachePathName.length());
                entry.setTime(cachePathName.lastModified());

                zipOutput.putNextEntry(entry);

                cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath());

                int count, total = 0;
                final int BUFFER_SIZE = 2048;
                byte[] data = new byte[BUFFER_SIZE];

                while ((count = fileInput.read(data, 0, BUFFER_SIZE)) != -1) {
                    zipOutput.write(data, 0, count);

                    total += count;
                }

                zipOutput.flush();

                // Sanity check...

                if (total != cachePathName.length()) {
                    throw new CacheOperationException(
                            "Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). "
                                    + "This could have occured either due implementation error or file I/O error. "
                                    + "Aborting archive operation to prevent a potentially corrupt export archive to "
                                    + "be created.",
                            total, cachePathName.length(), cachePathName.getPath(),
                            currentUserAccount.getAccount().getOid());
                }

                else {
                    cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total,
                            cachePathName.length(), file.getPath());
                }
            }

            catch (SecurityException e) {
                // we've messed up deployment... quite likely unrecoverable...

                throw new ConfigurationException(
                        "Security manager has denied r/w access when attempting to read file ''{0}'' and "
                                + "write it to archive ''{1}'' (Account : {2}) : {3}",
                        e, cachePathName.getPath(), target, currentUserAccount.getAccount().getOid(),
                        e.getMessage());
            }

            catch (IllegalArgumentException e) {
                // This may occur if we overrun some fixed size limits in ZIP format...

                throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e,
                        currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (FileNotFoundException e) {
                throw new CacheOperationException(
                        "Attempted to include file ''{0}'' in export archive but it has gone missing "
                                + "(Account : {1}). Possible implementation error in local file cache. Aborting  "
                                + "export operation as a precaution ({2})",
                        e, cachePathName.getPath(), currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (ZipException e) {
                throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e,
                        currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (IOException e) {
                throw new CacheOperationException(
                        "I/O error while creating export archive for account ID = {0}. "
                                + "Operation aborted ({1})",
                        e, currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            finally {
                if (zipOutput != null) {
                    try {
                        zipOutput.closeEntry();
                    }

                    catch (Throwable t) {
                        cacheLog.warn(
                                "Unable to close zip entry for file ''{0}'' in export archive ''{1}'' "
                                        + "(Account : {2}) : {3}.",
                                t, file.getPath(), target.getAbsolutePath(),
                                currentUserAccount.getAccount().getOid(), t.getMessage());
                    }
                }

                if (fileInput != null) {
                    try {
                        fileInput.close();
                    }

                    catch (Throwable t) {
                        cacheLog.warn(
                                "Failed to close input stream from file ''{0}'' being added "
                                        + "to export archive (Account : {1}) : {2}",
                                t, cachePathName.getPath(), currentUserAccount.getAccount().getOid(),
                                t.getMessage());
                    }
                }
            }
        }
    }

    catch (FileNotFoundException e) {
        throw new CacheOperationException(
                "Unable to create target export archive ''{0}'' for account {1) : {2}", e, target,
                currentUserAccount.getAccount().getOid(), e.getMessage());
    }

    finally {
        try {
            if (zipOutput != null) {
                zipOutput.close();
            }
        }

        catch (Throwable t) {
            cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target,
                    t.getMessage());
        }
    }
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

@SuppressWarnings("deprecation")
public static void signSAMLAssertion(SignableSAMLObject as, String keyAlias, char[] keyPassword)
        throws Exception {
    //String KEY_STORE_NAME="Unknown-1";
    //String KEY_STORE_PASS="spirit";
    //String PRIVATE_KEY_PASS="spirit";
    //String KEY_ALIAS="server1";

    ConfigurationManagerService cms = ConfigurationManagerService.getInstance();

    //String KEY_STORE_NAME =GetterUtil.getString(GnPropsUtil.get("portalb", "KEYSTORE_LOCATION"),"Unknown-1");

    String KEYSTORE_LOCATION = cms.getProperty("javax.net.ssl.keyStore");
    String KEY_STORE_PASS = cms.getProperty("javax.net.ssl.keyStorePassword"); //GetterUtil.getString(GnPropsUtil.get("portalb", "KEYSTORE_PASSWORD"),"spirit");
    String KEY_ALIAS = cms.getProperty("javax.net.ssl.key.alias"); //GetterUtil.getString(GnPropsUtil.get("portalb", "PRIVATEKEY_ALIAS"),"server1");
    String PRIVATE_KEY_PASS = cms.getProperty("javax.net.ssl.privateKeyPassword"); //GetterUtil.getString(GnPropsUtil.get("portalb", "PRIVATEKEY_PASSWORD"),"spirit");
    _log.debug("-------" + KEYSTORE_LOCATION);
    _log.debug("-------" + KEY_STORE_PASS);
    _log.debug("-------" + KEY_ALIAS);
    _log.debug("-------" + PRIVATE_KEY_PASS);

    KeyStoreManager keyManager = new DefaultKeyStoreManager();
    //KeyPair kp = null;
    X509Certificate cert = null;/*from  w ww . j a  v a2s.c  om*/
    //check if we must use the default key
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    if (keyAlias == null) {
        // kp = keyManager.getDefaultPrivateKey();
        cert = (X509Certificate) keyManager.getDefaultCertificate();

    } else {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        File file = new File(KEYSTORE_LOCATION);
        keyStore.load(new FileInputStream(file), KEY_STORE_PASS.toCharArray());

        privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS, PRIVATE_KEY_PASS.toCharArray());

        X509Certificate cert1 = (X509Certificate) keyStore.getCertificate(KEY_ALIAS);
        publicKey = cert1.getPublicKey();

        //kp = keyManager.getPrivateKey(keyAlias, keyPassword);
        cert = (X509Certificate) keyManager.getCertificate(keyAlias);
    }

    org.opensaml.xml.signature.Signature sig = (org.opensaml.xml.signature.Signature) Configuration
            .getBuilderFactory().getBuilder(org.opensaml.xml.signature.Signature.DEFAULT_ELEMENT_NAME)
            .buildObject(org.opensaml.xml.signature.Signature.DEFAULT_ELEMENT_NAME);

    Credential signingCredential = SecurityHelper.getSimpleCredential(cert, privateKey);

    //sig.setCanonicalizationAlgorithm(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    sig.setSigningCredential(signingCredential);
    // sig.setKeyInfo(SecurityHelper.getKeyInfoGenerator(signingCredential, null, null).generate(signingCredential));
    sig.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
    sig.setCanonicalizationAlgorithm("http://www.w3.org/2001/10/xml-exc-c14n#");

    SecurityConfiguration secConfig = Configuration.getGlobalSecurityConfiguration();
    try {
        SecurityHelper.prepareSignatureParams(sig, signingCredential, secConfig, null);
    } catch (SecurityException e) {
        throw new SMgrException(e.getMessage(), e);
    }

    as.setSignature(sig);
    try {
        Configuration.getMarshallerFactory().getMarshaller(as).marshall(as);
    } catch (MarshallingException e) {
        throw new SMgrException(e.getMessage(), e);
    }
    try {
        org.opensaml.xml.signature.Signer.signObject(sig);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.amalto.workbench.editors.DataModelMainPage.java

private void createCompDropTarget() {
    DropTarget dropTarget = new DropTarget(sash, DND.DROP_MOVE | DND.DROP_LINK);
    dropTarget.setTransfer(new TreeObjectTransfer[] { TreeObjectTransfer.getInstance() });
    dropTarget.addDropListener(new DropTargetAdapter() {

        @Override//from  w w  w .  j  ava 2  s  . c o m
        public void dragEnter(DropTargetEvent event) {
        }

        @Override
        public void dragLeave(DropTargetEvent event) {
        }

        @Override
        public void dragOver(DropTargetEvent event) {
            event.feedback |= DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
        }

        @Override
        public void drop(DropTargetEvent event) {
            List<String> nameList = new ArrayList<String>();
            if (dropTargetValidate(event, nameList)) {
                if (MessageDialog.openConfirm(sash.getShell(), Messages.ConfirmText,
                        Messages.DoIncludeImportSchema)) {
                    try {
                        HashMap<String, String> customTypesMap = ResourcesUtil
                                .getResourcesMapFromURI(uriPre + TreeObject.CUSTOM_TYPES_URI, xobject);
                        List<String> customTypeList = new ArrayList<String>();
                        for (String key : nameList) {
                            customTypeList.add(customTypesMap.get(key));
                        }
                        // doImportSchema();
                    } catch (SecurityException e) {
                        MessageDialog.openError(sash.getShell(), Messages._Error, e.getMessage());
                    }
                }
            }
        }
    });

}

From source file:org.quickserver.net.server.QuickServer.java

private boolean checkAccessConstraint(Socket socket) {
    try {//w w w .  j ava 2  s  .c o m
        if (getAccessConstraintConfig() != null) {
            getAccessConstraintConfig().checkAccept(socket);
        }
        return true;
    } catch (SecurityException se) {
        logger.warning("SecurityException occurred accepting connection : " + se.getMessage());
        return false;
    }
}

From source file:co.cask.cdap.gateway.handlers.AppFabricHttpHandler.java

/**
 * DO NOT DOCUMENT THIS API.//w  w w .j a  va 2s. com
 */
@POST
@Path("/unrecoverable/reset")
public void resetCDAP(HttpRequest request, HttpResponder responder) {

    try {
        if (!configuration.getBoolean(Constants.Dangerous.UNRECOVERABLE_RESET,
                Constants.Dangerous.DEFAULT_UNRECOVERABLE_RESET)) {
            responder.sendStatus(HttpResponseStatus.FORBIDDEN);
            return;
        }
        String account = getAuthenticatedAccountId(request);
        final Id.Account accountId = Id.Account.from(account);

        // Check if any program is still running
        boolean appRunning = checkAnyRunning(new Predicate<Id.Program>() {
            @Override
            public boolean apply(Id.Program programId) {
                return programId.getAccountId().equals(accountId.getId());
            }
        }, ProgramType.values());

        if (appRunning) {
            throw new Exception("App Still Running");
        }

        LOG.info("Deleting all data for account '" + account + "'.");

        // NOTE: deleting new datasets stuff first because old datasets system deletes all blindly by prefix
        //       which may damage metadata
        for (DatasetSpecification spec : dsFramework.getInstances()) {
            dsFramework.deleteInstance(spec.getName());
        }
        dsFramework.deleteAllModules();

        deleteMetrics(account, null);
        // delete all meta data
        store.removeAll(accountId);
        // todo: delete only for specified account
        // delete queues and streams data
        queueAdmin.dropAll();
        streamAdmin.dropAll();

        LOG.info("All data for account '" + account + "' deleted.");
        responder.sendStatus(HttpResponseStatus.OK);
    } catch (SecurityException e) {
        responder.sendStatus(HttpResponseStatus.UNAUTHORIZED);
    } catch (Throwable e) {
        LOG.warn(e.getMessage(), e);
        responder.sendString(HttpResponseStatus.BAD_REQUEST,
                String.format(UserMessages.getMessage(UserErrors.RESET_FAIL), e.getMessage()));
    }
}

From source file:coral.service.ExpTemplateUtil.java

public String evalScriptR(String scriptname, ExpData data, ErrorFlag error, ExpServiceImpl service) {

    // Map<String, String> newOrChangedMap = new LinkedHashMap<String, sss
    // String>();

    // ScriptEngine jsEngine = m.getEngineByName("js");
    // ScriptContext context = new SimpleScriptContext();

    Context context = Context.enter();

    Scriptable scope = context.initStandardObjects();

    // context.setAttribute("data", data, ScriptContext.ENGINE_SCOPE);
    // context.setAttribute("error", error, ScriptContext.ENGINE_SCOPE);

    for (Map.Entry<String, Object> e : data.entrySet()) {
        if (e != null && e.getKey() != null && !e.getKey().toString().equals("")) {
            Object value = data.get(e.getKey());

            if (logger.isDebugEnabled()) {
                logger.debug("entered value: " + e.getKey() + " == " + value + " \t\t | " + value.getClass());
            }//ww w  . ja v  a 2 s . c o m
            scope.put(e.getKey(), scope, value);
        }
    }

    if (service != null) {
        scope.put("agents", scope, service.getAllData().values().toArray());
    }

    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(basepath + scriptname)));

        Object o = context.evaluateReader(scope, br, "coral", 1, null);
        if (logger.isDebugEnabled())
            logger.debug("JS OBJECT: " + o);

        for (Object keyOb : scope.getIds()) {
            String key = keyOb.toString();
            Object value = scope.get(key.toString(), scope);

            if (logger.isDebugEnabled())
                logger.debug("KEYS: " + key + " value: " + value);

            // TODO dirty way to unwrap NativeJavaObjects
            if (!(value instanceof Number) && !(value instanceof String)) {
                try {
                    Method m = value.getClass().getMethod("unwrap");
                    value = m.invoke(value);
                } catch (SecurityException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (NoSuchMethodException e1) {
                    // TODO Auto-generated catch block
                    // e1.printStackTrace();
                } catch (IllegalArgumentException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IllegalAccessException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (InvocationTargetException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

            if (value instanceof Number || value instanceof String) {
                if (!data.containsKey(key) || data.get(key) == null
                        || !data.get(key).toString().equals(value.toString())) {
                    data.put(key, value);
                    // newOrChangedMap.put(key, value.toString());
                    if (logger.isDebugEnabled()) {
                        logger.debug("SCRIPTED VALUE: " + key + " == " + value.toString() + " \t\t | "
                                + value.getClass());
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("retained: " + key + " == " + value.toString());
                    }
                }
            } else if (value instanceof List<?>) {
                Object[] array = ((List<?>) value).toArray();

                if (!data.containsKey(key) || data.get(key) == null
                        || !data.get(key).toString().equals(Arrays.asList(array).toString())) {
                    data.put(key, array);
                    // newOrChangedMap.put(key, array);
                    if (logger.isDebugEnabled()) {
                        logger.debug("SCRIPTED ARRAY: " + key + " == " + value.toString() + " \t\t | "
                                + value.getClass());
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("ARRAY retained: " + key + " == " + value.toString());
                    }
                }

                logger.debug("ARRAY: " + key + " == " + value.toString() + " \t\t | " + value.getClass());
            } else {
                logger.debug("NONVALUE: " + key + " == " + value.toString() + " \t\t | " + value.getClass());
            }
            // context.removeAttribute(key,
            // ScriptContext.ENGINE_SCOPE);

        }

    } catch (FileNotFoundException e1) {
        logger.error("File Not Found Exception ", e1);
        return errorPage(scriptname + " " + e1.getMessage());
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return null;
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

/**
 * Deletes the template's file. Deletes the templates folder if no other templates files exist in the folder.
 * Deletes the {@link CloudifyConstants#ADDITIONAL_TEMPLATES_FOLDER_NAME} folder if empty.
 *
 * @param templateName//w  w w.  java  2s  .  c o m
 * @throws RestErrorException
 */
private void deleteTemplateFile(final String templateName) throws RestErrorException {
    final File templateFile = getTemplateFile(templateName);
    if (templateFile == null) {
        throw new RestErrorException("failed_to_remove_template_file", templateName,
                "template file doesn't exist");
    }
    // delete the file from the directory.
    final String templatesPath = templateFile.getAbsolutePath();
    logger.log(Level.FINE, "[deleteTemplateFile] - removing template file " + templatesPath);
    boolean deleted = false;
    try {
        deleted = templateFile.delete();
    } catch (final SecurityException e) {
        logger.log(Level.WARNING, "[deleteTemplateFile] - Failed to deleted template file " + templatesPath
                + ", Error: " + e.getMessage(), e);
        throw new RestErrorException("failed_to_remove_template_file", templatesPath, e.getMessage());
    }
    if (!deleted) {
        throw new RestErrorException("failed_to_remove_template_file", templatesPath,
                "template file was not deleted.");
    }
    logger.log(Level.FINE,
            "[deleteTemplateFile] - Successfully deleted template file [" + templatesPath + "].");
    final File templateFolder = templateFile.getParentFile();
    final File[] templatesFiles = DSLReader.findDefaultDSLFiles(DSLUtils.TEMPLATE_DSL_FILE_NAME_SUFFIX,
            templateFolder);
    if (templatesFiles == null || templatesFiles.length == 0) {
        try {
            logger.log(Level.FINE, "[deleteTemplateFile] - templates folder is empty, deleting the folder ["
                    + templatesPath + "].");
            FileUtils.deleteDirectory(templateFolder);
        } catch (final IOException e) {
            logger.log(Level.WARNING,
                    "[deleteTemplateFile] - Failed to delete templates folder" + templateFolder, e);
        }
    } else {
        // delete properties and overrides files if exist.
        ComputeTemplatesReader.removeTemplateFiles(templateFolder, templateName);
    }
    final File templatesFolder = getTemplatesFolder();
    if (templatesFolder.list().length == 0) {
        templateFolder.delete();
    }
}

From source file:com.cloud.hypervisor.xenserver.resource.CitrixResourceBase.java

public boolean createVmdataFiles(final String vmName, final List<String[]> vmDataList,
        final String configDriveLabel) {

    // add vm iso to the isolibrary
    final String isoPath = "/tmp/" + vmName + "/configDrive/";
    final String configDriveName = "cloudstack/";

    //create folder for the VM
    //Remove the folder before creating it.

    try {/*w w w . ja  v a  2 s .  c  o m*/
        deleteLocalFolder("/tmp/" + isoPath);
    } catch (final IOException e) {
        s_logger.debug("Failed to delete the exiting config drive for vm " + vmName + " " + e.getMessage());
    } catch (final Exception e) {
        s_logger.debug("Failed to delete the exiting config drive for vm " + vmName + " " + e.getMessage());
    }

    if (vmDataList != null) {
        for (final String[] item : vmDataList) {
            final String dataType = item[0];
            final String fileName = item[1];
            final String content = item[2];

            // create file with content in folder

            if (dataType != null && !dataType.isEmpty()) {
                //create folder
                final String folder = isoPath + configDriveName + dataType;
                if (folder != null && !folder.isEmpty()) {
                    final File dir = new File(folder);
                    final boolean result = true;

                    try {
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                    } catch (final SecurityException ex) {
                        s_logger.debug("Failed to create dir " + ex.getMessage());
                        return false;
                    }

                    if (result && content != null && !content.isEmpty()) {
                        File file = new File(folder + "/" + fileName + ".txt");
                        try (OutputStreamWriter fw = new OutputStreamWriter(
                                new FileOutputStream(file.getAbsoluteFile()), "UTF-8");
                                BufferedWriter bw = new BufferedWriter(fw);) {
                            bw.write(content);
                            s_logger.debug("created file: " + file + " in folder:" + folder);
                        } catch (final IOException ex) {
                            s_logger.debug("Failed to create file " + ex.getMessage());
                            return false;
                        }
                    }
                }
            }
        }
        s_logger.debug("Created the vm data in " + isoPath);
    }

    String s = null;
    try {

        final String cmd = "mkisofs -iso-level 3 -V " + configDriveLabel + " -o " + isoPath + vmName + ".iso "
                + isoPath;
        final Process p = Runtime.getRuntime().exec(cmd);

        final BufferedReader stdInput = new BufferedReader(
                new InputStreamReader(p.getInputStream(), Charset.defaultCharset()));

        final BufferedReader stdError = new BufferedReader(
                new InputStreamReader(p.getErrorStream(), Charset.defaultCharset()));

        // read the output from the command
        while ((s = stdInput.readLine()) != null) {
            s_logger.debug(s);
        }

        // read any errors from the attempted command
        while ((s = stdError.readLine()) != null) {
            s_logger.debug(s);
        }
        s_logger.debug(" Created config drive ISO using the command " + cmd + " in the host " + _host.getIp());
    } catch (final IOException e) {
        s_logger.debug(e.getMessage());
        return false;
    }

    return true;
}

From source file:com.ecyrd.jspwiki.WikiEngine.java

/**
 *  Does all the real initialization./*from w  w  w. j  a v a  2  s .c om*/
 */
private void initialize(Properties props) throws WikiException {
    m_startTime = new Date();
    m_properties = props;

    //
    //  Initialized log4j.  However, make sure that
    //  we don't initialize it multiple times.  Also, if
    //  all of the log4j statements have been removed from
    //  the property file, we do not do any property setting
    //  either.q
    //
    if (!c_configured) {
        if (props.getProperty("log4j.rootCategory") != null) {
            PropertyConfigurator.configure(props);
        }
        c_configured = true;
    }

    log.info("*******************************************");
    log.info(Release.APPNAME + " " + Release.getVersionString() + " starting. Whee!");

    fireEvent(WikiEngineEvent.INITIALIZING); // begin initialization

    log.debug("Java version: " + System.getProperty("java.runtime.version"));
    log.debug("Java vendor: " + System.getProperty("java.vm.vendor"));
    log.debug("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
            + System.getProperty("os.arch"));
    log.debug("Default server locale: " + Locale.getDefault());
    log.debug("Default server timezone: " + TimeZone.getDefault().getDisplayName(true, TimeZone.LONG));

    if (m_servletContext != null) {
        log.info("Servlet container: " + m_servletContext.getServerInfo());
        if (m_servletContext.getMajorVersion() < 2
                || (m_servletContext.getMajorVersion() == 2 && m_servletContext.getMinorVersion() < 4)) {
            throw new InternalWikiException(
                    "I require a container which supports at least version 2.4 of Servlet specification");
        }
    }

    log.debug("Configuring WikiEngine...");

    //  Initializes the CommandResolver
    m_commandResolver = new CommandResolver(this, props);

    //
    //  Create and find the default working directory.
    //
    m_workDir = TextUtil.getStringProperty(props, PROP_WORKDIR, null);

    if (m_workDir == null) {
        m_workDir = System.getProperty("java.io.tmpdir", ".");
        m_workDir += File.separator + Release.APPNAME + "-" + m_appid;
    }

    try {
        File f = new File(m_workDir);
        f.mkdirs();

        //
        //  A bunch of sanity checks
        //
        if (!f.exists())
            throw new WikiException("Work directory does not exist: " + m_workDir);
        if (!f.canRead())
            throw new WikiException("No permission to read work directory: " + m_workDir);
        if (!f.canWrite())
            throw new WikiException("No permission to write to work directory: " + m_workDir);
        if (!f.isDirectory())
            throw new WikiException("jspwiki.workDir does not point to a directory: " + m_workDir);
    } catch (SecurityException e) {
        log.fatal("Unable to find or create the working directory: " + m_workDir, e);
        throw new IllegalArgumentException("Unable to find or create the working dir: " + m_workDir);
    }

    log.info("JSPWiki working directory is '" + m_workDir + "'");

    m_saveUserInfo = TextUtil.getBooleanProperty(props, PROP_STOREUSERNAME, m_saveUserInfo);

    m_useUTF8 = "UTF-8".equals(TextUtil.getStringProperty(props, PROP_ENCODING, "ISO-8859-1"));
    m_baseURL = TextUtil.getStringProperty(props, PROP_BASEURL, "");
    if (!m_baseURL.endsWith("/")) {
        m_baseURL = m_baseURL + "/";
    }

    m_beautifyTitle = TextUtil.getBooleanProperty(props, PROP_BEAUTIFYTITLE, m_beautifyTitle);

    m_templateDir = TextUtil.getStringProperty(props, PROP_TEMPLATEDIR, "default");
    m_frontPage = TextUtil.getStringProperty(props, PROP_FRONTPAGE, "Main");

    // Initialize the page name comparator now as it may be used while
    // initializing other modules
    initPageSorter(props);

    //
    //  Initialize the important modules.  Any exception thrown by the
    //  managers means that we will not start up.
    //

    // FIXME: This part of the code is getting unwieldy.  We must think
    //        of a better way to do the startup-sequence.
    try {
        Class urlclass = ClassUtil.findClass("com.ecyrd.jspwiki.url",
                TextUtil.getStringProperty(props, PROP_URLCONSTRUCTOR, "DefaultURLConstructor"));
        m_urlConstructor = (URLConstructor) urlclass.newInstance();
        m_urlConstructor.initialize(this, props);

        m_pageManager = (PageManager) ClassUtil.getMappedObject(PageManager.class.getName(), this, props);
        m_pluginManager = (PluginManager) ClassUtil.getMappedObject(PluginManager.class.getName(), this, props);
        m_differenceManager = (DifferenceManager) ClassUtil.getMappedObject(DifferenceManager.class.getName(),
                this, props);
        m_attachmentManager = (AttachmentManager) ClassUtil.getMappedObject(AttachmentManager.class.getName(),
                this, props);
        m_variableManager = (VariableManager) ClassUtil.getMappedObject(VariableManager.class.getName(), props);
        // m_filterManager     = (FilterManager)ClassUtil.getMappedObject(FilterManager.class.getName(), this, props );
        m_renderingManager = (RenderingManager) ClassUtil.getMappedObject(RenderingManager.class.getName());

        m_searchManager = (SearchManager) ClassUtil.getMappedObject(SearchManager.class.getName(), this, props);

        m_authenticationManager = (AuthenticationManager) ClassUtil
                .getMappedObject(AuthenticationManager.class.getName());
        m_authorizationManager = (AuthorizationManager) ClassUtil
                .getMappedObject(AuthorizationManager.class.getName());
        m_userManager = (UserManager) ClassUtil.getMappedObject(UserManager.class.getName());
        m_groupManager = (GroupManager) ClassUtil.getMappedObject(GroupManager.class.getName());

        m_editorManager = (EditorManager) ClassUtil.getMappedObject(EditorManager.class.getName(), this);
        m_editorManager.initialize(props);

        m_progressManager = new ProgressManager();

        // Initialize the authentication, authorization, user and acl managers

        m_authenticationManager.initialize(this, props);
        m_authorizationManager.initialize(this, props);
        m_userManager.initialize(this, props);
        m_groupManager.initialize(this, props);
        m_aclManager = getAclManager();

        // Start the Workflow manager
        m_workflowMgr = (WorkflowManager) ClassUtil.getMappedObject(WorkflowManager.class.getName());
        m_workflowMgr.initialize(this, props);

        m_internationalizationManager = (InternationalizationManager) ClassUtil
                .getMappedObject(InternationalizationManager.class.getName(), this);

        m_templateManager = (TemplateManager) ClassUtil.getMappedObject(TemplateManager.class.getName(), this,
                props);

        m_adminBeanManager = (AdminBeanManager) ClassUtil.getMappedObject(AdminBeanManager.class.getName(),
                this);

        // Since we want to use a page filters initilize() method
        // as a engine startup listener where we can initialize global event listeners,
        // it must be called lastly, so that all object references in the engine
        // are availabe to the initialize() method
        m_filterManager = (FilterManager) ClassUtil.getMappedObject(FilterManager.class.getName(), this, props);

        // RenderingManager depends on FilterManager events.

        m_renderingManager.initialize(this, props);

        //
        //  ReferenceManager has the side effect of loading all
        //  pages.  Therefore after this point, all page attributes
        //  are available.
        //
        //  initReferenceManager is indirectly using m_filterManager, therefore
        //  it has to be called after it was initialized.
        //
        initReferenceManager();

        //
        //  Hook the different manager routines into the system.
        //
        getFilterManager().addPageFilter(m_referenceManager, -1001);
        getFilterManager().addPageFilter(m_searchManager, -1002);
    }

    catch (RuntimeException e) {
        // RuntimeExceptions may occur here, even if they shouldn't.
        log.fatal("Failed to start managers.", e);
        e.printStackTrace();
        throw new WikiException("Failed to start managers: " + e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        log.fatal("JSPWiki could not start, URLConstructor was not found: ", e);
        e.printStackTrace();
        throw new WikiException(e.getMessage(), e);
    } catch (InstantiationException e) {
        log.fatal("JSPWiki could not start, URLConstructor could not be instantiated: ", e);
        e.printStackTrace();
        throw new WikiException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.fatal("JSPWiki could not start, URLConstructor cannot be accessed: ", e);
        e.printStackTrace();
        throw new WikiException(e.getMessage(), e);
    } catch (Exception e) {
        // Final catch-all for everything
        log.fatal("JSPWiki could not start, due to an unknown exception when starting.", e);
        e.printStackTrace();
        throw new WikiException("Failed to start; please check log files for better information.", e);
    }

    //
    //  Initialize the good-to-have-but-not-fatal modules.
    //
    try {
        if (TextUtil.getBooleanProperty(props, RSSGenerator.PROP_GENERATE_RSS, false)) {
            m_rssGenerator = (RSSGenerator) ClassUtil.getMappedObject(RSSGenerator.class.getName(), this,
                    props);
        }

        m_pageRenamer = (PageRenamer) ClassUtil.getMappedObject(PageRenamer.class.getName(), this, props);
    } catch (Exception e) {
        log.error(
                "Unable to start RSS generator - JSPWiki will still work, " + "but there will be no RSS feed.",
                e);
    }

    // Start the RSS generator & generator thread
    if (m_rssGenerator != null) {
        m_rssFile = TextUtil.getStringProperty(props, RSSGenerator.PROP_RSSFILE, "rss.rdf");
        File rssFile = null;
        if (m_rssFile.startsWith(File.separator)) {
            // honor absolute pathnames:
            rssFile = new File(m_rssFile);
        } else {
            // relative path names are anchored from the webapp root path:
            rssFile = new File(getRootPath(), m_rssFile);
        }
        int rssInterval = TextUtil.getIntegerProperty(props, RSSGenerator.PROP_INTERVAL, 3600);
        RSSThread rssThread = new RSSThread(this, rssFile, rssInterval);
        rssThread.start();
    }

    fireEvent(WikiEngineEvent.INITIALIZED); // initialization complete

    log.info("WikiEngine configured.");
    m_isConfigured = true;
}

From source file:org.apache.wiki.WikiEngine.java

/**
 *  Does all the real initialization./*from w  w w . j av  a 2  s.c om*/
 */
private void initialize(Properties props) throws WikiException {
    m_startTime = new Date();
    m_properties = props;

    //
    //  Initialized log4j.  However, make sure that
    //  we don't initialize it multiple times.  Also, if
    //  all of the log4j statements have been removed from
    //  the property file, we do not do any property setting
    //  either.q
    //
    if (!c_configured) {
        if (props.getProperty("log4j.rootCategory") != null) {
            PropertyConfigurator.configure(props);
        }
        c_configured = true;
    }

    log.info("*******************************************");
    log.info(Release.APPNAME + " " + Release.getVersionString() + " starting. Whee!");

    fireEvent(WikiEngineEvent.INITIALIZING); // begin initialization

    log.debug("Java version: " + System.getProperty("java.runtime.version"));
    log.debug("Java vendor: " + System.getProperty("java.vm.vendor"));
    log.debug("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
            + System.getProperty("os.arch"));
    log.debug("Default server locale: " + Locale.getDefault());
    log.debug("Default server timezone: " + TimeZone.getDefault().getDisplayName(true, TimeZone.LONG));

    if (m_servletContext != null) {
        log.info("Servlet container: " + m_servletContext.getServerInfo());
        if (m_servletContext.getMajorVersion() < 2
                || (m_servletContext.getMajorVersion() == 2 && m_servletContext.getMinorVersion() < 4)) {
            throw new InternalWikiException(
                    "I require a container which supports at least version 2.4 of Servlet specification");
        }
    }

    log.debug("Configuring WikiEngine...");

    //  Initializes the CommandResolver
    m_commandResolver = new CommandResolver(this, props);

    //
    //  Create and find the default working directory.
    //
    m_workDir = TextUtil.getStringProperty(props, PROP_WORKDIR, null);

    if (m_workDir == null) {
        m_workDir = System.getProperty("java.io.tmpdir", ".");
        m_workDir += File.separator + Release.APPNAME + "-" + m_appid;
    }

    try {
        File f = new File(m_workDir);
        f.mkdirs();

        //
        //  A bunch of sanity checks
        //
        if (!f.exists())
            throw new WikiException("Work directory does not exist: " + m_workDir);
        if (!f.canRead())
            throw new WikiException("No permission to read work directory: " + m_workDir);
        if (!f.canWrite())
            throw new WikiException("No permission to write to work directory: " + m_workDir);
        if (!f.isDirectory())
            throw new WikiException("jspwiki.workDir does not point to a directory: " + m_workDir);
    } catch (SecurityException e) {
        log.fatal("Unable to find or create the working directory: " + m_workDir, e);
        throw new IllegalArgumentException("Unable to find or create the working dir: " + m_workDir);
    }

    log.info("JSPWiki working directory is '" + m_workDir + "'");

    m_saveUserInfo = TextUtil.getBooleanProperty(props, PROP_STOREUSERNAME, m_saveUserInfo);

    m_useUTF8 = "UTF-8".equals(TextUtil.getStringProperty(props, PROP_ENCODING, "ISO-8859-1"));
    m_baseURL = TextUtil.getStringProperty(props, PROP_BASEURL, "");
    if (!m_baseURL.endsWith("/")) {
        m_baseURL = m_baseURL + "/";
    }

    m_beautifyTitle = TextUtil.getBooleanProperty(props, PROP_BEAUTIFYTITLE, m_beautifyTitle);

    m_templateDir = TextUtil.getStringProperty(props, PROP_TEMPLATEDIR, "default");
    m_frontPage = TextUtil.getStringProperty(props, PROP_FRONTPAGE, "Main");

    // Initialize the page name comparator now as it may be used while
    // initializing other modules
    initPageSorter(props);

    //
    //  Initialize the important modules.  Any exception thrown by the
    //  managers means that we will not start up.
    //

    // FIXME: This part of the code is getting unwieldy.  We must think
    //        of a better way to do the startup-sequence.
    try {
        Class urlclass = ClassUtil.findClass("org.apache.wiki.url",
                TextUtil.getStringProperty(props, PROP_URLCONSTRUCTOR, "DefaultURLConstructor"));
        m_urlConstructor = (URLConstructor) urlclass.newInstance();
        m_urlConstructor.initialize(this, props);

        m_pageManager = (PageManager) ClassUtil.getMappedObject(PageManager.class.getName(), this, props);
        m_pluginManager = (PluginManager) ClassUtil.getMappedObject(PluginManager.class.getName(), this, props);
        m_differenceManager = (DifferenceManager) ClassUtil.getMappedObject(DifferenceManager.class.getName(),
                this, props);
        m_attachmentManager = (AttachmentManager) ClassUtil.getMappedObject(AttachmentManager.class.getName(),
                this, props);
        m_variableManager = (VariableManager) ClassUtil.getMappedObject(VariableManager.class.getName(), props);
        // m_filterManager     = (FilterManager)ClassUtil.getMappedObject(FilterManager.class.getName(), this, props );
        m_renderingManager = (RenderingManager) ClassUtil.getMappedObject(RenderingManager.class.getName());

        m_searchManager = (SearchManager) ClassUtil.getMappedObject(SearchManager.class.getName(), this, props);

        m_authenticationManager = (AuthenticationManager) ClassUtil
                .getMappedObject(AuthenticationManager.class.getName());
        m_authorizationManager = (AuthorizationManager) ClassUtil
                .getMappedObject(AuthorizationManager.class.getName());
        m_userManager = (UserManager) ClassUtil.getMappedObject(UserManager.class.getName());
        m_groupManager = (GroupManager) ClassUtil.getMappedObject(GroupManager.class.getName());

        m_editorManager = (EditorManager) ClassUtil.getMappedObject(EditorManager.class.getName(), this);
        m_editorManager.initialize(props);

        m_progressManager = new ProgressManager();

        // Initialize the authentication, authorization, user and acl managers

        m_authenticationManager.initialize(this, props);
        m_authorizationManager.initialize(this, props);
        m_userManager.initialize(this, props);
        m_groupManager.initialize(this, props);
        m_aclManager = getAclManager();

        // Start the Workflow manager
        m_workflowMgr = (WorkflowManager) ClassUtil.getMappedObject(WorkflowManager.class.getName());
        m_workflowMgr.initialize(this, props);

        m_internationalizationManager = (InternationalizationManager) ClassUtil
                .getMappedObject(InternationalizationManager.class.getName(), this);

        m_templateManager = (TemplateManager) ClassUtil.getMappedObject(TemplateManager.class.getName(), this,
                props);

        m_adminBeanManager = (AdminBeanManager) ClassUtil.getMappedObject(AdminBeanManager.class.getName(),
                this);

        // Since we want to use a page filters initilize() method
        // as a engine startup listener where we can initialize global event listeners,
        // it must be called lastly, so that all object references in the engine
        // are availabe to the initialize() method
        m_filterManager = (FilterManager) ClassUtil.getMappedObject(FilterManager.class.getName(), this, props);

        // RenderingManager depends on FilterManager events.

        m_renderingManager.initialize(this, props);

        //
        //  ReferenceManager has the side effect of loading all
        //  pages.  Therefore after this point, all page attributes
        //  are available.
        //
        //  initReferenceManager is indirectly using m_filterManager, therefore
        //  it has to be called after it was initialized.
        //
        initReferenceManager();

        //
        //  Hook the different manager routines into the system.
        //
        m_filterManager.addPageFilter(m_referenceManager, -1001);
        m_filterManager.addPageFilter(m_searchManager, -1002);
    }

    catch (RuntimeException e) {
        // RuntimeExceptions may occur here, even if they shouldn't.
        log.fatal("Failed to start managers.", e);
        e.printStackTrace();
        throw new WikiException("Failed to start managers: " + e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        log.fatal("JSPWiki could not start, URLConstructor was not found: ", e);
        e.printStackTrace();
        throw new WikiException(e.getMessage(), e);
    } catch (InstantiationException e) {
        log.fatal("JSPWiki could not start, URLConstructor could not be instantiated: ", e);
        e.printStackTrace();
        throw new WikiException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.fatal("JSPWiki could not start, URLConstructor cannot be accessed: ", e);
        e.printStackTrace();
        throw new WikiException(e.getMessage(), e);
    } catch (Exception e) {
        // Final catch-all for everything
        log.fatal("JSPWiki could not start, due to an unknown exception when starting.", e);
        e.printStackTrace();
        throw new WikiException("Failed to start; please check log files for better information.", e);
    }

    //
    //  Initialize the good-to-have-but-not-fatal modules.
    //
    try {
        if (TextUtil.getBooleanProperty(props, RSSGenerator.PROP_GENERATE_RSS, false)) {
            m_rssGenerator = (RSSGenerator) ClassUtil.getMappedObject(RSSGenerator.class.getName(), this,
                    props);
        }

        m_pageRenamer = (PageRenamer) ClassUtil.getMappedObject(PageRenamer.class.getName(), this, props);
    } catch (Exception e) {
        log.error(
                "Unable to start RSS generator - JSPWiki will still work, " + "but there will be no RSS feed.",
                e);
    }

    // Start the RSS generator & generator thread
    if (m_rssGenerator != null) {
        m_rssFile = TextUtil.getStringProperty(props, RSSGenerator.PROP_RSSFILE, "rss.rdf");
        File rssFile = null;
        if (m_rssFile.startsWith(File.separator)) {
            // honor absolute pathnames:
            rssFile = new File(m_rssFile);
        } else {
            // relative path names are anchored from the webapp root path:
            rssFile = new File(getRootPath(), m_rssFile);
        }
        int rssInterval = TextUtil.getIntegerProperty(props, RSSGenerator.PROP_INTERVAL, 3600);
        RSSThread rssThread = new RSSThread(this, rssFile, rssInterval);
        rssThread.start();
    }

    fireEvent(WikiEngineEvent.INITIALIZED); // initialization complete

    log.info("WikiEngine configured.");
    m_isConfigured = true;
}