Example usage for javax.servlet ServletContext getRealPath

List of usage examples for javax.servlet ServletContext getRealPath

Introduction

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

Prototype

public String getRealPath(String path);

Source Link

Document

Gets the real path corresponding to the given virtual path.

Usage

From source file:Bean.CAT.TerminosBean.java

public void serializarTest() throws IOException {

       //serializacin
       ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
               .getContext();//  w  w  w  .  java2  s . co  m
       String realPath = (String) servletContext.getRealPath("/"); // Sustituye "/" por el directorio ej: "/upload"

       //serializacin
       try (ObjectOutputStream salida = new ObjectOutputStream(
               new FileOutputStream(realPath + "/Tests/" + test.getIdTest() + ".obj"))) {
           salida.writeObject(terminosTest);
           System.out.println(" se serializ");

       }

   }

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

public static int loadFormAdapters(ServletContext servletContext) throws Exception {

    int adapterCount = 0;

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> formConstructors = new HashMap<String, Constructor>();

    // create a JSON Array object which will hold json for all of the available security adapters
    JSONArray jsonAdapters = new JSONArray();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/forms/"));

    // create a filter for finding .formadapter.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".formadapter.xml");
        }/*from   w  w  w . ja  va  2 s  .  c om*/
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/formAdapter.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // read the xml into a string
        String xml = Strings.getString(xmlFile);

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonFormAdapter = org.json.XML.toJSONObject(xml).getJSONObject("formAdapter");

        // get the type from the json
        String type = jsonFormAdapter.getString("type");
        // get the class name from the json
        String className = jsonFormAdapter.getString("class");
        // get the class 
        Class classClass = Class.forName(className);
        // check the class extends com.rapid.security.SecurityAdapter
        if (!Classes.extendsClass(classClass, com.rapid.forms.FormAdapter.class))
            throw new Exception(type + " form adapter class " + classClass.getCanonicalName()
                    + " must extend com.rapid.forms.FormsAdapter");
        // check this type is unique
        if (formConstructors.get(type) != null)
            throw new Exception(type + " form adapter already loaded. Type names must be unique.");
        // add to constructors hashmap referenced by type
        formConstructors.put(type, classClass.getConstructor(ServletContext.class, Application.class));

        // add to our collection
        jsonAdapters.put(jsonFormAdapter);

        // increment the count
        adapterCount++;

    }

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonFormAdapters", jsonAdapters);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("formConstructors", formConstructors);

    _logger.info(adapterCount + " form adapters loaded in .formAdapter.xml files");

    return adapterCount;

}

From source file:com.siacra.beans.GrupoBean.java

public void handleFileUpload(FileUploadEvent event) {
    try {// www  .  j  a v a  2s.  com
        //            Asignatura asignatura = getAsignaturaService().getAsignaturaById(getIdAsignatura());
        /* Obtenemos el path */
        ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String path = context.getRealPath("/WEB-INF/files/");
        /* Inicializamos el destino y el origen */
        File targetFolder = new File(path);
        InputStream inputStream = event.getFile().getInputstream();
        /* Escribimos en el destino, leyendo la data del origen */

        OutputStream out = new FileOutputStream(new File(targetFolder, event.getFile().getFileName()));
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        /* Cerramos los archivos */
        inputStream.close();
        out.flush();
        out.close();

        RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_INFO,
                "Informacion", "El archivo fue cargado correctamente"));

        archivoXlsx(path, event);

    } catch (IOException e) {
        RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_FATAL,
                "Informacion", "El archivo no pudo ser cargado correctamente"));
        System.out.println(e.getMessage());
    }
}

From source file:org.eumetsat.usd.gcp.server.data.NetCDFCalibrationDataManager.java

/**
 * Constructor./*  ww  w . j  a v a 2s .com*/
 * 
 * @param servletContext
 *            servlet context.
 * @param csvFilePath
 *            path to the CSV file.
 * @param configManager
 *            configuration manager.
 */
@Inject
public NetCDFCalibrationDataManager(final ServletContext servletContext, @CsvFilePath final String csvFilePath,
        final ConfigManager configManager) {
    this.configManager = configManager;

    // set path to CSV file.
    this.csvFilePath = servletContext.getRealPath(File.separator + csvFilePath);
}

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

