Example usage for javax.servlet ServletContextEvent getServletContext

List of usage examples for javax.servlet ServletContextEvent getServletContext

Introduction

In this page you can find the example usage for javax.servlet ServletContextEvent getServletContext.

Prototype

public ServletContext getServletContext() 

Source Link

Document

Return the ServletContext that changed.

Usage

From source file:io.cettia.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override//from  ww w.j a  v  a2s  .  c o m
        public void on(final ServerSocket socket) {
            log.debug("socket.uri() is {}", socket.uri());
            socket.on("abort", new VoidAction() {
                @Override
                public void on() {
                    socket.close();
                }
            }).on("echo", new Action<Object>() {
                @Override
                public void on(Object data) {
                    socket.send("echo", data);
                }
            }).on("/reply/inbound", new Action<Reply<Map<String, Object>>>() {
                @Override
                public void on(Reply<Map<String, Object>> reply) {
                    Map<String, Object> data = reply.data();
                    switch ((String) data.get("type")) {
                    case "resolved":
                        reply.resolve(data.get("data"));
                        break;
                    case "rejected":
                        reply.reject(data.get("data"));
                        break;
                    }
                }
            }).on("/reply/outbound", new Action<Map<String, Object>>() {
                @Override
                public void on(Map<String, Object> data) {
                    switch ((String) data.get("type")) {
                    case "resolved":
                        socket.send("test", data.get("data"), new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    case "rejected":
                        socket.send("test", data.get("data"), null, new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    }
                }
            });
        }
    });
    final HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server);
    final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server);

    org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server();
    ServerConnector connector = new ServerConnector(jetty);
    jetty.addConnector(connector);
    connector.setPort(8000);
    ServletContextHandler handler = new ServletContextHandler();
    jetty.setHandler(handler);
    handler.addEventListener(new ServletContextListener() {
        @Override
        @SuppressWarnings("serial")
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                    Map<String, String[]> params = req.getParameterMap();
                    if (params.containsKey("heartbeat")) {
                        server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0]));
                    }
                    if (params.containsKey("_heartbeat")) {
                        server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0]));
                    }
                }
            });
            regSetup.addMapping("/setup");
            // For HTTP transport
            Servlet servlet = new AsityServlet().onhttp(httpTransportServer);
            ServletRegistration.Dynamic reg = context.addServlet(AsityServlet.class.getName(), servlet);
            reg.setAsyncSupported(true);
            reg.addMapping("/cettia");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
    // For WebSocket transport
    ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler);
    ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class, "/cettia")
            .configurator(new Configurator() {
                @Override
                public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
                    return endpointClass.cast(new AsityServerEndpoint().onwebsocket(wsTransportServer));
                }
            }).build();
    container.addEndpoint(config);

    jetty.start();

    CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node")
            .addArgument("./src/test/resources/runner").addArgument("--cettia.transports")
            .addArgument("websocket,httpstream,httplongpoll");
    DefaultExecutor executor = new DefaultExecutor();
    // The exit value of mocha is the number of failed tests.
    executor.execute(cmdLine);

    jetty.stop();
}

From source file:com.ning.jetty.core.listeners.SetupServer.java

