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:jenkins.model.Jenkins.java

private static void computeVersion(ServletContext context) {
    // set the version
    Properties props = new Properties();
    InputStream is = null;//w  ww  .j av  a 2 s .  co m
    try {
        is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
        if (is != null)
            props.load(is);
    } catch (IOException e) {
        e.printStackTrace(); // if the version properties is missing, that's OK.
    } finally {
        IOUtils.closeQuietly(is);
    }
    String ver = props.getProperty("version");
    if (ver == null)
        ver = "?";
    VERSION = ver;
    context.setAttribute("version", ver);

    VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
    SESSION_HASH = Util.getDigestOf(ver + System.currentTimeMillis()).substring(0, 8);

    if (ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
        RESOURCE_PATH = "";
    else
        RESOURCE_PATH = "/static/" + SESSION_HASH;

    VIEW_RESOURCE_PATH = "/resources/" + SESSION_HASH;
}

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

public static int loadControls(ServletContext servletContext) throws Exception {

    // assume no controls
    int controlCount = 0;

    // create a list for our controls
    List<JSONObject> jsonControls = new ArrayList<JSONObject>();

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

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

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

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

        // get a scanner to read the file
        Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A");

        // read the xml into a string
        String xml = fileScanner.next();

        // close the scanner (and file)
        fileScanner.close();

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

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

        JSONObject jsonControl;
        int index = 0;
        int count = 0;

        if (jsonControlCollection.optJSONArray("control") == null) {
            jsonControl = jsonControlCollection.getJSONObject("control");
        } else {
            jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index);
            count = jsonControlCollection.getJSONArray("control").length();
        }

        do {

            // check this type does not already exist
            for (int i = 0; i < jsonControls.size(); i++) {
                if (jsonControl.getString("type").equals(jsonControls.get(i).getString("type")))
                    throw new Exception(" control type is loaded already. Type names must be unique");
            }

            // add the jsonControl to our array
            jsonControls.add(jsonControl);

            // inc the control count
            controlCount++;
            // inc the count of controls in this file
            index++;

            // get the next one
            if (index < count)
                jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index);

        } while (index < count);

    }

    // sort the list of controls by name
    Collections.sort(jsonControls, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject c1, JSONObject c2) {
            try {
                return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false);
            } catch (JSONException e) {
                return 0;
            }
        }

    });

    // create a JSON Array object which will hold json for all of the available controls
    JSONArray jsonArrayControls = new JSONArray(jsonControls);

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

    _logger.info(controlCount + " controls loaded in .control.xml files");

    return controlCount;

}

From source file:com.redsqirl.CanvasBean.java

/**
 * save//from www  .ja  v  a  2  s  .com
 * 
 * Method to save the workflow
 * 
 * @return
 * @author Igor.Souza
 * @throws JSONException
 */
