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:servlet.CustomerControl.java

protected void doListTickets(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();

    JSONObject jso0 = new JSONObject();
    JSONArray jsa0 = new JSONArray();
    try {// w  ww.j  av  a2s .  com
        jso0.put("tickets", jsa0);
    } catch (JSONException ex) {
        Logger.getLogger(CustomerControl.class.getName()).log(Level.SEVERE, null, ex);
    }

    User user = (User) session.getAttribute("user");
    int userID;
    int userCredit = 0;
    int userLP = 0;
    if (user != null) {
        userID = user.getUserID();
        userCredit = user.getCredit();
        userLP = user.getTradePoint();
    } else {
        out.println(jso0.toString());
        return;
    }
    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_tickets = "SELECT DISTINCT t.ticketID, t.state, s.rowName, s.seatName,"
                    + " (ms.price + s.surcharge) AS 'price', ms.playtime, m.*, h.houseName,"
                    + " c.cinemaName, c.cinemaDistrict, c.cinemaAddress, c.tel, c.image1"
                    + " FROM Ticket t, MovieSession ms, Movie m, Seat s, House h, Cinema c"
                    + " WHERE t.msID = ms.msID" + " AND ms.houseID = h.houseID" + " AND h.cinemaID = c.cinemaID"
                    + " AND h.houseID = s.houseID" + " AND t.seatID = s.seatID" + " AND ms.movieID = m.movieID"
                    + " AND t.userID = ?;";
    try {
        Class.forName(db_driver);
        Connection conn = DriverManager.getConnection(db_url, db_user, db_password);
        PreparedStatement statmt = conn.prepareStatement(db_q_tickets);
        statmt.setInt(1, userID);
        if (statmt.execute()) {
            ResultSet rs = statmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int numOfColumns = rsmd.getColumnCount();
            while (rs.next()) {
                JSONObject jso1 = new JSONObject();
                jsa0.put(jso1);
                for (int i = 1; i <= numOfColumns; i++) {
                    jso1.put(rsmd.getColumnLabel(i), rs.getString(i));
                }
                String playtime = jso1.getString("playtime");
                jso1.put("date", playtime.substring(0, 10));
                jso1.put("time", playtime.subSequence(11, 16));
            }

        }
        conn.close();
        out.println(jso0.toString());

    } 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);
    } catch (JSONException ex) {
        Logger.getLogger(CustomerControl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Create debug string containing all parameter names and their values from
 * the context.//from w ww .  j a va2 s.c o  m
 *
 * @param  scContext - context to print out
 * @return String - debug string containing all parameter names and their
 *                  values from the context
 */
public static String debug(ServletContext scContext) {
    Enumeration enumNames;
    String strParam;
    StringBuilder sbfReturn = new StringBuilder();

    sbfReturn.append("ServletContext=[ServletContextName=");
    sbfReturn.append(scContext.getServletContextName());
    sbfReturn.append(";");
    for (enumNames = scContext.getInitParameterNames(); enumNames.hasMoreElements();) {
        strParam = (String) enumNames.nextElement();
        sbfReturn.append("Param=");
        sbfReturn.append(strParam);
        sbfReturn.append(" value=");
        sbfReturn.append(scContext.getInitParameter(strParam));
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }
    sbfReturn.append("]");

    return sbfReturn.toString();
}

From source file:info.magnolia.cms.servlets.PropertyInitializer.java

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 *//* www .  ja  v  a 2s  . com*/
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();

    String propertiesLocationString = context.getInitParameter(MAGNOLIA_INITIALIZATION_FILE);

    if (log.isDebugEnabled()) {
        log.debug("{} value in web.xml is :[{}]", MAGNOLIA_INITIALIZATION_FILE, propertiesLocationString); //$NON-NLS-1$
    }
    if (StringUtils.isEmpty(propertiesLocationString)) {
        propertiesLocationString = DEFAULT_INITIALIZATION_PARAMETER;
    }

    String[] propertiesLocation = StringUtils.split(propertiesLocationString, ',');

    String servername = null;

    try {
        servername = StringUtils.lowerCase(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        log.error(e.getMessage());
    }

    String rootPath = StringUtils.replace(context.getRealPath(StringUtils.EMPTY), "\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
    String webapp = StringUtils.substringAfterLast(rootPath, "/"); //$NON-NLS-1$

    File logs = new File(webapp + File.separator + "logs");
    File tmp = new File(webapp + File.separator + "tmp");
    if (!logs.exists()) {
        logs.mkdir();
        log.debug("Creating " + logs.getAbsoluteFile() + " folder");
    }

    if (!tmp.exists()) {
        tmp.mkdir();
        log.debug("Creating " + tmp.getAbsoluteFile() + " folder");
    }

    if (log.isDebugEnabled()) {
        log.debug("rootPath is {}, webapp is {}", rootPath, webapp); //$NON-NLS-1$ 
    }

    for (int j = 0; j < propertiesLocation.length; j++) {
        String location = StringUtils.trim(propertiesLocation[j]);
        location = StringUtils.replace(location, "${servername}", servername); //$NON-NLS-1$
        location = StringUtils.replace(location, "${webapp}", webapp); //$NON-NLS-1$

        File initFile = new File(rootPath, location);

        if (!initFile.exists() || initFile.isDirectory()) {
            if (log.isDebugEnabled()) {
                log.debug("Configuration file not found with path [{}]", //$NON-NLS-1$
                        initFile.getAbsolutePath());
            }
            continue;
        }

        InputStream fileStream;
        try {
            fileStream = new FileInputStream(initFile);
        } catch (FileNotFoundException e1) {
            log.debug("Configuration file not found with path [{}]", //$NON-NLS-1$
                    initFile.getAbsolutePath());
            return;
        }

        try {
            envProperties.load(fileStream);

            log.info("Loading configuration at {}", initFile.getAbsolutePath());//$NON-NLS-1$

            Log4jConfigurer.initLogging(context, envProperties);

            new ConfigLoader(context, envProperties);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(fileStream);
        }
        return;

    }

    log.error(MessageFormat.format(
            "No configuration found using location list {0}. [servername] is [{1}], [webapp] is [{2}] and base path is [{3}]", //$NON-NLS-1$
            new Object[] { ArrayUtils.toString(propertiesLocation), servername, webapp, rootPath }));

}

From source file:interactivespaces.example.activity.externalproxy.webappproxy.InteractiveSpacesExternalProxyServlet.java

/**
 * Get the content for the function of the mobile device.
 *
 * @param function/*from   w  w w.j  a  va 2  s .c  o  m*/
 *          the function the mobile device should have
 *
 * @return the content for the function
 */
private String getFunctionContent(String function) {
    ServletContext context = getServletContext();
    String fullPath = context.getRealPath("/WEB-INF/functions/" + function + ".html");

    String serverHost = context.getInitParameter(CONTEXT_PARAMETER_MY_SERVER_HOST);

    String content = Files.readFile(new File(fullPath));

    content = content.replaceAll("\\@HOST\\@", serverHost);

    return content;
}

From source file:org.impalaframework.web.spring.loader.BaseImpalaContextLoader.java

/**
 * Overrides the empty {@link ContextLoader#customizeContext(ServletContext, ConfigurableWebApplicationContext)}
 * by setting the parent {@link ApplicationContext} to use an empty location if the current location is simply the default,
 * and this does not exist. Effectively provides transparent support for "empty" parent {@link ApplicationContext}
 *//*from   w w  w .j  a va 2s  . c o  m*/
@Override
protected void customizeContext(ServletContext servletContext,
        ConfigurableWebApplicationContext applicationContext) {

    final String initParameter = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
    if (initParameter == null) {
        final ServletContextResource servletContextResource = new ServletContextResource(servletContext,
                XmlWebApplicationContext.DEFAULT_CONFIG_LOCATION);
        if (!servletContextResource.exists()) {
            try {
                applicationContext.setConfigLocation("classpath:META-INF/impala-web-empty.xml");
            } catch (UnsupportedOperationException e) {
                //no longer supported in Spring 3.2, so ignore this
            }
        }
    }
}

From source file:org.quartz.ee.servlet.QuartzInitializerListener.java

public void contextInitialized(ServletContextEvent sce) {

    log.info("Quartz Initializer Servlet loaded, initializing Scheduler...");

    ServletContext servletContext = sce.getServletContext();
    StdSchedulerFactory factory;//from  w  ww  .ja  v  a  2  s. co m
    try {

        String configFile = servletContext.getInitParameter("config-file");
        String shutdownPref = servletContext.getInitParameter("shutdown-on-unload");

        if (shutdownPref != null) {
            performShutdown = Boolean.valueOf(shutdownPref).booleanValue();
        }

        // get Properties
        if (configFile != null) {
            factory = new StdSchedulerFactory(configFile);
        } else {
            factory = new StdSchedulerFactory();
        }

        // Always want to get the scheduler, even if it isn't starting, 
        // to make sure it is both initialized and registered.
        scheduler = factory.getScheduler();

        // Should the Scheduler being started now or later
        String startOnLoad = servletContext.getInitParameter("start-scheduler-on-load");

        int startDelay = 0;
        String startDelayS = servletContext.getInitParameter("start-delay-seconds");
        try {
            if (startDelayS != null && startDelayS.trim().length() > 0)
                startDelay = Integer.parseInt(startDelayS);
        } catch (Exception e) {
            log.error("Cannot parse value of 'start-delay-seconds' to an integer: " + startDelayS
                    + ", defaulting to 5 seconds.");
            startDelay = 5;
        }

        /*
         * If the "start-scheduler-on-load" init-parameter is not specified,
         * the scheduler will be started. This is to maintain backwards
         * compatability.
         */
        if (startOnLoad == null || (Boolean.valueOf(startOnLoad).booleanValue())) {
            if (startDelay <= 0) {
                // Start now
                scheduler.start();
                log.info("Scheduler has been started...");
            } else {
                // Start delayed
                scheduler.startDelayed(startDelay);
                log.info("Scheduler will start in " + startDelay + " seconds.");
            }
        } else {
            log.info("Scheduler has not been started. Use scheduler.start()");
        }

        String factoryKey = servletContext.getInitParameter("servlet-context-factory-key");
        if (factoryKey == null) {
            factoryKey = QUARTZ_FACTORY_KEY;
        }

        log.info("Storing the Quartz Scheduler Factory in the servlet context at key: " + factoryKey);
        servletContext.setAttribute(factoryKey, factory);

    } catch (Exception e) {
        log.error("Quartz Scheduler failed to initialize: " + e.toString());
        e.printStackTrace();
    }
}

From source file:org.opentestsystem.shared.test.jetty.InheritingSpringContextLoaderListener.java

@Override
public WebApplicationContext createWebApplicationContext(ServletContext servletContext) {

    _logger.debug("Adding root Spring application context to Jetty container");
    XmlWebApplicationContext uiSpringContext = new XmlWebApplicationContext();
    uiSpringContext.setServletContext(servletContext);
    uiSpringContext.setParent(_externalContext);
    String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
    if (!StringUtils.isEmpty(contextConfigLocation)) {
        uiSpringContext.setConfigLocation(contextConfigLocation);
        _logger.debug("root Spring application context to Jetty container configured from {}",
                contextConfigLocation);/*from   ww  w .  j a va  2 s.co m*/
    } else {
        _logger.debug(
                "root Spring application context to Jetty container using default configuration location");
    }
    uiSpringContext.refresh();
    return uiSpringContext;
}

From source file:org.springframework.faces.mvc.servlet.FacesHandlerAdapterTests.java

private void doTestOverrideInitParams(boolean override) throws Exception {
    adapter.setOverrideInitParameters(override);
    ServletContext servletContext = new MockServletContext();
    adapter.setServletContext(servletContext);
    ServletContext facesServletContext = adapter.getFacesServletContext();
    assertEquals((override ? "false" : null),
            facesServletContext.getInitParameter("org.apache.myfaces.ERROR_HANDLING"));
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsServlet.java

/**
 * Loads the application properties and populates a java.util.Properties
 * instance.//from w w  w.  j a  v a  2 s .  co  m
 * 
 * @param servletConfig
 *            The ServletConfig used to locate the application property
 *            file.
 * @return The application properties.
 */
private Properties loadApplicationProperties(ServletConfig servletConfig) {
    // read application properties from servlet context
    ServletContext ctx = servletConfig.getServletContext();
    String path = ctx.getRealPath("/");
    String appConfigFile = ctx.getInitParameter(APP_CONFIG_LOCATION);
    Properties properties = new Properties();
    try {
        InputStream is = new FileInputStream(path + appConfigFile);
        properties.load(is);
        is.close();
        LOG.info("Loaded application properties from " + path + appConfigFile);
    } catch (IOException e) {
        LOG.error("Unable to load application properties from " + path + appConfigFile, e);
    }
    return properties;
}

From source file:org.seasar.cubby.plugins.guice.CubbyModuleTest.java

@Test
public void configure() throws Exception {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ServletContext servletContext = createNiceMock(ServletContext.class);
    expect(servletContext.getInitParameter("cubby.guice.module")).andStubReturn(TestModule.class.getName());
    final Hashtable<String, Object> attributes = new Hashtable<String, Object>();
    expect(servletContext.getAttribute((String) anyObject())).andStubAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            return attributes.get(getCurrentArguments()[0]);
        }//  w  w  w.  j  a  v  a2s.  co  m

    });
    servletContext.setAttribute((String) anyObject(), anyObject());
    expectLastCall().andAnswer(new IAnswer<Void>() {

        public Void answer() throws Throwable {
            attributes.put((String) getCurrentArguments()[0], getCurrentArguments()[1]);
            return null;
        }

    });
    replay(servletContext);

    final CubbyGuiceServletContextListener cubbyGuiceServletContextListener = new CubbyGuiceServletContextListener();
    cubbyGuiceServletContextListener.contextInitialized(new ServletContextEvent(servletContext));

    final GuiceFilter guiceFilter = new GuiceFilter();
    guiceFilter.init(new FilterConfig() {

        public String getFilterName() {
            return "guice";
        }

        public String getInitParameter(final String name) {
            return null;
        }

        @SuppressWarnings("unchecked")
        public Enumeration getInitParameterNames() {
            return new Vector<String>().elements();
        }

        public ServletContext getServletContext() {
            return servletContext;
        }

    });

    final FilterChain chain = new FilterChain() {

        public void doFilter(final ServletRequest request, final ServletResponse response)
                throws IOException, ServletException {
            final PluginRegistry pluginRegistry = PluginRegistry.getInstance();
            final GuicePlugin guicePlugin = new GuicePlugin();
            try {
                guicePlugin.initialize(servletContext);
                guicePlugin.ready();
                pluginRegistry.register(guicePlugin);
            } catch (final Exception e) {
                throw new ServletException(e);
            }

            final Injector injector = guicePlugin.getInjector();
            System.out.println(injector);

            final PathResolverProvider pathResolverProvider = ProviderFactory.get(PathResolverProvider.class);
            final PathResolver pathResolver = pathResolverProvider.getPathResolver();
            System.out.println(pathResolver);

            final PathTemplateParser pathTemplateParser = injector.getInstance(PathTemplateParser.class);
            System.out.println(pathTemplateParser);
            assertTrue(pathTemplateParser instanceof MyPathTemplateParser);

            final ContainerProvider containerProvider = ProviderFactory.get(ContainerProvider.class);
            final Container container = containerProvider.getContainer();
            final Foo foo = container.lookup(Foo.class);
            System.out.println(foo);
            System.out.println(foo.pathResolver);

            assertSame(pathResolver, foo.pathResolver);

            try {
                final Baz baz = injector.getInstance(Baz.class);
                System.out.println(baz);
                fail();
            } catch (final ConfigurationException e) {
                // ok
            }

            final ConverterProvider converterProvider = ProviderFactory.get(ConverterProvider.class);
            System.out.println(converterProvider);
            System.out.println(converterProvider.getConverter(BigDecimalConverter.class));

            final FileUpload fileUpload1 = injector.getInstance(FileUpload.class);
            System.out.println(fileUpload1);
            System.out.println(fileUpload1.getFileItemFactory());

            final FileUpload fileUpload2 = injector.getInstance(FileUpload.class);
            System.out.println(fileUpload2);
            System.out.println(fileUpload2.getFileItemFactory());

            assertNotSame(fileUpload1, fileUpload2);
            assertNotSame(fileUpload1.getFileItemFactory(), fileUpload2.getFileItemFactory());
        }

    };
    guiceFilter.doFilter(request, response, chain);
    cubbyGuiceServletContextListener.contextDestroyed(new ServletContextEvent(servletContext));
    ThreadContext.remove();
}