public static int loadSecurityAdapters(ServletContext servletContext) throws Exception {

    int adapterCount = 0;

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> securityConstructors = new HashMap<String, Constructor>();

    // create a JSON Array object which will hold json for all of the available security adapters
    JSONArray jsonSecurityAdapters = new JSONArray();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/security/"));

    // create a filter for finding .securityadapter.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".securityadapter.xml");
        }/*  w ww .j  ava  2  s .c  o  m*/
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/securityAdapter.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // read the xml into a string
        String xml = Strings.getString(xmlFile);

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonSecurityAdapter = org.json.XML.toJSONObject(xml).getJSONObject("securityAdapter");

        // get the type from the json
        String type = jsonSecurityAdapter.getString("type");
        // get the class name from the json
        String className = jsonSecurityAdapter.getString("class");
        // get the class 
        Class classClass = Class.forName(className);
        // check the class extends com.rapid.security.SecurityAdapter
        if (!Classes.extendsClass(classClass, com.rapid.security.SecurityAdapter.class))
            throw new Exception(type + " security adapter class " + classClass.getCanonicalName()
                    + " must extend com.rapid.security.SecurityAdapter");
        // check this type is unique
        if (securityConstructors.get(type) != null)
            throw new Exception(type + " security adapter already loaded. Type names must be unique.");
        // add to constructors hashmap referenced by type
        securityConstructors.put(type, classClass.getConstructor(ServletContext.class, Application.class));

        // add to our collection
        jsonSecurityAdapters.put(jsonSecurityAdapter);

        // increment the count
        adapterCount++;

    }

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonSecurityAdapters", jsonSecurityAdapters);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("securityConstructors", securityConstructors);

    _logger.info(adapterCount + " security adapters loaded in .securityAdapter.xml files");

    return adapterCount;

}

From source file:managedBeans.facturacion.ListadoFacturaMB.java

