Example usage for javax.servlet ServletContext getInitParameter

List of usage examples for javax.servlet ServletContext getInitParameter

Introduction

In this page you can find the example usage for javax.servlet ServletContext getInitParameter.

Prototype

public String getInitParameter(String name);

Source Link

Document

Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.

Usage

From source file:org.red5.server.tomcat.TomcatLoader.java

/**
 * Initialization.//from  w  ww . j av a2  s. com
 */
public void init() {
    log.info("Loading tomcat context");

    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);

    // create one embedded (server) and use it everywhere
    embedded = new Embedded();
    embedded.createLoader(originalClassLoader);
    embedded.setCatalinaBase(serverRoot);
    embedded.setCatalinaHome(serverRoot);
    embedded.setName(serviceEngineName);
    log.trace("Classloader for embedded: {} TCL: {}", Embedded.class.getClassLoader(), originalClassLoader);

    engine = embedded.createEngine();
    engine.setDefaultHost(host.getName());
    engine.setName(serviceEngineName);

    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);

    // scan for additional webapp contexts

    // Root applications directory
    File appDirBase = new File(webappFolder);
    // Subdirs of root apps dir
    File[] dirs = appDirBase.listFiles(new DirectoryFilter());
    // Search for additional context files
    for (File dir : dirs) {
        String dirName = '/' + dir.getName();
        // check to see if the directory is already mapped
        if (null == host.findChild(dirName)) {
            String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName);
            log.debug("Webapp context directory (full path): {}", webappContextDir);
            Context ctx = null;
            if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
                log.trace("Adding ROOT context");
                ctx = addContext("/", webappContextDir);
            } else {
                log.trace("Adding context from directory scan: {}", dirName);
                ctx = addContext(dirName, webappContextDir);
            }
            log.trace("Context: {}", ctx);

            //see if the application requests php support
            String enablePhp = ctx.findParameter("enable-php");
            //if its null try to read directly
            if (enablePhp == null) {
                File webxml = new File(webappContextDir + "/WEB-INF/", "web.xml");
                if (webxml.exists() && webxml.canRead()) {
                    try {
                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                        Document doc = docBuilder.parse(webxml);
                        // normalize text representation
                        doc.getDocumentElement().normalize();
                        log.trace("Root element of the doc is {}", doc.getDocumentElement().getNodeName());
                        NodeList listOfElements = doc.getElementsByTagName("context-param");
                        int totalElements = listOfElements.getLength();
                        log.trace("Total no of elements: {}", totalElements);
                        for (int s = 0; s < totalElements; s++) {
                            Node fstNode = listOfElements.item(s);
                            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                                Element fstElmnt = (Element) fstNode;
                                NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("param-name");
                                Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                                NodeList fstNm = fstNmElmnt.getChildNodes();
                                String pName = (fstNm.item(0)).getNodeValue();
                                log.trace("Param name: {}", pName);
                                if ("enable-php".equals(pName)) {
                                    NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("param-value");
                                    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                                    NodeList lstNm = lstNmElmnt.getChildNodes();
                                    String pValue = (lstNm.item(0)).getNodeValue();
                                    log.trace("Param value: {}", pValue);
                                    enablePhp = pValue;
                                    //
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.warn("Error reading web.xml", e);
                    }
                }
                webxml = null;
            }
            log.debug("Enable php: {}", enablePhp);
            if ("true".equals(enablePhp)) {
                log.info("Adding PHP (Quercus) servlet for context: {}", ctx.getName());
                // add servlet wrapper
                StandardWrapper wrapper = (StandardWrapper) ctx.createWrapper();
                wrapper.setServletName("QuercusServlet");
                wrapper.setServletClass("com.caucho.quercus.servlet.QuercusServlet");
                log.debug("Wrapper: {}", wrapper);
                ctx.addChild(wrapper);
                // add servlet mappings
                ctx.addServletMapping("*.php", "QuercusServlet");
            }

            webappContextDir = null;
        }
    }
    appDirBase = null;
    dirs = null;

    // Dump context list
    if (log.isDebugEnabled()) {
        for (Container cont : host.findChildren()) {
            log.debug("Context child name: {}", cont.getName());
        }
    }

    // Set a realm
    if (realm == null) {
        realm = new MemoryRealm();
    }
    embedded.setRealm(realm);

    // use Tomcat jndi or not
    if (System.getProperty("catalina.useNaming") != null) {
        embedded.setUseNaming(Boolean.valueOf(System.getProperty("catalina.useNaming")));
    }

    // add the valves to the host
    for (Valve valve : valves) {
        log.debug("Adding host valve: {}", valve);
        ((StandardHost) host).addValve(valve);
    }

    // baseHost = embedded.createHost(hostName, appRoot);
    engine.addChild(host);

    // add any additional hosts
    if (hosts != null && !hosts.isEmpty()) {
        // grab current contexts from base host
        Container[] currentContexts = host.findChildren();
        log.info("Adding {} additional hosts", hosts.size());
        for (Host h : hosts) {
            log.debug("Host - name: {} appBase: {} info: {}",
                    new Object[] { h.getName(), h.getAppBase(), h.getInfo() });
            //add the contexts to each host
            for (Container cont : currentContexts) {
                Context c = (Context) cont;
                addContext(c.getPath(), c.getDocBase(), h);
            }
            //add the host to the engine
            engine.addChild(h);
        }
    }

    // Add new Engine to set of Engine for embedded server
    embedded.addEngine(engine);

    // set connection properties
    for (String key : connectionProperties.keySet()) {
        log.debug("Setting connection property: {} = {}", key, connectionProperties.get(key));
        if (connectors == null || connectors.isEmpty()) {
            connector.setProperty(key, connectionProperties.get(key));
        } else {
            for (Connector ctr : connectors) {
                ctr.setProperty(key, connectionProperties.get(key));
            }
        }
    }

    // set the bind address
    if (address == null) {
        //bind locally
        address = InetSocketAddress.createUnresolved("127.0.0.1", connector.getPort()).getAddress();
    }
    // apply the bind address
    ProtocolHandler handler = connector.getProtocolHandler();
    if (handler instanceof Http11Protocol) {
        ((Http11Protocol) handler).setAddress(address);
    } else if (handler instanceof Http11NioProtocol) {
        ((Http11NioProtocol) handler).setAddress(address);
    } else {
        log.warn("Unknown handler type: {}", handler.getClass().getName());
    }

    // Start server
    try {
        // Add new Connector to set of Connectors for embedded server,
        // associated with Engine
        if (connectors == null || connectors.isEmpty()) {
            embedded.addConnector(connector);
            log.trace("Connector oName: {}", connector.getObjectName());
        } else {
            for (Connector ctr : connectors) {
                embedded.addConnector(ctr);
                log.trace("Connector oName: {}", ctr.getObjectName());
            }
        }

        log.info("Starting Tomcat servlet engine");
        embedded.start();

        LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext));

        for (Container cont : host.findChildren()) {
            if (cont instanceof StandardContext) {
                StandardContext ctx = (StandardContext) cont;

                final ServletContext servletContext = ctx.getServletContext();
                log.debug("Context initialized: {}", servletContext.getContextPath());

                //set the hosts id
                servletContext.setAttribute("red5.host.id", getHostId());

                String prefix = servletContext.getRealPath("/");
                log.debug("Path: {}", prefix);

                try {
                    if (ctx.resourcesStart()) {
                        log.debug("Resources started");
                    }

                    log.debug("Context - available: {} privileged: {}, start time: {}, reloadable: {}",
                            new Object[] { ctx.getAvailable(), ctx.getPrivileged(), ctx.getStartTime(),
                                    ctx.getReloadable() });

                    Loader cldr = ctx.getLoader();
                    log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName());
                    if (cldr instanceof WebappLoader) {
                        log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath());
                    }
                    final ClassLoader webClassLoader = cldr.getClassLoader();
                    log.debug("Webapp classloader: {}", webClassLoader);

                    // get the (spring) config file path
                    final String contextConfigLocation = servletContext.getInitParameter(
                            org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                    ? defaultSpringConfigLocation
                                    : servletContext.getInitParameter(
                                            org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                    log.debug("Spring context config location: {}", contextConfigLocation);

                    // get the (spring) parent context key
                    final String parentContextKey = servletContext.getInitParameter(
                            org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                    ? defaultParentContextKey
                                    : servletContext.getInitParameter(
                                            org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                    log.debug("Spring parent context key: {}", parentContextKey);

                    //set current threads classloader to the webapp classloader
                    Thread.currentThread().setContextClassLoader(webClassLoader);

                    //create a thread to speed-up application loading
                    Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                        public void run() {
                            //set thread context classloader to web classloader
                            Thread.currentThread().setContextClassLoader(webClassLoader);
                            //get the web app's parent context
                            ApplicationContext parentContext = null;
                            if (applicationContext.containsBean(parentContextKey)) {
                                parentContext = (ApplicationContext) applicationContext
                                        .getBean(parentContextKey);
                            } else {
                                log.warn("Parent context was not found: {}", parentContextKey);
                            }
                            // create a spring web application context
                            final String contextClass = servletContext.getInitParameter(
                                    org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                            ? XmlWebApplicationContext.class.getName()
                                            : servletContext.getInitParameter(
                                                    org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                            //web app context (spring)
                            ConfigurableWebApplicationContext appctx = null;
                            try {
                                Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                                appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            } catch (Throwable e) {
                                throw new RuntimeException("Failed to load webapplication context class.", e);
                            }
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            //set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            //refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                        }
                    };
                    thread.setDaemon(true);
                    thread.start();

                } catch (Throwable t) {
                    log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                            t.getMessage());
                    t.printStackTrace();
                } finally {
                    //reset the classloader
                    Thread.currentThread().setContextClassLoader(originalClassLoader);
                }
            }
        }

        // if everything is ok at this point then call the rtmpt and rtmps
        // beans so they will init
        if (applicationContext.containsBean("red5.core")) {
            ApplicationContext core = (ApplicationContext) applicationContext.getBean("red5.core");
            if (core.containsBean("rtmpt.server")) {
                log.debug("Initializing RTMPT");
                core.getBean("rtmpt.server");
                log.debug("Finished initializing RTMPT");
            } else {
                log.info("Dedicated RTMPT server configuration was not specified");
            }
            if (core.containsBean("rtmps.server")) {
                log.debug("Initializing RTMPS");
                core.getBean("rtmps.server");
                log.debug("Finished initializing RTMPS");
            } else {
                log.info("Dedicated RTMPS server configuration was not specified");
            }
        } else {
            log.info("Core context was not found");
        }
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading tomcat, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading tomcat", e);
        }
    } finally {
        registerJMX();
    }

}

