Example usage for javax.servlet ServletContext getInitParameter

List of usage examples for javax.servlet ServletContext getInitParameter

Introduction

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

Prototype

public String getInitParameter(String name);

Source Link

Document

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

Usage

From source file:org.lightadmin.core.config.LightAdminWebApplicationInitializer.java

private boolean lightAdminSecurityEnabled(final ServletContext servletContext) {
    return toBoolean(servletContext.getInitParameter(LIGHT_ADMINISTRATION_SECURITY));
}

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
 */// w ww. j a v  a 2s .co 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:com.bodybuilding.turbine.servlet.ClusterListServlet.java

/**
 * Returns Hystrix Dashboard URL/*from   w w  w  .  j a  v  a  2  s . c om*/
 * @param sc ServletContext
 * @param request HttpServletRequest for building full URL
 * @return
 */
private Optional<String> getDashboardUrl(ServletContext sc, HttpServletRequest request) {
    String dashboardUrl = DASHBOARD_URL.get();
    if (dashboardUrl == null) {
        dashboardUrl = sc.getInitParameter("hystrix.dashboard.url");
    }

    if (dashboardUrl == null) {
        dashboardUrl = "/monitor/monitor.html?stream=";
    }

    if (!dashboardUrl.startsWith("http://") && !dashboardUrl.startsWith("https://")) {
        if (!dashboardUrl.startsWith("/")) {
            dashboardUrl = "/" + dashboardUrl;
        }
        dashboardUrl = request.getRequestURL().toString().replaceFirst(Pattern.quote(request.getServletPath()),
                dashboardUrl);
    }
    return Optional.ofNullable(dashboardUrl);
}

From source file:org.mule.config.builders.MuleXmlBuilderContextListener.java

/**
 * Creates the MuleContext based on the configuration resource(s) and possibly 
 * init parameters for the Servlet.//from   ww w  . ja  v  a2s  .com
 */
protected MuleContext createMuleContext(String configResource, ServletContext servletContext)
        throws ConfigurationException, InitialisationException {
    String serverId = StringUtils.defaultIfEmpty(servletContext.getInitParameter("mule.serverId"), null);

    // serverId will be used as a sub-folder in Mule working directory (.mule)

    if (serverId == null) {
        // guess this app's context name from the temp/work dir the container created us
        // Servlet 2.5 has servletContext.getContextPath(), but we can't force users to upgrade yet
        final File tempDir = (File) servletContext.getAttribute(ATTR_JAVAX_SERVLET_CONTEXT_TEMPDIR);
        final String contextName = FilenameUtils.getBaseName(tempDir.toString());
        serverId = contextName;
    }

    WebappMuleXmlConfigurationBuilder builder = new WebappMuleXmlConfigurationBuilder(servletContext,
            configResource);
    MuleContextFactory muleContextFactory = new DefaultMuleContextFactory();

    String muleAppConfig = servletContext.getInitParameter(INIT_PARAMETER_MULE_APP_CONFIG) != null
            ? servletContext.getInitParameter(INIT_PARAMETER_MULE_APP_CONFIG)
            : PropertiesMuleConfigurationFactory.getMuleAppConfiguration(configResource);

    DefaultMuleConfiguration muleConfiguration = new PropertiesMuleConfigurationFactory(muleAppConfig)
            .createConfiguration();

    /*
    We deliberately enable container mode here to allow for multi-tenant environment (multiple WARs
    embedding Mule instance each). See property javadocs for more info.
     */
    muleConfiguration.setContainerMode(true);

    if (serverId != null) {
        muleConfiguration.setId(serverId);
    }
    MuleContextBuilder muleContextBuilder = new DefaultMuleContextBuilder();
    muleContextBuilder.setMuleConfiguration(muleConfiguration);

    // Support Spring-first configuration in webapps
    final ApplicationContext parentContext = (ApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (parentContext != null) {
        builder.setParentContext(parentContext);
    }
    return muleContextFactory.createMuleContext(builder, muleContextBuilder);
}

From source file:org.sindice.core.analytics.commons.webapps.SparqledContextListener.java

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

    addEnvToContext(context);//from  w  w  w. jav a 2s  . com
    final String home = (String) context.getInitParameter(SPARQLED_HOME);
    final File sparqledHome = home == null ? null : new File(home);

    if (sparqledHome == null || !sparqledHome.exists()) {
        throw new RuntimeException("Missing sparqled home");
    }
    logger.info("Looking for configuration in [{}]", sparqledHome);

    configureLogging(context, sparqledHome);
    final XMLConfiguration config = createXMLConfiguration(context);
    final File applicationConfigFile = new File(sparqledHome, CONFIG_XML);

    try {
        config.load(applicationConfigFile);
    } catch (ConfigurationException e) {
        throw new RuntimeException("Invalid configuration file: " + applicationConfigFile, e);
    }
    // important to set this as it is used later in logback.xml
    context.setAttribute("sparqled.home", home);

    context.setAttribute("config", config);
    logger.info("config now availabe via the following line of code\n"
            + "    XMLConfiguration appConfig = (XMLConfiguration) servletContext.getAttribute(\"config\");");
}