private void generarFactura(String ruta) throws IOException, JRException {
    FacDocumentosmaster documento = documentosmasterFacade.buscarBySedeAndDocumentoAndNum(sedeActual,
            documentoSeleccionado.getFacDocumentosmasterPK().getCfgdocumentoidDoc(),
            documentoSeleccionado.getFacDocumentosmasterPK().getNumDocumento());
    byte[] bites = sedeActual.getLogo();
    if (bites != null) {
        bites = sedeActual.getCfgempresaidEmpresa().getLogo();
    }//from www  . ja  va 2 s  .co m
    List<FacturaReporte> facturas = new ArrayList();
    FacturaReporte facturaReporte = new FacturaReporte();
    //        facturaReporte.setNumFactura(documento.getFacDocumentosmasterPK().getNumDocumento());
    facturaReporte.setNumFac(documento.determinarNumFactura());
    facturaReporte.setDescuento(documento.getDescuento());
    facturaReporte.setSubtotal(documento.getSubtotal());
    facturaReporte.setTotalFactura(documento.getTotal());
    facturaReporte.setDetalle(crearListadoDetalle(documentodetalleFacade.buscarByDocumentoMaster(documento)));
    facturaReporte
            .setImpuesto(crearListadoImpuesto(documentoimpuestoFacade.buscarByDocumentoMaster(documento)));
    facturaReporte.setPago(crearListadoPago(docuementopagoFacade.buscarByDocumentoMaster(documento)));
    facturas.add(facturaReporte);
    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(facturas);
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpServletResponse httpServletResponse = (HttpServletResponse) facesContext.getExternalContext()
            .getResponse();
    try (ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream()) {
        httpServletResponse.setContentType("application/pdf");
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String rutaReportes = servletContext.getRealPath("/facturacion/reportes/");//ubicacion para los subreportes
        Map<String, Object> parametros = new HashMap<>();
        if (bites != null) {
            InputStream logo = new ByteArrayInputStream(bites);
            parametros.put("logo", logo);
        }
        CfgEmpresa empresa = sedeActual.getCfgempresaidEmpresa();
        switch (documento.getCfgDocumento().getCfgAplicaciondocumentoIdaplicacion().getCodaplicacion()) {
        case "1":
            parametros.put("title", "VENTA No");
            parametros.put("nit", empresa.getCfgTipodocempresaId().getDocumentoempresa() + " "
                    + sedeActual.getNumDocumento() + " " + empresa.getCfgTipoempresaId().getDescripcion());
            parametros.put("resdian", documento.getCfgDocumento().getResDian());
            break;
        case "6":
            parametros.put("title", "VENTA No");
            break;
        }
        parametros.put("empresa", empresa.getNomEmpresa() + " - " + sedeActual.getNomSede());
        parametros.put("direccion", sedeActual.getDireccion());
        String telefono = sedeActual.getTel1();
        if (sedeActual.getTel2() != null && !sedeActual.getTel2().isEmpty()) {
            telefono = telefono + "-".concat(sedeActual.getTel2());
        }
        parametros.put("telefono", telefono);
        parametros.put("cliente", documento.getCfgclienteidCliente().nombreCompleto());
        if (tipoImpresion != 2) { //no es impresion carta
            parametros.put("identificacionCliente",
                    documento.getCfgclienteidCliente().getCfgTipoidentificacionId().getAbreviatura() + " "
                            + documento.getCfgclienteidCliente().getNumDoc());
        } else {
            parametros.put("identificacionCliente", documento.getCfgclienteidCliente().getNumDoc());
            parametros.put("tipoDoc",
                    documento.getCfgclienteidCliente().getCfgTipoidentificacionId().getAbreviatura());
        }
        parametros.put("fecha", documento.getFecCrea());
        parametros.put("usuario", usuarioActual.nombreCompleto());
        parametros.put("ubicacion", sedeActual.getCfgMunicipio().getNomMunicipio() + " "
                + sedeActual.getCfgMunicipio().getCfgDepartamento().getNomDepartamento());
        parametros.put("identificacionUsuario", usuarioActual.getNumDoc());
        parametros.put("SUBREPORT_DIR", rutaReportes);
        parametros.put("observacion", documento.getObservaciones());
        parametros.put("vendedor", documento.getSegusuarioidUsuario1().nombreCompleto());
        if (documento.getFaccajaidCaja() != null) {
            parametros.put("caja", documento.getFaccajaidCaja().getNomCaja());
        } else {
            parametros.put("caja", null);
        }
        JasperPrint jasperPrint = JasperFillManager.fillReport(ruta, parametros, beanCollectionDataSource);
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }
}

From source file:org.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java

/**
 * This method will drive the call to WsGen to generate a WSDL file for
 * applications deployed without WSDL. We will then read this file in from
 * disk and create a Definition. After we are done with the file we will
 * remove it from disk.  This method accepts a CatalogManager as a parameter
 * for the eventual use in by an XMLSchemaCollection.
 *//*from   w  w  w .  ja  va2s. c o m*/