public void save() {

    logger.info("save");
    String msg = null;
    // Set path
    path = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("pathFile");

    String selecteds = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
            .get("selecteds");
    logger.warn("save " + selecteds);
    FacesContext fCtx = FacesContext.getCurrentInstance();
    ServletContext sc = (ServletContext) fCtx.getExternalContext().getContext();
    sc.setAttribute("selecteds", selecteds);

    workflowType = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
            .get("workflowType");
    logger.warn("workflow Type " + workflowType);

    String name = generateWorkflowName(path);
    if (workflowType != null && workflowType.equals("S")) {
        if (path != null) {
            path = path.substring(0, path.lastIndexOf("/")) + "/" + name;
        }
    }

    /*if (!path.endsWith(".rs") || !path.endsWith(".srs")) {
       if (workflowType != null && workflowType.equals("S")) {
    path += ".srs";
       } else {
    path += ".rs";
       }
    }*/

    if (workflowType != null && workflowType.equals("S")) {
        if (!path.endsWith(".srs")) {
            path += ".srs";
        }
    } else {
        if (!path.endsWith(".rs")) {
            path += ".rs";
        }
    }

    // Update the object positions
    updateCanvasStatus();
    {
        String nameWorkflowSwp = generateWorkflowName(path);

        try {
            msg = getworkFlowInterface().renameWorkflow(nameWorkflow, nameWorkflowSwp);
        } catch (RemoteException e) {
            msg = "Error when renaming workflow";
            logger.error("Error when renaming workflow: " + e);
            usageRecordLog().addError("ERROR SAVE", e.getMessage());
        }

        if (msg == null && !nameWorkflowSwp.equals(nameWorkflow)) {
            workflowMap.put(nameWorkflowSwp, workflowMap.get(nameWorkflow));
            workflowMap.remove(nameWorkflow);
            // idMap.put(nameWorkflowSwp, idMap.get(nameWorkflow));
            idMap.put(nameWorkflowSwp, new HashMap<String, String>());
            idMap.remove(nameWorkflow);

            getMapWorkflowType().put(nameWorkflowSwp, getMapWorkflowType().get(nameWorkflow));
            getMapWorkflowType().remove(nameWorkflow);

            nameWorkflow = nameWorkflowSwp;
        }
    }
    try {
        if (msg == null) {
            logger.warn("save workflow " + nameWorkflow + " in " + path);
            DataFlow df = getWorkflowMap().get(nameWorkflow);
            setDf(df);
            msg = df.save(path);
        }

        if (msg == null) {
            df.setPath(path);
            Iterator<String> itCompIds = df.getComponentIds().iterator();
            idMap.get(nameWorkflow).clear();
            while (itCompIds.hasNext()) {
                String cur = itCompIds.next();
                idMap.get(nameWorkflow).put(cur, cur);
            }

            logger.warn("save msg :" + msg);
        }
    } catch (Exception e) {
        msg = "Error saving workflow";
        logger.warn(msg, e);
    }

    displayErrorMessage(msg, "SAVE");
}

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 va 2 s.c  o m
    };

    // 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;

}

From source file:com.redsqirl.CanvasBean.java

public void cloneWorkflow() throws Exception {
    logger.info("cloneWorkflow");
    String nameWf = getNameWorkflow();
    updateAllCanvasesStatus();//w  ww  . j a v a 2 s.  c o m
    String wfClone = getworkFlowInterface().cloneDataFlow(getNameWorkflow());
    FacesContext fCtx = FacesContext.getCurrentInstance();
    ServletContext sc = (ServletContext) fCtx.getExternalContext().getContext();
    Map<String, String> cloneMap = new LinkedHashMap<String, String>();
    if (idMap.containsKey(nameWf)) {
        cloneMap.putAll(idMap.get(nameWf));
    }
    sc.setAttribute("cloneMap", cloneMap);
    sc.setAttribute("wfClone", wfClone);
    getIdMapClone().put(wfClone, cloneMap);
    logger.info(wfClone);
    setCloneWFId(wfClone);
}

From source file:org.apache.tapestry.engine.AbstractEngine.java

/**
 *  Invoked from {@link #service(RequestContext)} to ensure that the engine's
 *  instance variables are setup.  This allows the application a chance to
 *  restore transient variables that will not have survived deserialization.
 *
 *  Determines the servlet prefix:  this is the base URL used by
 *  {@link IEngineService services} to build URLs.  It consists
 *  of two parts:  the context path and the servlet path.
 *
 *  <p>The servlet path is retrieved from {@link HttpServletRequest#getServletPath()}.
 *
 *  <p>The context path is retrieved from {@link HttpServletRequest#getContextPath()}.
 *
 *  <p>The global object is retrieved from {@link IEngine#getGlobal()} method.
 *
 *  <p>The final path is available via the {@link #getServletPath()} method.
 *
 *  <p>In addition, this method locates and/or creates the:
 *  <ul>//from  ww  w  .ja v a 2  s  .c  o m
 *  <li>{@link IComponentClassEnhancer}
 *  <li>{@link Pool}
 *  <li>{@link ITemplateSource}
 *  <li>{@link ISpecificationSource}
 *  <li>{@link IPageSource}
 *  <li>{@link IEngineService} {@link Map}
 *  <ll>{@link IScriptSource}
 *  <li>{@link IComponentMessagesSource}
 *  <li>{@link IPropertySource}
 *  </ul>
 *
 *  <p>This order is important, because some of the later shared objects
 *  depend on some of the earlier shared objects already having
 *  been located or created
 *  (especially {@link #getPool() pool}).
 *
 *  <p>Subclasses should invoke this implementation first, then perform their
 *  own setup.
 *
 **/