From source file:io.swagger.inflector.SwaggerInflector.java

public SwaggerInflector(@Context ServletContext servletContext) {
    this.servletContext = servletContext;
    Configuration config = null;/*from  w w  w  .  j  a v a2s.  c o  m*/
    if (servletContext != null) {
        if (servletContext.getInitParameter("inflector-config") != null) {
            try {
                config = Configuration.read(servletContext.getInitParameter("inflector-config"));
            } catch (Exception e) {
                LOGGER.error("unable to read configuration from init param");
            }
        }
    }
    if (config == null) {
        // use default location
        config = Configuration.read();
    }
    init(config);
}

From source file:org.jasig.portal.jmx.JavaManagementServerListener.java

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */// w  ww  .j  av a  2  s . c o m
public void contextInitialized(ServletContextEvent event) {
    Log logger = LogFactory.getLog(LOGGER_NAME);
    final ServletContext servletContext = event.getServletContext();

    //Create the bean
    this.javaManagementServerBean = new JavaManagementServerBean();

    //Get the failOnException option
    final String failOnExceptionStr = servletContext.getInitParameter(FAIL_ON_EXCEPTION);
    boolean failOnException = Boolean.parseBoolean(failOnExceptionStr);
    this.javaManagementServerBean.setFailOnException(failOnException);

    final String host = servletContext.getInitParameter(JMX_RMI_HOST);
    this.javaManagementServerBean.setHost(host);

    //Get the base rmi port from the init parameters
    final String portOneStr = servletContext.getInitParameter(JMX_RMI_PORT_1);
    try {
        final int portOne = Integer.parseInt(portOneStr);
        this.javaManagementServerBean.setPortOne(portOne);
    } catch (NumberFormatException nfe) {
        logger.warn("init-parameter '" + JMX_RMI_PORT_1 + "' is required and must contain a number. '"
                + portOneStr + "' is not a valid number.", nfe);
    }

    //Get the second rmi port from the init parameters
    final String portTwoStr = servletContext.getInitParameter(JMX_RMI_PORT_2);
    try {
        final int portTwo = Integer.parseInt(portTwoStr);
        this.javaManagementServerBean.setPortTwo(portTwo);
    } catch (NumberFormatException nfe) {
        logger.debug("Failed to convert init-parameter '" + JMX_RMI_PORT_2 + "' with value '" + portTwoStr
                + "' to a number, defaulting portTwo to portOne + 1", nfe);
    }

    this.javaManagementServerBean.startServer();
}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