@Override
public void contextInitialized(final ServletContextEvent event) {
    if (guiceModule != null) {
        // Overriden in subclasses?
        super.contextInitialized(event);
        return;/*from   ww  w . j  a  v  a2 s  . c  o m*/
    }

    final String moduleClassName = event.getServletContext().getInitParameter("guiceModuleClassName");
    if (StringUtils.isEmpty(moduleClassName)) {
        throw new IllegalStateException("Missing parameter for the base Guice module!");
    }

    try {
        final Class<?> moduleClass = Class.forName(moduleClassName);
        if (!Module.class.isAssignableFrom(moduleClass)) {
            throw new IllegalStateException(
                    String.format("%s exists but is not a Guice Module!", moduleClassName));
        }

        guiceModule = (Module) moduleClass.newInstance();
        log.info("Instantiated " + moduleClassName + " as the main guice module.");
    } catch (ClassNotFoundException cnfe) {
        throw new IllegalStateException(cnfe);
    } catch (InstantiationException ie) {
        throw new IllegalStateException(ie);
    } catch (IllegalAccessException iae) {
        throw new IllegalStateException(iae);
    }

    super.contextInitialized(event);
}

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

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();
    SearchIndexer searchIndexer = ApplicationUtils.instance().getSearchIndexer();

    try {/* ww  w  . j  a  v a  2  s.  com*/
        OntModel tboxAssertionsModel = ModelAccess.on(ctx).getOntModel(ModelNames.TBOX_ASSERTIONS);
        OntModel tboxInferencesModel = ModelAccess.on(ctx).getOntModel(ModelNames.TBOX_INFERENCES);
        OntModel tboxUnionModel = ModelAccess.on(ctx).getOntModel(ModelNames.TBOX_UNION);

        // set up simple reasoning for the ABox

        RDFService rdfService = ModelAccess.on(ctx).getRDFService();
        Dataset dataset = ModelAccess.on(ctx).getDataset();

        Model rebuildModel = dataset.getNamedModel(JENA_INF_MODEL_REBUILD);
        if (rebuildModel.contains(null, null, (RDFNode) null)) {
            log.info("Clearing obsolete data from inference rebuild model");
            rebuildModel.removeAll();
        }
        Model scratchModel = dataset.getNamedModel(JENA_INF_MODEL_SCRATCHPAD);
        if (scratchModel.contains(null, null, (RDFNode) null)) {
            log.info("Clearing obsolete data from inference scratchpad model");
            scratchModel.removeAll();
        }
        Model inferenceModel = dataset.getNamedModel(ABOX_INFERENCES);

        // the simple reasoner will register itself as a listener to the ABox assertions
        SimpleReasoner simpleReasoner = new SimpleReasoner(tboxUnionModel, rdfService, inferenceModel,
                rebuildModel, scratchModel, searchIndexer);
        sce.getServletContext().setAttribute(SimpleReasoner.class.getName(), simpleReasoner);

        StartupStatus ss = StartupStatus.getBean(ctx);
        List<ReasonerPlugin> pluginList = new ArrayList<ReasonerPlugin>();
        List<String> pluginClassnameList = this.readFileOfListeners(ctx);
        for (String classname : pluginClassnameList) {
            try {
                ReasonerPlugin plugin = (ReasonerPlugin) Class.forName(classname).getConstructors()[0]
                        .newInstance();
                plugin.setSimpleReasoner(simpleReasoner);
                if (!plugin.isConfigurationOnlyPlugin()) {
                    pluginList.add(plugin);
                    log.info("adding reasoner plugin " + plugin.getClass().getName());
                }
            } catch (Throwable t) {
                ss.info(this, "Could not instantiate reasoner plugin " + classname);
            }
        }
        simpleReasoner.setPluginList(pluginList);

        SimpleReasonerTBoxListener simpleReasonerTBoxListener = new SimpleReasonerTBoxListener(simpleReasoner);
        sce.getServletContext().setAttribute(SimpleReasonerTBoxListener.class.getName(),
                simpleReasonerTBoxListener);
        tboxAssertionsModel.register(simpleReasonerTBoxListener);
        tboxInferencesModel.register(simpleReasonerTBoxListener);

        RecomputeMode mode = getRecomputeRequired(ctx);
        if (RecomputeMode.FOREGROUND.equals(mode)) {
            log.info("ABox inference recompute required.");
            simpleReasoner.recompute();
        } else if (RecomputeMode.BACKGROUND.equals(mode)) {
            log.info("starting ABox inference recompute in a separate thread.");
            new VitroBackgroundThread(new ABoxRecomputer(simpleReasoner), "ABoxRecomputer").start();
        }

    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:org.red5.server.war.SubContextLoaderServlet.java

/**
 * Main entry point for the Red5 Server as a war
 *//*w w  w  .j a va 2  s.  com*/
// Notification that the web application is ready to process requests
@Override
public void contextInitialized(ServletContextEvent sce) {
    if (null != servletContext) {
        return;
    }
    System.setProperty("red5.deployment.type", "war");

    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    initRegistry(servletContext);

    long time = System.currentTimeMillis();

    logger.info("RED5 Server subcontext loader");
    logger.debug("Path: " + prefix);

    try {
        String[] configArray = servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM)
                .split("[,\\s]");
        logger.debug("Config location files: " + configArray.length);

        WebSettings settings = new WebSettings();
        settings.setPath(prefix);
        // prefix the config file paths so they can be found later
        String[] subConfigs = new String[configArray.length];
        for (int s = 0; s < configArray.length; s++) {
            String cfg = "file:/" + prefix + configArray[s];
            logger.debug("Sub config location: " + cfg);
            subConfigs[s] = cfg;
        }
        settings.setConfigs(subConfigs);
        settings.setWebAppKey(servletContext.getInitParameter("webAppRootKey"));

        // store this contexts settings in the registry
        IRemotableList remote = null;
        boolean firstReg = false;
        try {
            remote = (IRemotableList) Naming.lookup("rmi://localhost:" + rmiPort + "/subContextList");
        } catch (Exception e) {
            logger.warn("Lookup failed: " + e.getMessage());
        }
        if (remote == null) {
            remote = new RemotableList();
            firstReg = true;
        }
        logger.debug("Adding child web settings");
        remote.addChild(settings);
        logger.debug("Remote list size: " + remote.numChildren());
        if (firstReg) {
            Naming.bind("rmi://localhost:" + rmiPort + "/subContextList", remote);
        } else {
            Naming.rebind("rmi://localhost:" + rmiPort + "/subContextList", remote);
        }

    } catch (Throwable t) {
        logger.error(t);
    }

    long startupIn = System.currentTimeMillis() - time;
    logger.info("Startup done in: " + startupIn + " ms");

}