From source file:Admin_Thesaurus.ImportData.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (SystemIsLockedForAdministrativeJobs(request, response)) {
        return;/*from  w  ww  .j  a  v a2s.  c o m*/
    }
    String basePath = request.getSession().getServletContext().getRealPath("");

    // ---------------------- LOCK SYSTEM ----------------------
    ConfigDBadmin config = new ConfigDBadmin(basePath);
    DBAdminUtilities dbAdminUtils = new DBAdminUtilities();
    dbAdminUtils.LockSystemForAdministrativeJobs(config);

    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    HttpSession session = request.getSession();
    ServletContext context = session.getServletContext();
    SessionWrapperClass sessionInstance = new SessionWrapperClass();
    init(request, response, sessionInstance);

    PrintWriter out = response.getWriter();

    OutputStreamWriter logFileWriter = null;

    try {

        // check for previous logon but because of ajax usage respond with Session Invalidate str
        UserInfoClass SessionUserInfo = (UserInfoClass) sessionInstance.getAttribute("SessionUser");

        if (SessionUserInfo == null || !SessionUserInfo.servletAccessControl(this.getClass().getName())) {
            out.println("Session Invalidate");
            response.sendRedirect("Index");
            return;
        }

        //tools
        Utilities u = new Utilities();
        DBGeneral dbGen = new DBGeneral();
        DBImportData dbImport = new DBImportData();
        DBMergeThesauri dbMerge = new DBMergeThesauri();
        StringObject translatedMsgObj = new StringObject("");

        Vector<String> thesauriNames = new Vector<String>();

        CommonUtilsDBadmin common_utils = new CommonUtilsDBadmin(config);
        StringObject resultObj = new StringObject("");

        String initiallySelectedThesaurus = SessionUserInfo.selectedThesaurus;

        //Parameters
        String xmlFilePath = request.getParameter("importXMLfilename");

        //String importSchemaName    = request.getParameter("schematype");
        String importSchemaName = ConstantParameters.xmlschematype_THEMAS;
        String importThesaurusName = request.getParameter("Import_Thesaurus_NewName_NAME");
        String importMethodChoice = request.getParameter("ImportThesaurusMode");//thesaurusImport or bulkImport
        String importHierarchyName = u
                .getDecodedParameterValue(request.getParameter("Import_Thesaurus_HierarchyName"));
        String pathToErrorsXML = context.getRealPath("/translations/Consistencies_Error_Codes.xml");
        String language = context.getInitParameter("LocaleLanguage");
        String country = context.getInitParameter("LocaleCountry");
        String WebAppUsersFileName = request.getSession().getServletContext()
                .getRealPath("/" + UsersClass.WebAppUsersXMLFilePath);

        String logPath = context.getRealPath("/" + ConstantParameters.LogFilesFolderName);
        String logFileNamePath = logPath;
        String webAppSaveResults_Folder = Parameters.Save_Results_Folder;
        String pathToSaveScriptingAndLocale = context
                .getRealPath("/translations/SaveAll_Locale_And_Scripting.xml");
        Locale targetLocale = new Locale(language, country);

        if ((importMethodChoice.equals("thesaurusImport") && (importThesaurusName != null))
                || (importMethodChoice.equals("bulkImport") && importHierarchyName != null)) {
            UpDownFiles fup = new UpDownFiles();
            String[] formData = new String[10];
            FileItem[] dom = fup.prepareToUpBinary(request, formData);
            //Hashtable initParams = UpDownFiles.uploadParams;

            if (dom[0] != null) {

                String filename = xmlFilePath;
                ///String caption = (String) initParams.get("caption");

                filename = filename.substring(filename.lastIndexOf(File.separator) + 1);

                String fileType = filename.substring(filename.lastIndexOf(".") + 1);
                String userFileName = filename.substring(0, filename.lastIndexOf("."));

                filename = userFileName + "(" + getDate() + " " + getTime() + ")." + fileType;

                String fullPath = getServletContext().getRealPath("/Uploads") + "/" + filename;
                xmlFilePath = fullPath;
                if (fup.writeBinary(dom[0], fullPath)) {
                    //mode = 1;
                } else {
                    //mode = -1;
                }
            } else {
                //mode = -1;
            }
        }

        QClass Q = new QClass();
        TMSAPIClass TA = new TMSAPIClass();
        IntegerObject sis_session = new IntegerObject();
        IntegerObject tms_session = new IntegerObject();

        //open connection and start transaction
        if (dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, null, null,
                true) == QClass.APIFail) {
            Utils.StaticClass
                    .webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName());
            return;
        }

        dbGen.GetExistingThesaurus(false, thesauriNames, Q, sis_session);

        if (importMethodChoice.equals("thesaurusImport")) {

            //Format Name Of import Thesaurus
            importThesaurusName = importThesaurusName.trim();
            importThesaurusName = importThesaurusName.replaceAll(" ", "_");
            importThesaurusName = importThesaurusName.toUpperCase();

            if (thesauriNames.contains(importThesaurusName)) {

                resultObj.setValue(u.translateFromMessagesXML("root/ImportData/importThesaurusNameFailure",
                        new String[] { importThesaurusName }));
                //resultObj.setValue("Thesaurus '" + importThesaurusName + "' already exists in database. Please choose a different name for the Thesaurus.");

                Vector<String> allHierarchies = new Vector<String>();
                Vector<String> allGuideTerms = new Vector<String>();
                dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session,
                        allHierarchies, allGuideTerms);

                //end query and close connection
                Q.free_all_sets();
                Q.TEST_end_query();
                //Q.TEST_abort_transaction();
                dbGen.CloseDBConnection(Q, null, sis_session, null, false);

                StringBuffer xml = new StringBuffer();
                xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI));
                xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms,
                        targetLocale));

                xml.append(getXMLMiddle(thesauriNames,
                        u.translateFromMessagesXML("root/ImportData/ImportFunctionFailure", null)
                                + resultObj.getValue(),
                        importMethodChoice));
                xml.append(u.getXMLUserInfo(SessionUserInfo));
                xml.append(u.getXMLEnd());
                u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl");

                // ---------------------- UNLOCK SYSTEM ----------------------
                dbAdminUtils.UnlockSystemForAdministrativeJobs();
                return;
            }
        } else if (importMethodChoice.equals("bulkImport")) {
            importThesaurusName = SessionUserInfo.selectedThesaurus;
            if (thesauriNames.contains(importThesaurusName) == false) {

                //String pathToMessagesXML = context.getRealPath("/translations/Messages.xml");
                //StringObject resultMessageObj = new StringObject();
                StringObject resultMessageObj_2 = new StringObject();
                //Vector<String> errorArgs = new Vector<String>();

                resultObj.setValue(u.translateFromMessagesXML("root/ImportData/ThesaurusDoesNotExist",
                        new String[] { importThesaurusName }));

                //resultObj.setValue("Thesaurus '" + importThesaurusName + "' does not exist in database. Please choose a different thesaurus if this one still exists.");
                Vector<String> allHierarchies = new Vector<String>();
                Vector<String> allGuideTerms = new Vector<String>();
                dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session,
                        allHierarchies, allGuideTerms);

                //end query and close connection
                Q.free_all_sets();
                Q.TEST_end_query();
                //Q.TEST_abort_transaction();
                dbGen.CloseDBConnection(Q, null, sis_session, null, false);

                StringBuffer xml = new StringBuffer();
                xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI));
                xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms,
                        targetLocale));

                resultMessageObj_2
                        .setValue(u.translateFromMessagesXML("root/ImportData/InsertionFailure", null));
                xml.append(getXMLMiddle(thesauriNames, resultMessageObj_2.getValue() + resultObj.getValue(),
                        importMethodChoice));
                //xml.append(getXMLMiddle(thesauriNames, "Data insertion failure. " + resultObj.getValue(),importMethodChoice));
                xml.append(u.getXMLUserInfo(SessionUserInfo));
                xml.append(u.getXMLEnd());
                u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl");

                // ---------------------- UNLOCK SYSTEM ----------------------
                dbAdminUtils.UnlockSystemForAdministrativeJobs();
                return;
            }
        }

        //end query and close connection
        Q.free_all_sets();
        Q.TEST_end_query();
        dbGen.CloseDBConnection(Q, null, sis_session, null, false);
        Utils.StaticClass.closeDb();

        StringObject DBbackupFileNameCreated = new StringObject("");

        long startTime = Utilities.startTimer();
        String time = Utilities.GetNow();
        String Filename = "Import_Thesaurus_" + importThesaurusName + "_" + time;
        logFileNamePath += "/" + Filename + ".xml";

        try {
            OutputStream fout = new FileOutputStream(logFileNamePath);
            OutputStream bout = new BufferedOutputStream(fout);
            logFileWriter = new OutputStreamWriter(bout, "UTF-8");
            logFileWriter.append(ConstantParameters.xmlHeader);//+ "\r\n"

            //logFileWriter.append("<?xml-stylesheet type=\"text/xsl\" href=\"../" + webAppSaveResults_Folder + "/ImportCopyMergeThesaurus_Report.xsl" + "\"?>\r\n");
            logFileWriter.append("<page language=\"" + Parameters.UILang + "\" primarylanguage=\""
                    + Parameters.PrimaryLang.toLowerCase() + "\">\r\n");
            logFileWriter.append("<title>"
                    + u.translateFromMessagesXML("root/ImportData/ReportTitle",
                            new String[] { importThesaurusName, time })
                    + "</title>\r\n" + "<pathToSaveScriptingAndLocale>" + pathToSaveScriptingAndLocale
                    + "</pathToSaveScriptingAndLocale>\r\n");
            //logFileWriter.append("<!--"+time + " LogFile for data import in thesaurus: " + importThesaurusName +".-->\r\n");
            Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + time
                    + " LogFile for data import in thesaurus: " + importThesaurusName + ".");

        } catch (Exception exc) {
            Utils.StaticClass.webAppSystemOutPrintln(
                    Parameters.LogFilePrefix + "Error in opening file: " + exc.getMessage());
            Utils.StaticClass.handleException(exc);
        }

        if (importMethodChoice.equals("thesaurusImport")) {

            if (dbImport.thesaurusImportActions(SessionUserInfo, common_utils, config, targetLocale,
                    pathToErrorsXML, xmlFilePath, importSchemaName, importThesaurusName,
                    "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated,
                    resultObj, logFileWriter) == false) {
                abortActions(request, sessionInstance, context, targetLocale, common_utils,
                        initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj,
                        out);
                return;
            }
        } else if (importMethodChoice.equals("bulkImport")) {
            /*
             //open connection and start Transaction
             if(dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, tms_session, SessionUserInfo.selectedThesaurus, false)==QClass.APIFail)
             {
             Utils.StaticClass.webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName());
             return;
             }
             */
            if (dbImport.bulkImportActions(sessionInstance, context, common_utils, config, targetLocale,
                    pathToErrorsXML, xmlFilePath, importThesaurusName, importHierarchyName,
                    "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated,
                    resultObj, logFileWriter) == false) {
                abortActions(request, sessionInstance, context, targetLocale, common_utils,
                        initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj,
                        out);
                return;
            }

        }

        commitActions(request, WebAppUsersFileName, sessionInstance, context, targetLocale, importThesaurusName,
                out, Filename.concat(".html"));

        //ReportSuccessMessage            
        logFileWriter
                .append("\r\n<creationInfo>"
                        + u.translateFromMessagesXML("root/ImportData/ReportSuccessMessage",
                                new String[] { importThesaurusName, xmlFilePath,
                                        ((Utilities.stopTimer(startTime)) / 60) + "" })
                        + "</creationInfo>\r\n");

        if (logFileWriter != null) {
            logFileWriter.append("</page>");
            logFileWriter.flush();
            logFileWriter.close();
        }

        //Now XSL should be found and java xsl transformation should be performed
        String XSL = context.getRealPath("/" + webAppSaveResults_Folder)
                + "/ImportCopyMergeThesaurus_Report.xsl";

        u.XmlFileTransform(logFileNamePath, XSL, logPath + "/" + Filename.concat(".html"));

    } catch (Exception e) {

        Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + ".Exception catched in servlet "
                + getServletName() + ". Message:" + e.getMessage());
        Utils.StaticClass.handleException(e);
        if (logFileWriter != null) {
            logFileWriter.append("</page>");
            logFileWriter.flush();
            logFileWriter.close();
        }
    } finally {
        out.flush();
        out.close();
        sessionInstance.writeBackToSession(session);
    }
}