protected void setupForRequest(RequestContext context) {
    HttpServlet servlet = context.getServlet();
    ServletContext servletContext = servlet.getServletContext();
    HttpServletRequest request = context.getRequest();
    HttpSession session = context.getSession();

    if (session != null)
        _sessionId = context.getSession().getId();
    else
        _sessionId = null;

    // Previously, this used getRemoteHost(), but that requires an
    // expensive reverse DNS lookup. Possibly, the host name lookup
    // should occur ... but only if there's an actual error message
    // to display.

    if (_clientAddress == null)
        _clientAddress = request.getRemoteAddr();

    // servletPath is null, so this means either we're doing the
    // first request in this session, or we're handling a subsequent
    // request in another JVM (i.e. another server in the cluster).
    // In any case, we have to do some late (re-)initialization.

    if (_servletPath == null) {
        // Get the path *within* the servlet context

        // In rare cases related to the tagsupport service, getServletPath() is wrong
        // (its a JSP, which invokes Tapestry as an include, thus muddling what
        // the real servlet and servlet path is).  In those cases, the JSP tag
        // will inform us.

        String path = (String) request.getAttribute(Tapestry.TAG_SUPPORT_SERVLET_PATH_ATTRIBUTE);

        if (path == null)
            path = request.getServletPath();

        // Get the context path, which may be the empty string
        // (but won't be null).

        _contextPath = request.getContextPath();

        _servletPath = _contextPath + path;
    }

    String servletName = context.getServlet().getServletName();

    if (_propertySource == null) {
        String name = PROPERTY_SOURCE_NAME + ":" + servletName;

        _propertySource = (IPropertySource) servletContext.getAttribute(name);

        if (_propertySource == null) {
            _propertySource = createPropertySource(context);

            servletContext.setAttribute(name, _propertySource);
        }
    }

    if (_enhancer == null) {
        String name = ENHANCER_NAME + ":" + servletName;

        _enhancer = (IComponentClassEnhancer) servletContext.getAttribute(name);

        if (_enhancer == null) {
            _enhancer = createComponentClassEnhancer(context);

            servletContext.setAttribute(name, _enhancer);
        }
    }

    if (_pool == null) {
        String name = POOL_NAME + ":" + servletName;

        _pool = (Pool) servletContext.getAttribute(name);

        if (_pool == null) {
            _pool = createPool(context);

            servletContext.setAttribute(name, _pool);
        }
    }

    if (_templateSource == null) {
        String name = TEMPLATE_SOURCE_NAME + ":" + servletName;

        _templateSource = (ITemplateSource) servletContext.getAttribute(name);

        if (_templateSource == null) {
            _templateSource = createTemplateSource(context);

            servletContext.setAttribute(name, _templateSource);
        }
    }

    if (_specificationSource == null) {
        String name = SPECIFICATION_SOURCE_NAME + ":" + servletName;

        _specificationSource = (ISpecificationSource) servletContext.getAttribute(name);

        if (_specificationSource == null) {
            _specificationSource = createSpecificationSource(context);

            servletContext.setAttribute(name, _specificationSource);
        }
    }

    if (_pageSource == null) {
        String name = PAGE_SOURCE_NAME + ":" + servletName;

        _pageSource = (IPageSource) servletContext.getAttribute(name);

        if (_pageSource == null) {
            _pageSource = createPageSource(context);

            servletContext.setAttribute(name, _pageSource);
        }
    }

    if (_scriptSource == null) {
        String name = SCRIPT_SOURCE_NAME + ":" + servletName;

        _scriptSource = (IScriptSource) servletContext.getAttribute(name);

        if (_scriptSource == null) {
            _scriptSource = createScriptSource(context);

            servletContext.setAttribute(name, _scriptSource);
        }
    }

    if (_serviceMap == null) {
        String name = SERVICE_MAP_NAME + ":" + servletName;

        _serviceMap = (Map) servletContext.getAttribute(name);

        if (_serviceMap == null) {
            _serviceMap = createServiceMap();

            servletContext.setAttribute(name, _serviceMap);
        }
    }

    if (_stringsSource == null) {
        String name = STRINGS_SOURCE_NAME + ":" + servletName;

        _stringsSource = (IComponentMessagesSource) servletContext.getAttribute(name);

        if (_stringsSource == null) {
            _stringsSource = createComponentStringsSource(context);

            servletContext.setAttribute(name, _stringsSource);
        }
    }

    if (_dataSqueezer == null) {
        String name = DATA_SQUEEZER_NAME + ":" + servletName;

        _dataSqueezer = (DataSqueezer) servletContext.getAttribute(name);

        if (_dataSqueezer == null) {
            _dataSqueezer = createDataSqueezer();

            servletContext.setAttribute(name, _dataSqueezer);
        }
    }

    if (_global == null) {
        String name = GLOBAL_NAME + ":" + servletName;

        _global = servletContext.getAttribute(name);

        if (_global == null) {
            _global = createGlobal(context);

            servletContext.setAttribute(name, _global);
        }
    }

    if (_resourceChecksumSource == null) {
        String name = RESOURCE_CHECKSUM_SOURCE_NAME + ":" + servletName;

        _resourceChecksumSource = (ResourceChecksumSource) servletContext.getAttribute(name);

        if (_resourceChecksumSource == null) {
            _resourceChecksumSource = createResourceChecksumSource();

            servletContext.setAttribute(name, _resourceChecksumSource);
        }
    }

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = getOutputEncoding();
        try {
            request.setCharacterEncoding(encoding);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(Tapestry.format("illegal-encoding", encoding));
        } catch (NoSuchMethodError e) {
            // Servlet API 2.2 compatibility
            // Behave okay if the setCharacterEncoding() method is unavailable
        } catch (AbstractMethodError e) {
            // Servlet API 2.2 compatibility
            // Behave okay if the setCharacterEncoding() method is unavailable
        }
    }
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