From source file:org.jwatch.listener.settings.SettingsLoaderListener.java

public void contextInitialized(ServletContextEvent event) {
    try {//  w  w w  .java2 s .  c  om
        log.info("Starting Settings Load...");
        long start = Calendar.getInstance().getTimeInMillis();

        ServletContext sc = event.getServletContext();
        if (sc != null) {
            String sMaxEvents = sc.getInitParameter("maxevents");
            int maxEvents = NumberUtils.toInt(sMaxEvents, EventService.DEFAULT_MAX_EVENT_LIST_SIZE);
            sc.setAttribute("maxevents", maxEvents); // expose to other servlets
            EventService.setMaxEventListSize(maxEvents);

            String sMaxShowEvents = sc.getInitParameter("maxshowevents");
            int maxShowEvents = NumberUtils.toInt(sMaxShowEvents,
                    EventService.DEFAULT_MAX_SHOW_EVENT_LIST_SIZE);
            sc.setAttribute("maxshowevents", maxShowEvents); // expose to other servlets
            EventService.setMaxShowEventListSize(maxShowEvents);
        }

        // load config file and instances
        QuartzInstanceService.initQuartzInstanceMap();

        SettingsUtil.loadProperties();

        // connect/start DB
        connectionUtil = new ConnectionUtil(SettingsUtil.getDBFilePath());
        StringBuffer jwatchLog = new StringBuffer();
        jwatchLog.append("CREATE TEXT TABLE IF NOT EXISTS JWATCHLOG (").append("id INTEGER IDENTITY,")
                .append("CALENDARNAME VARCHAR(256),").append("JOBGROUP VARCHAR(256),")
                .append("JOBNAME VARCHAR(256),").append("SCHEDULERNAME VARCHAR(256),")
                .append("TRIGGERGROUP VARCHAR(256),").append("TRIGGERNAME VARCHAR(256),")
                .append("FIRETIME DATE,").append("NEXTFIRETIME  DATE,").append("PREVIOUSFIRETIME  DATE,")
                .append("SCHEDULEDFIRETIME  DATE,").append("RECOVERING BOOLEAN,").append("JOBRUNTIME BIGINT, ")
                .append("REFIRECOUNT INTEGER, ").append("SCHEDULERID VARCHAR(256),")
                .append("QUARTZINSTANCEID VARCHAR(256)").append(")");
        connectionUtil.update(jwatchLog.toString());

        long end = Calendar.getInstance().getTimeInMillis();
        log.info("Settings startup completed in: " + (end - start) + " ms");
    } catch (Throwable t) {
        log.error("Failed to initialize Settings.", t);
    }
}

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  w  ww  . j  a  va 2 s. c  o  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:org.exoplatform.application.gadget.GadgetRegister.java

/**
 * Initializes the listener and each time a new gadget application war is deployed the gadgets
 * are added into the JCR node by GadgetRegistryService
 * @throws Exception when can't parse xml file
 *///ww w . j a v  a  2  s .c  o  m