From source file:net.jawr.web.bundle.processor.BundleProcessor.java

/**
 * Returns the list of servlet definition, which must be initialize
 * /*from   w  w  w. j av  a  2  s .c  om*/
 * @param webXmlDoc
 *            the web.xml document
 * @param servletContext
 *            the servlet context
 * @param servletsToInitialize
 *            the list of servlet to initialize
 * @param webAppClassLoader
 *            the web application class loader
 * @return the list of servlet definition, which must be initialize
 * @throws ClassNotFoundException
 *             if a class is not found
 */
protected List<ServletDefinition> getWebXmlServletDefinitions(Document webXmlDoc, ServletContext servletContext,
        List<String> servletsToInitialize, ClassLoader webAppClassLoader) throws ClassNotFoundException {

    // Parse the servlet configuration
    NodeList servletNodes = webXmlDoc.getElementsByTagName(SERVLET_TAG_NAME);

    List<ServletDefinition> servletDefinitions = new ArrayList<ServletDefinition>();

    for (int i = 0; i < servletNodes.getLength(); i++) {

        String servletName = null;
        Class<?> servletClass = null;
        MockServletConfig config = new MockServletConfig(servletContext);
        int order = i;

        Node servletNode = servletNodes.item(i);
        Map<String, Object> initParameters = new HashMap<String, Object>();
        NodeList childNodes = servletNode.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
            Node servletChildNode = childNodes.item(j);
            if (servletChildNode.getNodeName().equals(SERVLET_NAME_TAG_NAME)) {

                servletName = getTextValue(servletChildNode);
                config.setServletName(servletName);

            } else if (servletChildNode.getNodeName().equals(SERVLET_CLASS_TAG_NAME)) {

                String servletClassName = getTextValue(servletChildNode);
                servletClass = webAppClassLoader.loadClass(servletClassName);

            } else if (servletChildNode.getNodeName().equals(INIT_PARAM_TAG_NAME)) {

                initializeInitParams(servletChildNode, initParameters);
            } else if (servletChildNode.getNodeName().equals(LOAD_ON_STARTUP_TAG_NAME)) {

                order = Integer.parseInt(getTextValue(servletChildNode));
            }
        }

        // Initialize the servlet config with the init parameters
        config.setInitParameters(initParameters);

        // If the servlet name is part of the list of servlet to initialized
        // Set the flag accordingly
        if (servletsToInitialize.contains(servletName) || JawrServlet.class.isAssignableFrom(servletClass)) {
            ServletDefinition servletDef = new ServletDefinition(servletClass, config, order);
            servletDefinitions.add(servletDef);
        }
        // Handle Spring MVC servlet definition
        if (servletContext.getInitParameter(CONFIG_LOCATION_PARAM) == null
                && servletClass.getName().equals("org.springframework.web.servlet.DispatcherServlet")) {
            ((MockServletContext) servletContext).putInitParameter(CONFIG_LOCATION_PARAM,
                    "/WEB-INF/" + servletName + "-servlet.xml");
        }

    }
    return servletDefinitions;
}