/**
 * Perform initialisation necessary to setup AjaxToaster database pools...
 *///from w ww.ja  v  a 2  s  .c  o  m
private void initDBPools(Properties servletProperties, ServletContext context) {

    // Read the default JNDI name or connection pool name to use when creating database connections.
    // held in AjaxToaster.properties as the "default_db_jndi_name" property.
    // This is used if there is no properties file with an overriding "db_jndi_name" property supplied for a toaster script.

    default_db_jndi_name = servletProperties.getProperty(PROP_DEFAULT_JNDI_DATABASE);
    default_db_jdbc_name = servletProperties.getProperty(PROP_DEFAULT_JDBC_POOL);

    println("**** Default JDBC pool = " + default_db_jdbc_name);
    println("**** Default JNDI name = " + default_db_jndi_name);

    /**
     *  Create any jdbc connection pools
     *
     * Properties file format for connection pools is :
     *        jdbc.class.[poolId]    = [driver classname]
     *        jdbc.database.[poolId] = [database to connect to]
     *        jdbc.username.[poolId] = [user to connect as]
     *        jdbc.password.[poolId] = [password]
       *
     * ...Where [id] is a unique identifier for the pool. It can be anything as long as it's unique per pool.
     *
     * There is no restriction on the number of connection pools that can be defined.
       */

    for (Enumeration e = servletProperties.propertyNames(); e.hasMoreElements();) {

        String propertyName = (String) e.nextElement();

        println("**** checking property.... " + propertyName);

        if (propertyName.startsWith("jdbc.database.")) {

            String poolId = propertyName.substring(propertyName.lastIndexOf("."));

            poolId = poolId.replaceFirst("\\.", "");

            String driver = servletProperties.getProperty("jdbc.driver." + poolId);
            String url = servletProperties.getProperty("jdbc.database." + poolId);
            String username = servletProperties.getProperty("jdbc.username." + poolId);
            String password = servletProperties.getProperty("jdbc.password." + poolId);

            // Not using a container managed database connection pool.... lets make our own!
            // Create a database connection pool...

            println("**** INFO: JDBC CONNECTION PROPERTIES FOR " + poolId + " - ("
                    + servletProperties.getProperty(propertyName) + ")");
            println("****       driver=" + driver);
            println("****       url=" + url);
            println("****       username=" + username);
            println("****       password=" + password);

            try {
                String contextDirectory = context.getRealPath("/");
                DBConnectionPool dbpool = new DBConnectionPool(poolId, driver, url, username, password,
                        contextDirectory);
                String attr = ATTRIB_JDBC_CONN_POOL + "." + poolId;

                println("Storing JDBC pool in " + attr);

                context.setAttribute(attr, dbpool);
            } catch (Exception ex) {
                println("**** ERROR: Exception creating a database connection pool: " + ex.toString());
                // continue... some pools might be ok...
            }

        }

    }

}