public void contextInitialized(ServletContextEvent event) {
    try {
        ServletContext servletContext = event.getServletContext();
        String containerName = servletContext.getInitParameter("portalContainerName");
        ExoContainer pcontainer;
        if (containerName != null)
            pcontainer = ExoContainerContext.getContainerByName(containerName);
        else
            pcontainer = ExoContainerContext.getCurrentContainer();
        if (pcontainer == null)
            pcontainer = ExoContainerContext.getTopContainer();
        SourceStorage sourceStorage = (SourceStorage) pcontainer
                .getComponentInstanceOfType(SourceStorage.class);
        GadgetRegistryService gadgetService = (GadgetRegistryService) pcontainer
                .getComponentInstanceOfType(GadgetRegistryService.class);
        String confLocation = "/WEB-INF/gadget.xml";
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputStream in = event.getServletContext().getResourceAsStream(confLocation);
        Document docXML = db.parse(in);
        NodeList nodeList = docXML.getElementsByTagName("gadget");
        String gadgetName = null, address = null;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element gadgetElement = (Element) nodeList.item(i);
            gadgetName = gadgetElement.getAttribute("name");
            if (gadgetService.getGadget(gadgetName) != null)
                continue;
            try {
                NodeList nodeChild = gadgetElement.getChildNodes();
                for (int j = 0; j < nodeChild.getLength(); j++) {
                    Node node = nodeChild.item(j);
                    address = node.getTextContent();
                    if (node.getNodeName().equals("path")) {
                        InputStream sourceIs = event.getServletContext().getResourceAsStream(address);
                        String realPath = event.getServletContext().getRealPath(address);
                        File sourceFile = new File(realPath);
                        File homeDir = sourceFile.getParentFile();
                        String fileName = sourceFile.getName();
                        //Saves source of gadget
                        Source source = new Source(fileName, getMimeType(event.getServletContext(), fileName),
                                "UTF-8");
                        source.setStreamContent(sourceIs);
                        source.setLastModified(Calendar.getInstance());
                        String homeName = homeDir.getName();
                        sourceStorage.saveSource(homeName, source);
                        //Saves gadget
                        ModulePrefs prefs = GadgetApplication.getModulePreferences(
                                Uri.parse("http://www.exoplatform.org"), source.getTextContent());
                        Gadget gadget = new Gadget();
                        gadget.setName(gadgetName);
                        gadget.setUrl(sourceStorage.getSourceURI(homeName + "/" + fileName));
                        gadget.setTitle(getGadgetTitle(prefs, gadget.getName()));
                        gadget.setDescription(prefs.getDescription());
                        gadget.setThumbnail(prefs.getThumbnail().toString());
                        gadget.setReferenceUrl(prefs.getTitleUrl().toString());
                        gadget.setLocal(true);
                        gadgetService.saveGadget(gadget);
                        //Saves source's included
                        //              int dotIdx = address.lastIndexOf('.'); 
                        //              if(dotIdx < 0) continue;
                        //              String dirPath = address.substring(0, dotIdx);
                        if (homeDir.exists() && homeDir.isDirectory()) {
                            File[] files = homeDir.listFiles();
                            for (int k = 0; k < files.length; k++) {
                                saveTree(files[k], homeName, event.getServletContext(), sourceStorage);
                            }
                        }
                    } else if (node.getNodeName().equals("url")) {
                        URL urlObj = new URL(address);
                        URLConnection conn = urlObj.openConnection();
                        InputStream is = conn.getInputStream();
                        String source = IOUtils.toString(is, "UTF-8");
                        ModulePrefs prefs = GadgetApplication.getModulePreferences(Uri.parse(address), source);
                        Gadget gadget = new Gadget();
                        gadget.setName(gadgetName);
                        gadget.setUrl(address);
                        gadget.setTitle(getGadgetTitle(prefs, gadget.getName()));
                        gadget.setDescription(prefs.getDescription());
                        gadget.setThumbnail(prefs.getThumbnail().toString());
                        gadget.setReferenceUrl(prefs.getTitleUrl().toString());
                        gadget.setLocal(false);
                        gadgetService.saveGadget(gadget);
                    }
                }
            } catch (Exception ex) {
                log.warn("Can not register the gadget: '" + gadgetName + "' ");
            }
        }
    } catch (Exception ex) {
        log.error("Error while deploying a gadget", ex);
    }
}

From source file:be.fedict.eid.dss.webapp.StartupServletContextListener.java

private void initProtocolServices(ServletContextEvent event) {

    /*//from ww w .  jav  a  2  s. co  m
     * We once load the protocol services so we don't have to iterate over
     * all protocol descriptor files upon each DSS request.
     */
    ServletContext servletContext = event.getServletContext();
    Map<String, String> protocolServiceClassNames = this.servicesManager.getProtocolServiceClassNames();
    servletContext.setAttribute(PROTOCOL_SERVICES_CONTEXT_ATTRIBUTE, protocolServiceClassNames);
}

From source file:net.tirasa.connid.bundles.soap.wssample.DefaultContentLoader.java

