Example usage for javax.servlet ServletContext setAttribute

List of usage examples for javax.servlet ServletContext setAttribute

Introduction

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

Prototype

public void setAttribute(String name, Object object);

Source Link

Document

Binds an object to a given attribute name in this ServletContext.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.ApplicationModelSetup.java

/**
 * Setup the application configuration model. It is frequently called the
 * display model. If this is a new DB, populate the display model with the
 * initial data.//from   w w w .  j ava  2 s  . c  o  m
 * 
 * Also load any files that get loaded to the display model at each tomcat
 * startup.
 * 
 * Also, at each start of tomcat, load The display TBox and the
 * display/display model.
 */
private void setupDisplayModel(DataSource bds, ServletContext ctx, StartupStatus ss) {

    // display, editing and navigation Model 
    try {
        Model displayDbModel = makeDBModel(bds, JENA_DISPLAY_METADATA_MODEL, DB_ONT_MODEL_SPEC, ctx);
        if (displayDbModel.size() == 0) {
            readOntologyFilesInPathSet(APPPATH, ctx, displayDbModel);
        }
        OntModel displayModel = ModelFactory.createOntologyModel(MEM_ONT_MODEL_SPEC);
        displayModel.add(displayDbModel);
        displayModel.getBaseModel().register(new ModelSynchronizer(displayDbModel));
        ModelContext.setDisplayModel(displayModel, ctx);

        //at each startup load all RDF files from directory to sub-models of display model  
        initializeDisplayLoadedAtStartup(ctx, displayModel);
    } catch (Throwable t) {
        log.error("Unable to load user application configuration model", t);
        ss.fatal(this, "Unable to load user application configuration model", t);
    }

    //display tbox - currently reading in every time
    try {
        Model displayTboxModel = makeDBModel(bds, JENA_DISPLAY_TBOX_MODEL, DB_ONT_MODEL_SPEC, ctx);

        //Reading in single file every time, needs to be cleared/removed every time
        readOntologyFileFromPath(APPPATH_LOAD + "displayTBOX.n3", displayTboxModel, ctx);
        OntModel appTBOXModel = ModelFactory.createOntologyModel(MEM_ONT_MODEL_SPEC);
        appTBOXModel.add(displayTboxModel);
        appTBOXModel.getBaseModel().register(new ModelSynchronizer(displayTboxModel));
        ctx.setAttribute("displayOntModelTBOX", appTBOXModel);
        log.debug("Loaded file " + APPPATH_LOAD + "displayTBOX.n3 into display tbox model");
    } catch (Throwable t) {
        log.error("Unable to load user application configuration model TBOX", t);
        ss.fatal(this, "Unable to load user application configuration model TBOX", t);
    }

    //Display Display model, currently empty, create if doesn't exist but no files to load
    try {
        Model displayDisplayModel = makeDBModel(bds, JENA_DISPLAY_DISPLAY_MODEL, DB_ONT_MODEL_SPEC, ctx);

        //Reading in single file every time, needs to be cleared/removed every
        readOntologyFileFromPath(APPPATH_LOAD + "displayDisplay.n3", displayDisplayModel, ctx);
        OntModel appDisplayDisplayModel = ModelFactory.createOntologyModel(MEM_ONT_MODEL_SPEC);
        appDisplayDisplayModel.add(displayDisplayModel);
        appDisplayDisplayModel.getBaseModel().register(new ModelSynchronizer(displayDisplayModel));
        ctx.setAttribute("displayOntModelDisplayModel", appDisplayDisplayModel);
        log.debug("Loaded file " + APPPATH_LOAD + "displayDisplay.n3 into display display model");
    } catch (Throwable t) {
        log.error("Unable to load user application configuration model Display Model", t);
        ss.fatal(this, "Unable to load user application configuration model Display Model", t);
    }
}

From source file:alpha.portal.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}// w  w  w  . ja  va 2  s  . c  o  m
 */