From source file:org.viafirma.nucleo.Nucleo.java

/**
 * Inicializa el nucleo, y este a su vez inicializa todos los mdulos que
 * dependen de el// w  w w .ja va 2s  .  c  o  m
 * 
 */
@Override
public void init(ServletContext context) {
    singleton = this;
    // 1.- inicializamos el sistema de criptografa
    // Eliminamos el proveedor para evitar que se solapen si ya existia uno.
    //Security.removeProvider(new BouncyCastleProvider().getName());
    //Security.addProvider(new BouncyCastleProvider());
    //log.info("Lista de proveedores disponible:" + Arrays.asList(Security.getProviders()));
    // 1.- Inicializamos los proveedores criptograficos
    SecurityProvidersUtils.initProviders();

    org.apache.xml.security.Init.init();
    // inicializa el sistema de cache para mantener los certificados
    CacheManager manager = CacheManager.getInstance();

    cacheCertificados = new Cache("cacheCertificadosEnUso", 200, false, false, TIEMPO_VIDA_CERTIFICADO,
            TIEMPO_VIDA_CERTIFICADO);
    manager.addCache(cacheCertificados);
    log.debug("Inicializada cache de certificados.");

    cacheDocumentToSign = new Cache("cacheDocumentoToSign", 100, true, false, TIEMPO_VIDA_DOCUMENT_TO_SIGN,
            TIEMPO_VIDA_DOCUMENT_TO_SIGN);
    manager.addCache(cacheDocumentToSign);
    log.debug("Inicializada cache documentos a firmar .");

    // 2.- inicializo el servicio RMI.
    // creamos un registro propio programticamente
    // en lugar de utilizar el registro JNDI del servidor de aplicaciones o
    // el comando rmiregistry para aislar nuestra aplicacin de
    // incompatibilidades
    // entre diferentes servidores de aplicaciones.
    try {
        rmiRegistry = LocateRegistry.createRegistry(Constantes.PORT_RMI);
        // creamos la instancia del Servidor
        ConectorFirmaRMI serverRMI = new ConectorFirmaRMI();
        // publicamos el servidor en el registro
        rmiRegistry.bind(Constantes.NOMBRE_CONECOR_RMI_PUBLICADO, serverRMI);
        log.info("Avtivado registro RMI. Puerto: " + Constantes.PORT_RMI + ", nombre del servicio: "
                + Constantes.NOMBRE_CONECOR_RMI_PUBLICADO);
        // Publicamos el servicio tambien en web
    } catch (RemoteException e) {
        // No se puede activar el servicio RMI.
        log.fatal("No se puede activar el servicio RMI " + e.getMessage(), e);
    } catch (AlreadyBoundException e) {
        // El puerto ya esta en uso.
        log.fatal("El puesto " + Constantes.PORT_RMI
                + " ya esta en uso por otra aplicacin. No se puede activar el servicio de firma", e);
    }
    Properties properties = ConfigUtil.getInstance().readConfigPropertes();
    // 3.- iniciamos el sistema de custodia de docuemtos
    Custodia.init(properties);

    // 4.- iniciamos las erramientas de QRCode
    QRCodeUtil.init(properties);

    // 5.- inicializo el envio de Email.
    SendMailUtil.init(properties);

    // Configuracin del sistema de validacin de CRLs. Por defecto la
    // validacin esta activada.
    String tempValidacion = (String) properties.get(Constantes.PARAM_VALIDACION_ONLINE);
    boolean validacionOnline = tempValidacion == null ? true : new Boolean(tempValidacion);
    ValidadorHandler.init(validacionOnline, properties);
    validador = ValidadorHandler.getCurrentInstance();
    log.debug("Inicializado Validador de certificados. Validacin online en: " + validacionOnline);

    // Metemos en el contexto de aplicacin todos los parametros de
    // configuracin
    for (Object key : properties.keySet()) {
        context.setAttribute((String) key, properties.get(key));
    }

    // Recuperamos la url pblica:
    URL_PUBLIC_VERIFICATION = properties.getProperty(Constantes.PARAM_URL_APLICACION)
            + Constantes.PATH_VERIFICACION;

    log.info("Nucleo Inicializado. ");
}