From source file:org.apache.marmotta.platform.core.startup.MarmottaStartupService.java

/**
 * Startup the Apache Marmotta Configuration. This method ensures that the Apache Marmotta home directory is created and the
 * ConfigurationService is properly initialised. It must be called first in the startup sequence.
 * The parameters home and configurationOverride can be used to override the default settings
 * of the Apache Marmotta./*  w  ww . j a  v  a  2  s. c  o  m*/
 *
 * @param home                    home directory of the Apache Marmotta instance (may be null, in which case the default will be used)
 * @param configurationOverride   configuration options that should override the default values from default-config.properties (may be null)
 * @param context                 the servlet context the Apache Marmotta is running in (may be null)
 */
public void startupConfiguration(String home, Configuration configurationOverride, ServletContext context) {
    lock.lock();

    //to set config version number
    String versionNumber = DEFAULT_KIWI_VERSION;

    try {
        if (configurationStarted) {
            log.warn("Apache Marmotta Startup: configuration already started; ignoring second request");
            return;
        }

        ModuleConfiguration coreConfiguration = moduleService.getModuleConfiguration(this.getClass());

        if (coreConfiguration.hasBuildInfo()) {
            log.info("Apache Marmotta Core Version {} starting up ... ", coreConfiguration.getModuleVersion());
            log.info("Build Information:");
            log.info(" - Build User: {}", coreConfiguration.getBuildUser());
            log.info(" - Build Host: {}", coreConfiguration.getBuildHost());
            log.info(" - Build Time: {}", coreConfiguration.getBuildTimestamp());
            log.info(" - Build OS:   {}", coreConfiguration.getBuildOS());
            log.info(" - Revision:   {}", coreConfiguration.getBuildRevisionHash());
            versionNumber = coreConfiguration.getModuleVersion();
        } else {
            log.info("Apache Marmotta Core (Development Version) starting up ... ");
        }

        //TODO: refactor this code
        if (StringUtils.isBlank(home)) {
            home = System.getProperty("marmotta.home");
            if (StringUtils.isNotBlank(home)) {
                log.info("Configured working directory {} from system property marmotta.home", home);
            } else {
                home = System.getProperty("lmf.home");
                if (StringUtils.isNotBlank(home)) {
                    log.info("Configured working directory {} from system property lmf.home", home);
                } else {
                    home = System.getProperty("kiwi.home");
                    if (StringUtils.isNotBlank(home)) {
                        log.info("Configured working directory {} from system property kiwi.home", home);
                    } else {
                        home = System.getenv("MARMOTTA_HOME");
                        if (StringUtils.isNotBlank(home)) {
                            log.info("Configured working directory {} from environment variable MARMOTTA_HOME",
                                    home);
                        } else {
                            home = System.getenv("LMF_HOME");
                            if (StringUtils.isNotBlank(home)) {
                                log.info("Configured working directory {} from environment variable LMF_HOME",
                                        home);
                            } else {
                                home = System.getenv("KIWI_HOME");
                                if (StringUtils.isNotBlank(home)) {
                                    log.info(
                                            "Configured working directory {} from environment variable KIWI_HOME",
                                            home);
                                } else {
                                    if (context != null) {
                                        home = context.getInitParameter("marmotta.home");
                                        if (StringUtils.isNotBlank(home)) {
                                            log.info(
                                                    "Configured working directory {} from servlet context parameter marmotta.home",
                                                    home);
                                        }
                                    } else {
                                        log.error(
                                                "could not determine Apache Marmotta home directory, please set the environment variable MARMOTTA_HOME");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (StringUtils.isNotBlank(home)) {
            if (home.startsWith("~" + File.separator)) {
                home = System.getProperty("user.home") + home.substring(1);
            }
            configurationService.setHome(home);
        } else {
            log.error("home directory not properly initialized!!!");
        }

        if (context != null) {
            configurationService.setServletContext(context);
        }

        configurationService.initialize(home, configurationOverride);

        configurationService.setConfiguration("kiwi.version", versionNumber);

        if (context != null) {
            configurationService.setConfiguration("kiwi.path", context.getContextPath());

            // register the systray links provided by the different components
            Map<String, String> demoLinks = new HashMap<>();
            Map<String, String> adminLinks = new HashMap<>();

            for (MarmottaSystrayLink link : CDIContext.getInstances(MarmottaSystrayLink.class)) {
                if (link.getSection() == MarmottaSystrayLink.Section.DEMO) {
                    demoLinks.put(link.getLabel(), link.getLink());
                } else if (link.getSection() == MarmottaSystrayLink.Section.ADMIN) {
                    adminLinks.put(link.getLabel(), link.getLink());
                }
            }
            context.setAttribute("systray.admin", adminLinks);
            context.setAttribute("systray.demo", demoLinks);
        }

        configurationStarted = true;
    } finally {
        lock.unlock();
    }

}

From source file:com.sun.faces.config.ConfigureListener.java

public void contextInitialized(ServletContextEvent sce) {
    // Prepare local variables we will need
    Digester digester = null;//from   w ww.  j  a v  a  2s . c  o m
    FacesConfigBean fcb = new FacesConfigBean();
    ServletContext context = sce.getServletContext();

    // store the servletContext instance in Thread local Storage.
    // This enables our Application's ApplicationAssociate to locate
    // it so it can store the ApplicationAssociate in the
    // ServletContext.
    tlsExternalContext.set(new ServletContextAdapter(context));

    // see if we're operating in the unit test environment
    try {
        if (RIConstants.IS_UNIT_TEST_MODE) {
            // if so, put the fcb in the servletContext
            context.setAttribute(FACES_CONFIG_BEAN_KEY, fcb);
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Can't query for test environment");
        }
    }

    // see if we need to disable our TLValidator
    RIConstants.HTML_TLV_ACTIVE = isFeatureEnabled(context, ENABLE_HTML_TLV);

    URL url = null;
    if (log.isDebugEnabled()) {
        log.debug("contextInitialized(" + context.getServletContextName() + ")");
    }

    // Ensure that we initialize a particular application ony once
    if (initialized()) {
        return;
    }

    // Step 1, configure a Digester instance we can use
    digester = digester(isFeatureEnabled(context, VALIDATE_XML));

    // Step 2, parse the RI configuration resource
    url = Util.getCurrentLoader(this).getResource(JSF_RI_CONFIG);
    parse(digester, url, fcb);

    // Step 3, parse any "/META-INF/faces-config.xml" resources
    Iterator resources;
    try {
        List list = new LinkedList();
        Enumeration items = Util.getCurrentLoader(this).getResources(META_INF_RESOURCES);
        while (items.hasMoreElements()) {
            list.add(0, items.nextElement());
        }
        resources = list.iterator();
    } catch (IOException e) {
        String message = null;
        try {
            message = Util.getExceptionMessageString(Util.CANT_PARSE_FILE_ERROR_MESSAGE_ID,
                    new Object[] { META_INF_RESOURCES });
        } catch (Exception ee) {
            message = "Can't parse configuration file:" + META_INF_RESOURCES;
        }
        log.warn(message, e);
        throw new FacesException(message, e);
    }
    while (resources.hasNext()) {
        url = (URL) resources.next();
        parse(digester, url, fcb);
    }

    // Step 4, parse any context-relative resources specified in
    // the web application deployment descriptor
    String paths = context.getInitParameter(FacesServlet.CONFIG_FILES_ATTR);
    if (paths != null) {
        for (StringTokenizer t = new StringTokenizer(paths.trim(), ","); t.hasMoreTokens();) {

            url = getContextURLForPath(context, t.nextToken().trim());
            if (url != null) {
                parse(digester, url, fcb);
            }

        }
    }

    // Step 5, parse "/WEB-INF/faces-config.xml" if it exists
    url = getContextURLForPath(context, WEB_INF_RESOURCE);
    if (url != null) {
        parse(digester, url, fcb);
    }

    // Step 6, use the accumulated configuration beans to configure the RI
    try {
        configure(context, fcb);
    } catch (FacesException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw new FacesException(e);
    }

    // Step 7, verify that all the configured factories are available
    // and optionall that configured objects can be created
    verifyFactories();
    if (isFeatureEnabled(context, VERIFY_OBJECTS)) {
        verifyObjects(context, fcb);
    }

    tlsExternalContext.set(null);
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

public void init(ServletConfig config) throws ServletException {
    ServletContext ctx = config.getServletContext();
    config(ctx);/*from   w w w.ja v a  2s.  c o m*/
    appVersion = ctx.getInitParameter("app-version");
    srcVersion = ctx.getInitParameter("src-version");
    buildTimestamp = ctx.getInitParameter("build-timestamp");
    super.init(config);
}

From source file:com.portfolio.rest.RestServicePortfolio.java

public RestServicePortfolio(@Context ServletConfig sc, @Context ServletContext context) {
    try {/*w  w  w  .j  a v  a2 s . c  o  m*/
        // Initialize data provider and cas
        try {
            casUrlValidation = context.getInitParameter("casUrlValidation");
        } catch (Exception ex) {
            casUrlValidation = null;
        }
        ;

        try {
            elggDefaultApiUrl = context.getInitParameter("elggDefaultApiUrl");
        } catch (Exception ex) {
            elggDefaultApiUrl = null;
        }
        ;

        try {
            elggDefaultSiteUrl = context.getInitParameter("elggDefaultSiteUrl");
        } catch (Exception ex) {
            elggDefaultSiteUrl = null;
        }
        ;

        try {
            elggApiKey = context.getInitParameter("elggApiKey");
        } catch (Exception ex) {
            elggApiKey = null;
        }
        ;

        try {
            elggDefaultUserPassword = context.getInitParameter("elggDefaultUserPassword");
        } catch (Exception ex) {
            elggDefaultUserPassword = null;
        }
        ;

        servContext = context;
        String dataProviderName = sc.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        // Try to initialize Datasource
        InitialContext cxt = new InitialContext();
        if (cxt == null) {
            throw new Exception("no context found!");
        }

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        logger.error("CAN'T INIT PROVIDER: " + e.toString());
        e.printStackTrace();
    }
}

From source file:org.apache.nifi.web.ContentViewerController.java

/**
 * Gets the content and defers to registered viewers to generate the markup.
 *
 * @param request servlet request/*  w ww. j  a  va2  s .  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // specify the charset in a response header
    response.addHeader("Content-Type", "text/html; charset=UTF-8");

    // get the content
    final ServletContext servletContext = request.getServletContext();
    final ContentAccess contentAccess = (ContentAccess) servletContext.getAttribute("nifi-content-access");

    final ContentRequestContext contentRequest;
    try {
        contentRequest = getContentRequest(request);
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to interpret content request.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    if (contentRequest.getDataUri() == null) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "The data reference must be specified.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // get the content
    final DownloadableContent downloadableContent;
    try {
        downloadableContent = contentAccess.getContent(contentRequest);
    } catch (final ResourceNotFoundException rnfe) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to find the specified content");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final AccessDeniedException ade) {
        request.setAttribute("title", "Access Denied");
        request.setAttribute("messages",
                "Unable to approve access to the specified content: " + ade.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "An unexpected error has occurred: " + e.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // determine how we want to view the data
    String mode = request.getParameter("mode");

    // if the name isn't set, use original
    if (mode == null) {
        mode = DisplayMode.Original.name();
    }

    // determine the display mode
    final DisplayMode displayMode;
    try {
        displayMode = DisplayMode.valueOf(mode);
    } catch (final IllegalArgumentException iae) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Invalid display mode: " + mode);

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // buffer the content to support resetting in case we need to detect the content type or char encoding
    try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent());) {
        final String mimeType;
        final String normalizedMimeType;

        // when standalone and we don't know the type is null as we were able to directly access the content bypassing the rest endpoint,
        // when clustered and we don't know the type set to octet stream since the content was retrieved from the node's rest endpoint
        if (downloadableContent.getType() == null || StringUtils
                .startsWithIgnoreCase(downloadableContent.getType(), MediaType.OCTET_STREAM.toString())) {
            // attempt to detect the content stream if we don't know what it is ()
            final DefaultDetector detector = new DefaultDetector();

            // create the stream for tika to process, buffered to support reseting
            final TikaInputStream tikaStream = TikaInputStream.get(bis);

            // provide a hint based on the filename
            final Metadata metadata = new Metadata();
            metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename());

            // Get mime type
            final MediaType mediatype = detector.detect(tikaStream, metadata);
            mimeType = mediatype.toString();
        } else {
            mimeType = downloadableContent.getType();
        }

        // Extract only mime type and subtype from content type (anything after the first ; are parameters)
        // Lowercase so subsequent code does not need to implement case insensitivity
        normalizedMimeType = mimeType.split(";", 2)[0].toLowerCase();

        // add attributes needed for the header
        request.setAttribute("filename", downloadableContent.getFilename());
        request.setAttribute("contentType", mimeType);

        // generate the header
        request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response);

        // remove the attributes needed for the header
        request.removeAttribute("filename");
        request.removeAttribute("contentType");

        // generate the markup for the content based on the display mode
        if (DisplayMode.Hex.equals(displayMode)) {
            final byte[] buffer = new byte[BUFFER_LENGTH];
            final int read = StreamUtils.fillBuffer(bis, buffer, false);

            // trim the byte array if necessary
            byte[] bytes = buffer;
            if (read != buffer.length) {
                bytes = new byte[read];
                System.arraycopy(buffer, 0, bytes, 0, read);
            }

            // convert bytes into the base 64 bytes
            final String base64 = Base64.encodeBase64String(bytes);

            // defer to the jsp
            request.setAttribute("content", base64);
            request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response);
        } else {
            // lookup a viewer for the content
            final String contentViewerUri = servletContext.getInitParameter(normalizedMimeType);

            // handle no viewer for content type
            if (contentViewerUri == null) {
                request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response);
            } else {
                // create a request attribute for accessing the content
                request.setAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE, new ViewableContent() {
                    @Override
                    public InputStream getContentStream() {
                        return bis;
                    }

                    @Override
                    public String getContent() throws IOException {
                        // detect the charset
                        final CharsetDetector detector = new CharsetDetector();
                        detector.setText(bis);
                        detector.enableInputFilter(true);
                        final CharsetMatch match = detector.detect();

                        // ensure we were able to detect the charset
                        if (match == null) {
                            throw new IOException("Unable to detect character encoding.");
                        }

                        // convert the stream using the detected charset
                        return IOUtils.toString(bis, match.getName());
                    }

                    @Override
                    public ViewableContent.DisplayMode getDisplayMode() {
                        return displayMode;
                    }

                    @Override
                    public String getFileName() {
                        return downloadableContent.getFilename();
                    }

                    @Override
                    public String getContentType() {
                        return normalizedMimeType;
                    }

                    @Override
                    public String getRawContentType() {
                        return mimeType;
                    }
                });

                try {
                    // generate the content
                    final ServletContext viewerContext = servletContext.getContext(contentViewerUri);
                    viewerContext.getRequestDispatcher("/view-content").include(request, response);
                } catch (final Exception e) {
                    String message = e.getMessage() != null ? e.getMessage() : e.toString();
                    message = "Unable to generate view of data: " + message;

                    // log the error
                    logger.error(message);
                    if (logger.isDebugEnabled()) {
                        logger.error(StringUtils.EMPTY, e);
                    }

                    // populate the request attributes
                    request.setAttribute("title", "Error");
                    request.setAttribute("messages", message);

                    // forward to the error page
                    final ServletContext viewerContext = servletContext.getContext("/nifi");
                    viewerContext.getRequestDispatcher("/message").forward(request, response);
                    return;
                }

                // remove the request attribute
                request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
            }
        }

        // generate footer
        request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response);
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {/*from w w  w .j a va 2 s .c o m*/

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}