@SuppressWarnings("unchecked")
public void contextInitialized(final ServletContextEvent event) {
    StartupListener.log.debug("Initializing context...");

    final ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*
     * String[] beans = ctx.getBeanDefinitionNames(); for (String bean :
     * beans) { log.debug(bean); }
     */

    PasswordEncoder passwordEncoder = null;
    try {
        final ProviderManager provider = (ProviderManager) ctx
                .getBean("org.springframework.security.authentication.ProviderManager#0");
        for (final Object o : provider.getProviders()) {
            final AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (final NoSuchBeanDefinitionException n) {
        StartupListener.log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (StartupListener.log.isDebugEnabled()) {
        StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        StartupListener.log.debug("Populating drop-downs...");
    }

    StartupListener.setupContext(context);
}

From source file:net.paoding.rose.web.impl.module.ModulesBuilderImpl.java

public List<Module> build(List<ModuleResource> moduleResources, WebApplicationContext rootContext)
        throws Exception {

    // ????????/*from   w  w  w. j av  a  2s .co  m*/
    moduleResources = new ArrayList<ModuleResource>(moduleResources);
    Collections.sort(moduleResources);

    // ??
    List<Module> modules = new ArrayList<Module>(moduleResources.size());
    Map<ModuleResource, Module> modulesAsMap = new HashMap<ModuleResource, Module>();

    // 
    for (ModuleResource moduleResource : moduleResources) {
        final Module parentModule = (moduleResource.getParent() == null) ? null//
                : modulesAsMap.get(moduleResource.getParent());
        final WebApplicationContext parentContext = (parentModule == null) ? rootContext//
                : parentModule.getApplicationContext();
        final String namespace = "context@controllers" + moduleResource.getRelativePath().replace('/', '.');

        // modulespring context
        final ServletContext servletContext = parentContext == null ? null //
                : parentContext.getServletContext();
        final ModuleAppContext moduleContext = ModuleAppContext.createModuleContext(//
                parentContext, //
                moduleResource.getContextResources(), //
                moduleResource.getMessageBasenames(), //
                /*id*/moduleResource.getModuleUrl().toString(), //
                namespace//
        );

        // ??...applicationContext
        registerBeanDefinitions(moduleContext, moduleResource.getModuleClasses());

        // module
        final ModuleImpl module = new ModuleImpl(//
                parentModule, //
                moduleResource.getModuleUrl(), //
                moduleResource.getMappingPath(), //
                moduleResource.getRelativePath(), //
                moduleContext);
        //
        modulesAsMap.put(moduleResource, module);

        // servletContext
        if (servletContext != null) {
            String contextAttrKey = WebApplicationContext.class.getName() + "@" + moduleResource.getModuleUrl();
            servletContext.setAttribute(contextAttrKey, moduleContext);
        }

        // Springweb??ParamValidatorParamResolver, ControllerInterceptor, ControllerErrorHandler
        List<ParamResolver> customerResolvers = findContextResolvers(moduleContext);

        // resolvers
        module.setCustomerResolvers(customerResolvers);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply resolvers " + customerResolvers);
        }

        // module
        List<InterceptorDelegate> interceptors = findInterceptors(moduleContext);
        for (Iterator<InterceptorDelegate> iter = interceptors.iterator(); iter.hasNext();) {
            InterceptorDelegate interceptor = iter.next();

            ControllerInterceptor most = InterceptorDelegate.getMostInnerInterceptor(interceptor);

            if (!most.getClass().getName().startsWith("net.paoding.rose.web")) {

                // deny?
                if (moduleResource.getInterceptedDeny() != null) {
                    if (RoseStringUtil.matches(moduleResource.getInterceptedDeny(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by rose.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
                //  allow?
                if (moduleResource.getInterceptedAllow() != null) {
                    if (!RoseStringUtil.matches(moduleResource.getInterceptedAllow(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by rose.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
            }
        }
        module.setControllerInterceptors(interceptors);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply intercetpors " + interceptors);
        }

        // validatormodule
        List<ParamValidator> validators = findContextValidators(moduleContext);
        module.setValidators(validators);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply global validators " + validators);
        }

        // errorhandler
        ControllerErrorHandler errorHandler = getContextErrorHandler(moduleContext);
        if (errorHandler != null) {
            if (Proxy.isProxyClass(errorHandler.getClass())) {
                module.setErrorHandler(errorHandler);
            } else {
                ErrorHandlerDispatcher dispatcher = new ErrorHandlerDispatcher(errorHandler);
                module.setErrorHandler(dispatcher);
            }
            if (logger.isInfoEnabled()) {
                logger.info("set errorHandler: " + module.getMappingPath() + "  " + errorHandler);
            }
        }

        // controllers
        final ListableBeanFactory beanFactory = moduleContext.getBeanFactory();
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            checkController(moduleContext, beanName, module);
        }

        // 
        modules.add(module);
    }

    return modules;
}

From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java

public List<Module> build(List<ModuleResource> moduleResources, WebApplicationContext rootContext)
        throws Exception {

    // ????????/*from  w w  w . j a  va  2s .  co  m*/
    moduleResources = new ArrayList<ModuleResource>(moduleResources);
    Collections.sort(moduleResources);

    // ??
    List<Module> modules = new ArrayList<Module>(moduleResources.size());
    Map<ModuleResource, Module> modulesAsMap = new HashMap<ModuleResource, Module>();

    // 
    for (ModuleResource moduleResource : moduleResources) {
        final Module parentModule = (moduleResource.getParent() == null) ? null//
                : modulesAsMap.get(moduleResource.getParent());
        final WebApplicationContext parentContext = (parentModule == null) ? rootContext//
                : parentModule.getApplicationContext();
        final String namespace = "context@controllers" + moduleResource.getRelativePath().replace('/', '.');

        // modulespring context
        final ServletContext servletContext = parentContext == null ? null //
                : parentContext.getServletContext();
        final ModuleAppContext moduleContext = ModuleAppContext.createModuleContext(//
                parentContext, //
                moduleResource.getContextResources(), //
                moduleResource.getMessageBasenames(), //
                /*id*/moduleResource.getModuleUrl().toString(), //
                namespace//
        );

        // ??...applicationContext
        registerBeanDefinitions(moduleContext, moduleResource.getModuleClasses());

        // module
        final ModuleImpl module = new ModuleImpl(//
                parentModule, //
                moduleResource.getModuleUrl(), //
                moduleResource.getMappingPath(), //
                moduleResource.getRelativePath(), //
                moduleContext);
        //
        modulesAsMap.put(moduleResource, module);

        // servletContext
        if (servletContext != null) {
            String contextAttrKey = WebApplicationContext.class.getName() + "@" + moduleResource.getModuleUrl();
            servletContext.setAttribute(contextAttrKey, moduleContext);
        }

        // Springweb??ParamValidatorParamResolver, ControllerInterceptor, ControllerErrorHandler
        List<ParamResolver> customerResolvers = findContextResolvers(moduleContext);

        // resolvers
        module.setCustomerResolvers(customerResolvers);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply resolvers " + customerResolvers);
        }

        // module
        List<InterceptorDelegate> interceptors = findInterceptors(moduleContext);
        for (Iterator<InterceptorDelegate> iter = interceptors.iterator(); iter.hasNext();) {
            InterceptorDelegate interceptor = iter.next();

            ControllerInterceptor most = InterceptorDelegate.getMostInnerInterceptor(interceptor);

            if (!most.getClass().getName().startsWith("net.paoding.rose.web")) {

                // deny?
                if (moduleResource.getInterceptedDeny() != null) {
                    if (BlitzStringUtil.matches(moduleResource.getInterceptedDeny(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by rose.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
                //  allow?
                if (moduleResource.getInterceptedAllow() != null) {
                    if (!BlitzStringUtil.matches(moduleResource.getInterceptedAllow(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by rose.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
            }
        }
        module.setControllerInterceptors(interceptors);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply intercetpors " + interceptors);
        }

        // validatormodule
        List<ParamValidator> validators = findContextValidators(moduleContext);
        module.setValidators(validators);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply global validators " + validators);
        }

        // errorhandler
        ControllerErrorHandler errorHandler = getContextErrorHandler(moduleContext);
        if (errorHandler != null) {
            if (Proxy.isProxyClass(errorHandler.getClass())) {
                module.setErrorHandler(errorHandler);
            } else {
                ErrorHandlerDispatcher dispatcher = new ErrorHandlerDispatcher(errorHandler);
                module.setErrorHandler(dispatcher);
            }
            if (logger.isInfoEnabled()) {
                logger.info("set errorHandler: " + module.getMappingPath() + "  " + errorHandler);
            }
        }

        // controllers
        final ListableBeanFactory beanFactory = moduleContext.getBeanFactory();
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            checkController(moduleContext, beanName, module);
        }

        // 
        modules.add(module);
    }

    return modules;
}

From source file:com.litt.saap.core.web.listener.InitSystemListener.java

/**
 * ?.//from  w  w  w .ja va2s . c  o m
 */
public void contextInitialized(ServletContextEvent event) {
    super.contextInitialized(event);
    ServletContext application = event.getServletContext();
    //HOME?
    Configuration config = ConfigManager.getInstance().getConfig();
    if (config.isEmpty()) {
        logger.error("???");
        throw new java.lang.RuntimeException("???");
    }
    logger.info("?" + config.getString("system.version"));
    //homePath = props.getProperty("home.path");
    String homePath = config.getString("home.path");
    CoreConstants.IS_DEBUG = config.getBoolean("debug", false);

    SaapConstants.HOME_PATH = homePath; //????
    logger.info("?" + homePath);
    File homeFile = new File(homePath);
    if (!homeFile.exists()) //???
    {
        homeFile.mkdirs();
    }

    //read license.
    //      File licensePath = new File(homePath, "license");
    //      File licenseFile = new File(licensePath, "license.xml");
    //      File publicKeyFile = new File(licensePath, "license.key");
    //      try {
    //         LicenseManager.reload(licenseFile.getPath(), publicKeyFile.getPath());
    //      } catch (LicenseException e) {
    //         logger.error("Can't read license file.", e);
    //      }

    String contextPath = application.getContextPath();
    //???APPLICATION
    ISystemInfoService systemInfoService = BeanManager.getBean("systemInfoService", ISystemInfoService.class);
    SystemInfoVo systemInfoVo = systemInfoService.getSystemInfo();
    systemInfoVo.setBaseUrl(config.getString("baseUrl") + contextPath);
    systemInfoVo.setHomePath(homePath);
    application.setAttribute(CoreConstants.APP_SYSTEMINFO, systemInfoVo); //servlet?
}

From source file:edu.cornell.mannlib.vitro.webapp.search.solr.SolrSetup.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    StartupStatus ss = StartupStatus.getBean(context);

    /* setup the http connection with the solr server */
    String solrServerUrlString = ConfigurationProperties.getBean(sce).getProperty("vitro.local.solr.url");
    if (solrServerUrlString == null) {
        ss.fatal(this, "Could not find vitro.local.solr.url in deploy.properties.  "
                + "Vitro application needs a URL of a solr server that it can use to index its data. "
                + "It should be something like http://localhost:${port}" + context.getContextPath() + "solr");
        return;//from ww  w  .jav a 2s  . co m
    }

    URL solrServerUrl = null;
    try {
        solrServerUrl = new URL(solrServerUrlString);
    } catch (MalformedURLException e) {
        ss.fatal(this,
                "Can't connect with the solr server. "
                        + "The value for vitro.local.solr.url in deploy.properties is not a valid URL: "
                        + solrServerUrlString);
        return;
    }

    try {
        CommonsHttpSolrServer server;
        boolean useMultiPartPost = true;
        //It would be nice to use the default binary handler but there seem to be library problems
        server = new CommonsHttpSolrServer(solrServerUrl, null, new XMLResponseParser(), useMultiPartPost);
        server.setSoTimeout(10000); // socket read timeout
        server.setConnectionTimeout(10000);
        server.setDefaultMaxConnectionsPerHost(100);
        server.setMaxTotalConnections(100);
        server.setMaxRetries(1);

        context.setAttribute(SOLR_SERVER, server);

        /* set up the individual to solr doc translation */
        OntModel jenaOntModel = ModelContext.getJenaOntModel(context);
        Model displayModel = ModelContext.getDisplayModel(context);

        /* try to get context attribute DocumentModifiers 
         * and use that as the start of the list of DocumentModifier 
         * objects.  This allows other ContextListeners to add to 
         * the basic set of DocumentModifiers. */
        @SuppressWarnings("unchecked")
        List<DocumentModifier> modifiers = (List<DocumentModifier>) context.getAttribute("DocumentModifiers");
        if (modifiers == null)
            modifiers = new ArrayList<DocumentModifier>();

        modifiers.add(new NameFields(RDFServiceUtils.getRDFServiceFactory(context)));
        modifiers.add(new NameBoost(1.2f));
        modifiers.add(new ThumbnailImageURL(jenaOntModel));

        /* try to get context attribute SearchIndexExcludes 
         * and use that as the start of the list of exclude 
         * objects.  This allows other ContextListeners to add to 
         * the basic set of SearchIndexExcludes . */
        @SuppressWarnings("unchecked")
        List<SearchIndexExcluder> excludes = (List<SearchIndexExcluder>) context
                .getAttribute("SearchIndexExcludes");
        if (excludes == null)
            excludes = new ArrayList<SearchIndexExcluder>();

        excludes.add(new ExcludeBasedOnNamespace(INDIVIDUAL_NS_EXCLUDES));
        excludes.add(new ExcludeBasedOnTypeNamespace(TYPE_NS_EXCLUDES));
        excludes.add(new ExcludeBasedOnType(OWL_TYPES_EXCLUDES));
        excludes.add(new ExcludeNonFlagVitro());
        excludes.add(new SyncingExcludeBasedOnType(displayModel));

        IndividualToSolrDocument indToSolrDoc = new IndividualToSolrDocument(excludes, modifiers);

        /* setup solr indexer */
        SolrIndexer solrIndexer = new SolrIndexer(server, indToSolrDoc);

        // This is where the builder gets the list of places to try to
        // get objects to index. It is filtered so that non-public text
        // does not get into the search index.
        WebappDaoFactory wadf = (WebappDaoFactory) context.getAttribute("webappDaoFactory");
        VitroFilters vf = VitroFilterUtils.getPublicFilter(context);
        wadf = new WebappDaoFactoryFiltering(wadf, vf);

        // make objects that will find additional URIs for context nodes etc
        List<StatementToURIsToUpdate> uriFinders = makeURIFinders(jenaOntModel, wadf.getIndividualDao());

        // Make the IndexBuilder
        IndexBuilder builder = new IndexBuilder(solrIndexer, wadf, uriFinders);
        // Save it to the servlet context so we can access it later in the webapp.
        context.setAttribute(IndexBuilder.class.getName(), builder);

        // set up listeners so search index builder is notified of changes to model
        ServletContext ctx = sce.getServletContext();
        SearchReindexingListener srl = new SearchReindexingListener(builder);
        ModelContext.registerListenerForChanges(ctx, srl);

        ss.info(this, "Setup of Solr index completed.");
    } catch (Throwable e) {
        ss.fatal(this, "could not setup local solr server", e);
    }

}

From source file:com.idega.core.accesscontrol.business.LoginBusinessBean.java

/**
 * The key is the login name and the value is
 * com.idega.core.accesscontrol.business.LoggedOnInfo
 *
 * @return Returns empty Map if no one is logged on
 *//*from  ww w.j  ava  2s. c o  m*/
public Map<Object, Object> getLoggedOnInfoMap(HttpSession session) {
    ServletContext sc = session.getServletContext();
    Map<Object, Object> loggedOnMap = (Map<Object, Object>) sc.getAttribute(_APPADDRESS_LOGGED_ON_LIST);
    if (loggedOnMap == null) {
        loggedOnMap = new TreeMap<Object, Object>();
        sc.setAttribute(_APPADDRESS_LOGGED_ON_LIST, loggedOnMap);
    }
    return loggedOnMap;
}

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  ww w . j a va 2s .co  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();
    }

}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/* w  w w  .j av  a 2  s.  c  o  m*/
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String type = "";
            String qs = "";
            byte[] data = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    executeMetadata(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DatabaseQueryServlet.GlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.ikon.servlet.admin.ConfigServlet.java

/**
 * List config/*from  w w  w  .  j a va 2s.  c  om*/
 */
private void list(String userId, String filter, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("list({}, {}, {}, {})", new Object[] { userId, filter, request, response });
    ServletContext sc = getServletContext();
    List<Config> list = ConfigDAO.findAll();

    for (Iterator<Config> it = list.iterator(); it.hasNext();) {
        Config cfg = it.next();

        if (Config.STRING.equals(cfg.getType())) {
            cfg.setType("String");
        } else if (Config.TEXT.equals(cfg.getType())) {
            cfg.setType("Text");
        } else if (Config.BOOLEAN.equals(cfg.getType())) {
            cfg.setType("Boolean");
        } else if (Config.INTEGER.equals(cfg.getType())) {
            cfg.setType("Integer");
        } else if (Config.LONG.equals(cfg.getType())) {
            cfg.setType("Long");
        } else if (Config.LIST.equals(cfg.getType())) {
            cfg.setType("List");
        } else if (Config.SELECT.equals(cfg.getType())) {
            cfg.setType("Select");
            ConfigStoredSelect stSelect = new Gson().fromJson(cfg.getValue(), ConfigStoredSelect.class);

            for (ConfigStoredOption stOption : stSelect.getOptions()) {
                if (stOption.isSelected()) {
                    cfg.setValue(stOption.getValue());
                }
            }
        } else if (Config.HIDDEN.equals(cfg.getType())) {
            it.remove();
        }

        if (!Config.HIDDEN.equals(cfg.getType()) && !cfg.getKey().contains(filter)) {
            it.remove();
        }
    }

    sc.setAttribute("configs", list);
    sc.setAttribute("filter", filter);
    sc.getRequestDispatcher("/admin/config_list.jsp").forward(request, response);
    log.debug("list: void");
}