From source file:org.intermine.web.struts.InitialiserPlugin.java

/**
 * Init method called at Servlet initialisation
 *
 * @param servlet ActionServlet that is managing all the modules
 * in this web application//from w  ww .j  av  a  2 s.com
 * @param config ModuleConfig for the module with which this
 * plug-in is associated
 *
 * @throws ServletException if this <code>PlugIn</code> cannot
 * be successfully initialized
 */
public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {

    // NOTE throwing exceptions other than a ServletException from this class causes the
    // webapp to fail to deploy with no error message.

    final ServletContext servletContext = servlet.getServletContext();
    initBlockingErrors(servletContext);

    // initialise properties
    Properties webProperties = loadWebProperties(servletContext);

    // read in additional webapp specific information and put in servletContext
    loadAspectsConfig(servletContext);
    loadClassDescriptions(servletContext);
    loadOpenIDProviders(servletContext);

    // get link redirector
    LinkRedirectManager redirect = getLinkRedirector(webProperties);

    // set up core InterMine application
    os = getProductionObjectStore(webProperties);
    WebConfig webConfig = null;
    if (os != null) {
        webConfig = loadWebConfig(servletContext, os);
    }

    final ObjectStoreWriter userprofileOSW = getUserprofileWriter(webProperties);

    if (userprofileOSW != null) {
        //verify all table mapping classes exist in the userprofile db
        if (!verifyTablesExist(userprofileOSW)) {
            return;
        }
        if (!verifySuperUserExist(userprofileOSW)) {
            return;
        }
        //verify if intermine_state exists in the savedbag table and if it has the right type
        if (!verifyListTables(userprofileOSW)) {
            return;
        }
        //verify if we the webapp needs to upgrade the lists
        verifyListUpgrade(userprofileOSW);
    }

    final ObjectStoreSummary oss = summariseObjectStore(servletContext);

    if (webProperties != null && userprofileOSW != null) {
        trackerDelegate = initTrackers(webProperties, userprofileOSW);
    }

    if (os != null && webProperties != null) {
        final Map<String, List<FieldDescriptor>> classKeys = loadClassKeys(os.getModel());
        final BagQueryConfig bagQueryConfig = loadBagQueries(servletContext, os, webProperties);

        if (userprofileOSW != null) {
            final InterMineAPI im;
            try {
                im = new InterMineAPI(os, userprofileOSW, classKeys, bagQueryConfig, oss, trackerDelegate,
                        redirect);
            } catch (UserNotFoundException unfe) {
                blockingErrorKeys.put("errors.init.superuser", null);
                return;
            }
            SessionMethods.setInterMineAPI(servletContext, im);

            InterMineContext.initilise(im, webProperties, webConfig);

            // need a global reference to ProfileManager so it can be closed cleanly on destroy
            profileManager = im.getProfileManager();

            //verify superuser setted in the db matches with the user in the properties file
            final Profile superProfile = profileManager.getSuperuserProfile();
            if (!superProfile.getUsername()
                    .equals(PropertiesUtil.getProperties().getProperty("superuser.account").trim())) {
                blockingErrorKeys.put("errors.init.superuser", null);
            }

            // index global webSearchables
            SearchRepository searchRepository = new GlobalRepository(superProfile);
            List<String> users = profileManager.getSuperUsers();
            for (String su : users) {
                new GlobalRepository(profileManager.getProfile(su));
            }
            SessionMethods.setGlobalSearchRepository(servletContext, searchRepository);

            servletContext.setAttribute(Constants.GRAPH_CACHE, new HashMap<String, String>());

            loadAutoCompleter(servletContext, os);

            cleanTags(im.getTagManager());

            if (webConfig != null) {
                Map<String, Boolean> keylessClasses = new HashMap<String, Boolean>();
                for (ClassDescriptor cld : os.getModel().getClassDescriptors()) {
                    boolean keyless = true;
                    for (FieldConfig fc : FieldConfigHelper.getClassFieldConfigs(webConfig, cld)) {
                        if ((fc.getDisplayer() == null) && fc.getShowInSummary()) {
                            keyless = false;
                            break;
                        }
                    }
                    if (keyless) {
                        keylessClasses.put(TypeUtil.unqualifiedName(cld.getName()), Boolean.TRUE);
                    }
                }
                servletContext.setAttribute(Constants.KEYLESS_CLASSES_MAP, keylessClasses);
            }

            if (oss != null) {
                setupClassSummaryInformation(servletContext, oss, os.getModel());
            }

            doRegistration(webProperties);
        }
    }
}