public void generateWsdl(String className, String bindingType, JAXWSCatalogManager catalogManager)
        throws WebServiceException {

    if (this.axisConfiguration == null) {
        this.axisConfiguration = axisService.getAxisConfiguration();
    }
    File tempFile = (File) axisConfiguration.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR);
    if (tempFile == null) {
        tempFile = new File(getProperty_doPriv("java.io.tmpdir"), "_axis2");
    }

    Parameter servletConfigParam = axisConfiguration.getParameter(HTTPConstants.HTTP_SERVLETCONFIG);

    String webBase = null;
    if (servletConfigParam != null) {
        Object obj = servletConfigParam.getValue();
        ServletContext servletContext;

        if (obj instanceof ServletConfig) {
            ServletConfig servletConfig = (ServletConfig) obj;
            servletContext = servletConfig.getServletContext();
            webBase = servletContext.getRealPath("/WEB-INF");
        }
    }

    if (classPath == null) {
        this.classPath = getDefaultClasspath(webBase);
    }
    if (log.isDebugEnabled()) {
        log.debug("For implementation class " + className + " WsGen classpath: " + classPath);
    }
    String localOutputDirectory = tempFile.getAbsolutePath() + className + "_" + axisService.getName();
    if (log.isDebugEnabled()) {
        log.debug("Output directory for generated WSDL file: " + localOutputDirectory);
    }
    try {

        if (log.isDebugEnabled()) {
            log.debug("Generating new WSDL Definition");
        }

        createOutputDirectory(localOutputDirectory);
        Class clazz;
        try {
            // Try the one in JDK16
            clazz = Class.forName("com.sun.tools.internal.ws.spi.WSToolsObjectFactory");
        } catch (Throwable t) {
            // Look for the RI
            clazz = Class.forName("com.sun.tools.ws.spi.WSToolsObjectFactory");
        }
        Method m1 = clazz.getMethod("newInstance", new Class[] {});
        Object factory = m1.invoke(new Object[] {});
        String[] arguments = getWsGenArguments(className, bindingType, localOutputDirectory);
        OutputStream os = new ByteArrayOutputStream();
        Method m2 = clazz.getMethod("wsgen", new Class[] { OutputStream.class, String[].class });
        m2.invoke(factory, os, arguments);
        os.close();
        wsdlDefMap = readInWSDL(localOutputDirectory);
        if (wsdlDefMap.isEmpty()) {
            throw new Exception(
                    "A WSDL Definition could not be generated for " + "the implementation class: " + className);
        }
        docMap = readInSchema(localOutputDirectory, catalogManager);
    } catch (Throwable t) {
        String msg = "Error occurred generating WSDL file for Web service implementation class " + "{"
                + className + "}";
        log.error(msg, t);
        throw new WebServiceException(msg, t);
    }
}

From source file:com.alfaariss.oa.OAContextListener.java