protected void initAppProperties(ServletContext sc) {
    // get properties from web.xml
    String appProperties = sc.getInitParameter(APP_PROPS_PARAM);
    if (appProperties != null) {
        StrTokenizer tokenizer = new StrTokenizer(appProperties);
        for (String str : tokenizer.getTokenArray()) {
            int i = str.indexOf("=");
            if (i < 0)
                continue;
            String name = StringUtils.substring(str, 0, i);
            String value = StringUtils.substring(str, i + 1);
            if (!StringUtils.isBlank(name)) {
                AppContext.setProperty(name, value);
            }//ww w  .j  a  v  a 2s  . c om
        }
    }

    // get properties from a set of app.properties files defined in web.xml
    String propsConfigName = getAppPropertiesConfig(sc);
    if (propsConfigName == null)
        throw new IllegalStateException(APP_PROPS_CONFIG_PARAM + " servlet context parameter not defined");

    final Properties properties = new Properties();

    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    StrTokenizer tokenizer = new StrTokenizer(propsConfigName);
    tokenizer.setQuoteChar('"');
    for (String str : tokenizer.getTokenArray()) {
        log.trace("Processing properties location: {}", str);
        str = StrSubstitutor.replaceSystemProperties(str);
        InputStream stream = null;
        try {
            if (ResourceUtils.isUrl(str) || str.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
                Resource resource = resourceLoader.getResource(str);
                if (resource.exists())
                    stream = resource.getInputStream();
            } else {
                stream = sc.getResourceAsStream(str);
            }

            if (stream != null) {
                log.info("Loading app properties from {}", str);
                try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                    properties.load(reader);
                }
            } else {
                log.trace("Resource {} not found, ignore it", str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    for (Object key : properties.keySet()) {
        AppContext.setProperty((String) key, properties.getProperty((String) key).trim());
    }
}

From source file:servlet.CustomerControl.java

protected void doRefundTicket(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");
    int userID;//from  ww  w  . jav a2 s .co  m
    int userCredit = 0;
    int userLP = 0;
    if (user != null) {
        userID = user.getUserID();
        userCredit = user.getCredit();
        userLP = user.getTradePoint();
    } else {
        userID = 3;
        userCredit = 3000;
        userLP = 500;
    }
    ServletContext sc = getServletContext();
    String db_driver = sc.getInitParameter("db_driver"), db_url = sc.getInitParameter("db_url"),
            db_user = sc.getInitParameter("db_user"), db_password = sc.getInitParameter("db_password"),
            db_q_update = "UPDATE Ticket SET state = 'request refundment' WHERE ticketID = ? AND state = 'purchased';",
            db_q_update2 = "UPDATE \"User\" SET credit = credit + ? WHERE userID = ?";
    int ticketID = Integer.parseInt(request.getParameter("ticketID"));

    try {
        Class.forName(db_driver);
        Connection conn = DriverManager.getConnection(db_url, db_user, db_password);

        PreparedStatement statmt1 = conn.prepareStatement(db_q_update);
        statmt1.setInt(1, ticketID);
        statmt1.executeUpdate();
        PreparedStatement statmt2 = conn.prepareStatement(
                "SELECT ms.price FROM Ticket t, MovieSession ms WHERE t.msID = ms.msID AND ticketID = ?;");
        statmt2.setInt(1, ticketID);
        statmt2.execute();
        ResultSet rs2 = statmt2.getResultSet();
        PreparedStatement statmt3 = conn.prepareStatement(db_q_update2);
        rs2.next();
        statmt3.setInt(1, rs2.getInt("price"));
        statmt3.setInt(2, userID);
        statmt3.executeUpdate();

        this.doListTickets(request, response);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(CustomerControl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(CustomerControl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.freebox.engeneering.application.web.common.ApplicationContextListener.java

/**
 * Initializes the application context by web flow xml configs.
 * @param servletContextEvent the servlet context event.
 *//*from   w ww  .  j  a v a2s . c o m*/
public void contextInitialized(ServletContextEvent servletContextEvent) {
    final ServletContext servletContext = servletContextEvent.getServletContext();
    final WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);

    String initParameter = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
    final String[] configLocations = getConfigLocations(context, initParameter);

    final Set<URL> xmlConfigs = new HashSet<URL>();
    for (String configLocation : configLocations) {
        try {
            final Resource[] locationResources = context.getResources(configLocation);
            for (Resource locationResource : locationResources) {
                xmlConfigs.add(locationResource.getURL());
            }
        } catch (IOException e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Could not find state chart configuration", e);
            }
        }
    }
    Assert.notEmpty(xmlConfigs, "Cannot find state chart configuration.");

    ApplicationContextLocator.setWebFlowConfiguration(xmlConfigs);
    ApplicationContextLocator.setApplicationContext(context);

    final FlowConfigurationLoader flowConfigurationLoader = (FlowConfigurationLoader) context
            .getBean("flowConfigurationLoader");
    flowConfigurationLoader.init(xmlConfigs);
}