From source file:org.red5.server.undertow.UndertowLoader.java

/**
 * Initialization.//from   w  ww. java2 s. c  o  m
 */
public void start() {
    log.info("Loading undertow context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // scan the sub directories to determine our context paths
    buildContextPathList(webappFolder);
    try {
        // create our servlet container
        container = ServletContainer.Factory.newInstance();
        // create a root path handler
        final PathHandler rootHandler = new PathHandler();
        // create one server and use it everywhere
        Undertow.Builder builder = Undertow.builder();
        // loop through connectors adding listeners to the builder
        for (UndertowConnector undertowConnector : connectors) {
            InetSocketAddress addr = undertowConnector.getSocketAddress();
            builder.addListener(addr.getPort(), addr.getHostName(),
                    (undertowConnector.isSecure() ? ListenerType.HTTPS : ListenerType.HTTP));
        }
        log.trace("Classloader for undertow: {} TCL: {}", Undertow.class.getClassLoader(), originalClassLoader);
        // create references for later lookup
        LoaderBase.setApplicationLoader(new UndertowApplicationLoader(container, applicationContext));
        // loop the other contexts
        for (String contextPath : contextPaths) {
            // create a class loader for the context
            ClassLoader classLoader = buildWebClassLoader(originalClassLoader, webappFolder, contextPath);
            // create deployment info
            DeploymentInfo info = deployment().setClassLoader(classLoader)
                    .setContextPath(contextPath.equalsIgnoreCase("/ROOT") ? "/" : contextPath)
                    .setDefaultEncoding("UTF-8").setDeploymentName(contextPath.substring(1) + ".war")
                    .setUrlEncoding("UTF-8");
            // parse the web.xml and configure the context
            parseWebXml(webappFolder, contextPath, info);
            if (log.isDebugEnabled()) {
                log.debug("Deployment info - name: {} servlets: {} filters: {}", new Object[] {
                        info.getDisplayName(), info.getServlets().size(), info.getFilters().size() });
            }
            // add the new deployment to the servlet container
            DeploymentManager manager = container.addDeployment(info);
            // set a reference to the manager and deploy the context
            LoaderBase.setRed5ApplicationContext(contextPath, new UndertowApplicationContext(manager));
            // deploy
            manager.deploy();
            // add path
            rootHandler.addPrefixPath(info.getContextPath(), manager.start());
            // get deployment
            Deployment deployment = manager.getDeployment();
            // get servlet context
            final ServletContext servletContext = deployment.getServletContext();
            log.debug("Context initialized: {}", servletContext.getContextPath());
            try {
                log.debug("Context: {}", servletContext);
                final ClassLoader webClassLoader = info.getClassLoader();
                log.debug("Webapp classloader: {}", webClassLoader);
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                // set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(webClassLoader);
                // create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(webClassLoader);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        // web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            // 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.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            // set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                            appctx.start();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class", e);
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
        // Dump deployments list
        if (log.isDebugEnabled()) {
            for (String deployment : container.listDeployments()) {
                log.debug("Container deployment: {}", deployment);
            }
        }
        // if everything is ok at this point then call the rtmpt and rtmps beans so they will init
        //         if (applicationContext.containsBean("rtmpt.server")) {
        //            log.debug("Initializing RTMPT");
        //            applicationContext.getBean("rtmpt.server");
        //            log.debug("Finished initializing RTMPT");
        //         } else {
        //            log.info("Dedicated RTMPT server configuration was not specified");
        //         }
        //         if (applicationContext.containsBean("rtmps.server")) {
        //            log.debug("Initializing RTMPS");
        //            applicationContext.getBean("rtmps.server");
        //            log.debug("Finished initializing RTMPS");
        //         } else {
        //            log.debug("Dedicated RTMPS server configuration was not specified");
        //         }
        // add a root handler
        builder.setHandler(rootHandler);
        // build the server instance
        server = builder.build();
        log.info("Starting Undertow");
        server.start();
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading undertow, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading undertow", e);
        }
    } finally {
        registerJMX();
    }
    log.debug("Undertow init exit");
}