/**
 * Starts the engine before all servlets are initialized.
 * /*from  w w  w.j av  a  2 s  .  c  o m*/
 * Searches for the properties needed for the configuration in:
 * <code>[Servlet context dir]/WEB-INF/[PROPERTIES_FILENAME]</code>
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
@Override
public void contextInitialized(ServletContextEvent oServletContextEvent) {
    Properties pConfig = new Properties();
    try {
        _logger.info("Starting Asimba");

        Package pCurrent = OAContextListener.class.getPackage();

        String sSpecVersion = pCurrent.getSpecificationVersion();
        if (sSpecVersion != null)
            _logger.info("Specification-Version: " + sSpecVersion);

        String sImplVersion = pCurrent.getImplementationVersion();
        if (sImplVersion != null)
            _logger.info("Implementation-Version: " + sImplVersion);

        ServletContext oServletContext = oServletContextEvent.getServletContext();

        Enumeration enumContextAttribs = oServletContext.getInitParameterNames();
        while (enumContextAttribs.hasMoreElements()) {
            String sName = (String) enumContextAttribs.nextElement();
            pConfig.put(sName, oServletContext.getInitParameter(sName));
        }

        if (pConfig.size() > 0) {
            _logger.info("Using configuration items found in servlet context: " + pConfig);
        }

        // Add MountingPoint to PathTranslator
        PathTranslator.getInstance().addKey(MP_WEBAPP_ROOT, oServletContext.getRealPath(""));

        // Try to see whether there is a system property with the location of the properties file:
        String sPropertiesFilename = System.getProperty(PROPERTIES_FILENAME_PROPERTY);
        if (null != sPropertiesFilename && !"".equals(sPropertiesFilename)) {
            File fConfig = new File(sPropertiesFilename);
            if (fConfig.exists()) {
                _logger.info("Reading Asimba properties from " + fConfig.getAbsolutePath());
                pConfig.putAll(getProperties(fConfig));
            }
        }

        String sWebInf = oServletContext.getRealPath("WEB-INF");
        if (sWebInf != null) {
            _logger.info("Cannot find path in ServletContext for WEB-INF");
            StringBuffer sbConfigFile = new StringBuffer(sWebInf);
            if (!sbConfigFile.toString().endsWith(File.separator))
                sbConfigFile.append(File.separator);
            sbConfigFile.append(PROPERTIES_FILENAME);

            File fConfig = new File(sbConfigFile.toString());
            if (fConfig.exists()) {
                _logger.info("Updating configuration items with the items in file: " + fConfig.toString());
                pConfig.putAll(getProperties(fConfig));
            } else {
                _logger.info("No optional configuration properties (" + PROPERTIES_FILENAME
                        + ") file found at: " + fConfig.toString());
            }
        }
        //Search for PROPERTIES_FILENAME file in servlet context classloader classpath 
        //it looks first at this location: ./<context>/web-inf/classes/[PROPERTIES_FILENAME]
        //if previous location didn't contain PROPERTIES_FILENAME then checking: 
        //./tomcat/common/classes/PROPERTIES_FILENAME
        URL urlProperties = oServletContext.getClass().getClassLoader().getResource(PROPERTIES_FILENAME);
        if (urlProperties != null) {
            String sProperties = urlProperties.getFile();
            _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in classpath: " + sProperties);
            File fProperties = new File(sProperties);
            if (fProperties != null && fProperties.exists()) {
                _logger.info("Updating configuration items with the items in file: "
                        + fProperties.getAbsolutePath());
                pConfig.putAll(getProperties(fProperties));
            } else
                _logger.info("Could not resolve: " + fProperties.getAbsolutePath());
        } else
            _logger.info("No optional '" + PROPERTIES_FILENAME
                    + "' configuration file found in servlet context classpath");

        if (!pConfig.containsKey("configuration.handler.filename")) {
            StringBuffer sbOAConfigFile = new StringBuffer(sWebInf);
            if (!sbOAConfigFile.toString().endsWith(File.separator))
                sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("conf");
            sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("asimba.xml");
            File fOAConfig = new File(sbOAConfigFile.toString());
            if (fOAConfig.exists()) {
                pConfig.put("configuration.handler.filename", sbOAConfigFile.toString());
                _logger.info(
                        "Setting 'configuration.handler.filename' configuration property with configuration file found at: "
                                + fOAConfig.toString());
            }
        }

        _oEngineLauncher.start(pConfig);

        _logger.info("Started Engine with OAContextListener");
    } catch (Exception e) {
        _logger.error("Can't start Engine with OAContextListener", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();
    }

}

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

/**
 * Initialization.//from w ww.  j  av a 2  s  .com
 */
@SuppressWarnings("cast")
public void init() {
    log.info("Loading tomcat virtual host");

    if (webappFolder != null) {
        //check for match with base webapp root
        if (webappFolder.equals(webappRoot)) {
            log.error("Web application root cannot be the same as base");
            return;
        }
    }

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();

    //ensure we have a host
    if (host == null) {
        host = createHost();
    }

    host.setParentClassLoader(classloader);

    String propertyPrefix = name;
    if (domain != null) {
        propertyPrefix += '_' + domain.replace('.', '_');
    }
    log.debug("Generating name (for props) {}", propertyPrefix);
    System.setProperty(propertyPrefix + ".webapp.root", webappRoot);

    log.info("Virtual host root: {}", webappRoot);

    log.info("Virtual host context id: {}", defaultApplicationContextId);

    // Root applications directory
    File appDirBase = new File(webappRoot);
    // Subdirs of root apps dir
    File[] dirs = appDirBase.listFiles(new TomcatLoader.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);
            Context ctx = null;
            if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
                log.debug("Adding ROOT context");
                ctx = addContext("/", webappContextDir);
            } else {
                log.debug("Adding context from directory scan: {}", dirName);
                ctx = addContext(dirName, webappContextDir);
            }
            log.debug("Context: {}", ctx);
            webappContextDir = null;
        }
    }
    appDirBase = null;
    dirs = null;

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

    engine.addChild(host);

    // Start server
    try {
        log.info("Starting Tomcat virtual host");

        //may not have to do this step for every host
        LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext));

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

                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 {
                    Loader cldr = ctx.getLoader();
                    log.debug("Loader type: {}", cldr.getClass().getName());
                    ClassLoader webClassLoader = cldr.getClassLoader();
                    log.debug("Webapp classloader: {}", webClassLoader);
                    //create a spring web application context
                    XmlWebApplicationContext appctx = new XmlWebApplicationContext();
                    appctx.setClassLoader(webClassLoader);
                    appctx.setConfigLocations(new String[] { "/WEB-INF/red5-*.xml" });
                    //check for red5 context bean
                    if (applicationContext.containsBean(defaultApplicationContextId)) {
                        appctx.setParent(
                                (ApplicationContext) applicationContext.getBean(defaultApplicationContextId));
                    } else {
                        log.warn("{} bean was not found in context: {}", defaultApplicationContextId,
                                applicationContext.getDisplayName());
                        //lookup context loader and attempt to get what we need from it
                        if (applicationContext.containsBean("context.loader")) {
                            ContextLoader contextLoader = (ContextLoader) applicationContext
                                    .getBean("context.loader");
                            appctx.setParent(contextLoader.getContext(defaultApplicationContextId));
                        } else {
                            log.debug("Context loader was not found, trying JMX");
                            MBeanServer mbs = JMXFactory.getMBeanServer();
                            //get the ContextLoader from jmx
                            ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader");
                            ContextLoaderMBean proxy = null;
                            if (mbs.isRegistered(oName)) {
                                proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs,
                                        oName, ContextLoaderMBean.class, true);
                                log.debug("Context loader was found");
                                appctx.setParent(proxy.getContext(defaultApplicationContextId));
                            } else {
                                log.warn("Context loader was not found");
                            }
                        }
                    }
                    if (log.isDebugEnabled()) {
                        if (appctx.getParent() != null) {
                            log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
                        }
                    }
                    //
                    appctx.setServletContext(servletContext);
                    //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);
                    appctx.refresh();
                } catch (Throwable t) {
                    log.error("Error setting up context: {}", servletContext.getContextPath(), t);
                    if (log.isDebugEnabled()) {
                        t.printStackTrace();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Error loading Tomcat virtual host", e);
    }

}

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