@Override
public void contextInitialized(final ServletContextEvent sce) {
    final WebApplicationContext springContext = WebApplicationContextUtils
            .getWebApplicationContext(sce.getServletContext());

    if (springContext == null) {
        LOG.error("Invalid Spring context");
        return;//from   w w  w .j  a v a2 s .co m
    }

    final DataSource dataSource = springContext.getBean(DataSource.class);
    localDataSource = dataSource;

    final DefaultDataTypeFactory dbUnitDataTypeFactory = (DefaultDataTypeFactory) springContext
            .getBean("dbUnitDataTypeFactory");

    final Connection conn = DataSourceUtils.getConnection(dataSource);

    // create schema
    final StringBuilder statement = new StringBuilder();

    final InputStream dbschema = DefaultContentLoader.class.getResourceAsStream(DBSCHEMA);

    final BufferedReader buff = new BufferedReader(new InputStreamReader(dbschema));

    String line = null;
    try {
        while ((line = buff.readLine()) != null) {
            if (!line.isEmpty() && !line.startsWith("--")) {
                statement.append(line);
            }
        }
    } catch (IOException e) {
        LOG.error("Error reading file " + DBSCHEMA, e);
        return;
    }

    Statement st = null;
    try {
        st = conn.createStatement();
        st.execute(statement.toString());
    } catch (SQLException e) {
        LOG.error("Error creating schema:\n" + statement.toString(), e);
        return;
    } finally {
        try {
            st.close();
        } catch (Throwable t) {
            // ignore exception
        }
    }

    try {
        IDatabaseConnection dbUnitConn = new DatabaseConnection(conn);

        final DatabaseConfig config = dbUnitConn.getConfig();
        config.setProperty("http://www.dbunit.org/properties/datatypeFactory", dbUnitDataTypeFactory);

        boolean existingData = false;
        final IDataSet existingDataSet = dbUnitConn.createDataSet();
        for (final ITableIterator itor = existingDataSet.iterator(); itor.next() && !existingData;) {
            existingData = (itor.getTable().getRowCount() > 0);
        }

        final FlatXmlDataSetBuilder dataSetBuilder = new FlatXmlDataSetBuilder();
        dataSetBuilder.setColumnSensing(true);
        final IDataSet dataSet = dataSetBuilder.build(getClass().getResourceAsStream("/content.xml"));
        DatabaseOperation.REFRESH.execute(dbUnitConn, dataSet);
    } catch (Throwable t) {
        LOG.error("Error loding default content", t);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}

From source file:com.sun.socialsite.web.listeners.ContextListener.java

/**
 * Responds to context initialization event by processing context
 * parameters for easy access by the rest of the application.
 *///from  www . j  a  v a 2 s .  c  o  m
public void contextInitialized(ServletContextEvent sce) {

    log.info("SocialSite Initializing ... ");

    // Keep a reference to ServletContext object
    servletContext = sce.getServletContext();

    // Set a "context.realpath" property, allowing others to find our filesystem basedir
    Config.setProperty("context.realpath", sce.getServletContext().getRealPath("/"));

    try {
        URL baseUrl = new URL(Config.getProperty("socialsite.base.url"));
        Config.setProperty("context.contextpath", baseUrl.getPath());
        log.debug("Config[context.contextpath]=" + Config.getProperty("context.contextpath"));
    } catch (MalformedURLException ex) {
        String msg = String.format("Could not decode socialsite.base.url[%s]",
                Config.getProperty("socialsite.base.url"));
        log.error(msg, ex);
    }

    // Log system information (if enabled)
    // TODO: move this down to DEBUG level
    if (log.isInfoEnabled()) {
        logClassLoaderInfo(ClassLoader.getSystemClassLoader(), "systemClassLoader");
        logClassLoaderInfo(Thread.currentThread().getContextClassLoader(), "contextClassLoader");
    }

    // Set a "context.contextpath" property, allowing others to find our webapp base
    // Now prepare the core services of the app so we can bootstrap
    try {
        Startup.prepare();
    } catch (StartupException ex) {
        log.fatal("SocialSite startup failed during app preparation", ex);
        return;
    }

    // If preparation failed or is incomplete then we are done
    if (!Startup.isPrepared()) {
        log.info("SocialSite startup requires interaction from user to continue");
        return;
    }

    try {
        Factory.bootstrap();
        Factory.getSocialSite().initialize();
    } catch (BootstrapException ex) {
        log.fatal("Factory bootstrap failed", ex);
    } catch (SocialSiteException ex) {
        log.fatal("Factory initialization failed", ex);
    }

    log.info("SocialSite Initialization Complete");
}