public static int loadConnectionAdapters(ServletContext servletContext) throws Exception {

    int adapterCount = 0;

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> connectionConstructors = new HashMap<String, Constructor>();

    // create an array list of json objects which we will sort later according to the order
    ArrayList<JSONObject> connectionAdapters = new ArrayList<JSONObject>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/database/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".connectionadapter.xml");
        }//from  w ww .  j  a v  a  2s  . c  om
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/connectionAdapter.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // read the xml into a string
        String xml = Strings.getString(xmlFile);

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonConnectionAdapter = org.json.XML.toJSONObject(xml).getJSONObject("connectionAdapter");

        // get the class name from the json
        String className = jsonConnectionAdapter.getString("class");
        // get the class 
        Class classClass = Class.forName(className);
        // check the class extends com.rapid.data.ConnectionAdapter
        if (!Classes.extendsClass(classClass, com.rapid.data.ConnectionAdapter.class))
            throw new Exception(
                    classClass.getCanonicalName() + " must extend com.rapid.data.ConnectionAdapter");
        // check this class is unique
        if (connectionConstructors.get(className) != null)
            throw new Exception(className + " connection adapter already loaded.");
        // add to constructors hashmap referenced by type
        connectionConstructors.put(className, classClass.getConstructor(ServletContext.class, String.class,
                String.class, String.class, String.class));

        // add to to our array list
        connectionAdapters.add(jsonConnectionAdapter);

        // increment the count
        adapterCount++;

    }

    // sort the connection adapters according to their order property
    Collections.sort(connectionAdapters, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject o1, JSONObject o2) {
            try {
                return o1.getInt("order") - o2.getInt("order");
            } catch (JSONException e) {
                return 999;
            }
        }
    });

    // create a JSON Array object which will hold json for all of the available security adapters
    JSONArray jsonConnectionAdapters = new JSONArray();

    // loop the sorted connection adapters and add to the json array
    for (JSONObject jsonConnectionAdapter : connectionAdapters)
        jsonConnectionAdapters.put(jsonConnectionAdapter);

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonConnectionAdapters", jsonConnectionAdapters);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("securityConstructors", connectionConstructors);

    _logger.info(adapterCount + " connection adapters loaded in .connectionAdapter.xml files");

    return adapterCount;

}