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:ContextLogger.java

public void contextInitialized(ServletContextEvent sce) {

    ServletContext context = sce.getServletContext();

    String realPath = context.getRealPath("/");
    String fileSep = System.getProperty("file.separator");

    if (realPath != null && (!realPath.endsWith(fileSep)))
        realPath = realPath + fileSep;/*from w w w .  j a  va  2 s .  co m*/
    //Initialize logger here:
    PropertyConfigurator.configure(realPath + "WEB-INF/classes/" + context.getInitParameter("logger-config"));
    log = Logger.getLogger(ContextLogger.class);

    String name = context.getServletContextName();
    //log request about servlet context being initialized
    log.info("ServletContext ready: " + (name == null ? "" : name));

}

From source file:fr.univlorraine.mondossierweb.Initializer.java

/**
 * Ajoute les paramtres de contexte aux proprits systmes, de manire  les rendre accessibles dans logback.xml
 * @param servletContext/*from  w  w  w  .j  ava 2s  .  co m*/
 */
private void addContextParametersToSystemProperties(ServletContext servletContext) {
    Enumeration<String> e = servletContext.getInitParameterNames();
    while (e.hasMoreElements()) {
        String parameterName = e.nextElement();
        System.setProperty("context." + parameterName, servletContext.getInitParameter(parameterName));
    }
}

From source file:com.ocpsoft.pretty.faces.el.resolver.FacesConfigBeanNameResolver.java

/**
 * Returns a collection of faces configuration files mentioned via the
 * default <code>javax.faces.CONFIG_FILES</code> init parameter
 * /*from  w ww.  j  a  v a 2 s  .  co  m*/
 * @param servletContext
 *           The ServletContext
 * @return A collection of URLs (never null)
 */
private Collection<URL> getConfigFilesFromInitParameter(ServletContext servletContext) {

    // read init parameter
    String initParam = servletContext.getInitParameter(FacesServlet.CONFIG_FILES_ATTR);

    // empty? return empty set
    if (initParam == null || initParam.trim().length() == 0) {
        return Collections.emptySet();
    }

    // split string at each comma
    String[] files = initParam.split(",");

    // the result
    Set<URL> result = new HashSet<URL>();

    // process each single file
    for (String file : files) {

        // ignore empty entries
        if (file.trim().length() == 0) {
            continue;
        }

        try {
            // try get URL for this file
            URL url = servletContext.getResource(file.trim());

            // add it to the result, if it exists
            if (url != null) {
                result.add(url);
            }
        } catch (MalformedURLException e) {
            // log on debug level, because the JSF implementation should
            // handle such a case
            log.debug("Invalid entry in javax.faces.CONFIG_FILES init parameter: " + file);
        }

    }

    return result;
}

From source file:it.geosolutions.geobatch.catalog.file.DataDirHandler.java

/**
 * Try to retrieve the info about where the requested property dir is located.
 *
 * @param propertyName a property name referring to a string containing a path
 *
 * @return a valid dir or null.//from w  w w .j a  v  a 2  s .  c om
 *
 * @throws NullPointerException
 * @throws IllegalStateException
 */
protected File retrieveConfiguredDir(String propertyName) throws NullPointerException, IllegalStateException {
    File ret = null;

    //        try {
    String prop = System.getProperty(propertyName);
    if (prop != null) {
        ret = new File(prop);
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(propertyName + " read from property");
        }
    } else {
        prop = System.getenv(propertyName);
        if (prop != null) {
            ret = new File(prop);
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(propertyName + " read from environment var");
            }
        } else {
            if (this.applicationContext instanceof WebApplicationContext) {
                final WebApplicationContext wContext = (WebApplicationContext) applicationContext;
                final ServletContext servletContext = wContext.getServletContext();
                String rootDir = servletContext.getInitParameter(propertyName);
                if (rootDir != null) {
                    ret = new File(rootDir);
                    if (LOGGER.isErrorEnabled()) {
                        LOGGER.error(propertyName + " read from servlet init param");
                    }
                }
            }
        }
    }
    //        } catch (SecurityException e) {
    //            // gobble exception
    //            if ( LOGGER.isInfoEnabled() ) {
    //                LOGGER.info(e.getLocalizedMessage(), e);
    //            }
    //        }

    if (ret == null) {
        return null;
    }

    if (!ret.exists()) {
        throw new IllegalStateException(
                "Could not initialize " + propertyName + ": The provided path does not exists (" + ret + ")");
    }

    if (!ret.isDirectory() || !ret.canRead()) {
        throw new IllegalStateException("Could not initialize " + propertyName
                + ": The provided path is not a readable directory (" + ret + ")");
    }

    if (!ret.isAbsolute())
        LOGGER.warn("The configured " + propertyName + " is not absolute: " + ret);

    return ret;
}

From source file:com.ibm.util.merge.web.InitializeServlet.java

private void getRuntimeProperties(ServletContext servletContext) {
    this.rootFrom = "System.getProperty";
    this.rootFolder = System.getProperty("IDMU_ROOT");
    if (this.rootFolder == null) {
        this.rootFrom = "context.getInitParameter";
        this.rootFolder = servletContext.getInitParameter("IDMU_ROOT");
    }//from   ww  w  .java  2s  . c  o  m
    if (this.rootFolder == null) {
        this.rootFrom = "default";
        this.rootFolder = "/opt/ibm/idmu";
    }
    this.idmuPropertiesFile = new File(
            this.rootFolder + File.separator + "properties" + File.separator + "idmu.properties");
    if (!this.idmuPropertiesFile.exists()) {
        setup(this.rootFolder, servletContext);
    }
    try {
        this.runtimeProperties.load(new FileInputStream(this.idmuPropertiesFile));
    } catch (IOException e) {
        throw new RuntimeException("Failed to load properties file " + this.idmuPropertiesFile);
    }
}

From source file:org.pepstock.jem.gwt.server.listeners.StartUp.java

@Override
public void contextInitialized(ServletContextEvent event) {
    // starts SHIRO
    super.contextInitialized(event);
    // gets servlet context
    ServletContext context = event.getServletContext();
    // gets servlet context and saves it
    SharedObjects.getInstance().setContext(context);
    // reads Hazecast init parameter
    String hazelcastFile = context.getInitParameter(ConfigKeys.HAZELCAST_CONFIG);
    // set the check version flag retreive by web.xml
    Boolean checkVersion = Boolean.valueOf(context.getInitParameter(ConfigKeys.JEM_CHECK_VERSION));
    SharedObjects.getInstance().setCheckVersion(checkVersion);
    setJemVersion(context);// www  .  j  a v a 2  s. c  o  m
    if (hazelcastFile != null) {
        try {
            // starts hazelcast
            startHazelcastClient(context, hazelcastFile);
        } catch (ConfigurationException e) {
            throw new JemRuntimeException(e);
        }
    } else {
        throw new MessageRuntimeException(UserInterfaceMessage.JEMG021E);
    }
}

From source file:servlet.CinemaControl.java

protected void doListHousesOfCinema(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    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");

}

From source file:org.ajax4jsf.webapp.WebXml.java

/**
 * @param context/*from   w ww.j a  v a2s  . c o m*/
 */
void setupResourcePrefixes(ServletContext context) {
    String globalResourcePrefix = context.getInitParameter(GLOBAL_RESOURCE_URI_PREFIX_PARAM);

    String sessionResourcePrefix = context.getInitParameter(SESSION_RESOURCE_URI_PREFIX_PARAM);

    String resourcePrefix = context.getInitParameter(RESOURCE_URI_PREFIX_PARAM);

    if (null != resourcePrefix) {
        if (globalResourcePrefix == null) {
            // TODO overriden
            globalResourcePrefix = resourcePrefix;
        }

        if (sessionResourcePrefix == null) {
            // TODO overriden
            sessionResourcePrefix = resourcePrefix;
        }
    } else {
        resourcePrefix = RESOURCE_URI_PREFIX_VERSIONED;
    }

    if (globalResourcePrefix == null) {
        // TODO overriden
        globalResourcePrefix = GLOBAL_RESOURCE_URI_PREFIX_VERSIONED;
    }

    if (sessionResourcePrefix == null) {
        // TODO overriden
        sessionResourcePrefix = SESSION_RESOURCE_URI_PREFIX_VERSIONED;
    }

    if (null != getFacesFilterPrefix()) {
        _prefixMapping = true;
        if (getFacesFilterPrefix().endsWith("/")) {
            setGlobalResourcePrefix(globalResourcePrefix);
            setSessionResourcePrefix(sessionResourcePrefix);
            setResourcePrefix(resourcePrefix);
        } else {
            setGlobalResourcePrefix("/" + globalResourcePrefix);
            setSessionResourcePrefix("/" + sessionResourcePrefix);
            setResourcePrefix("/" + resourcePrefix);
        }
    } else if (null != getFacesFilterSuffix()) {
        _prefixMapping = false;
        setResourcePrefix("/" + resourcePrefix);
        setGlobalResourcePrefix("/" + globalResourcePrefix);
        setSessionResourcePrefix("/" + sessionResourcePrefix);
    }
}

From source file:com.nabla.wapp.server.database.CommonConnectionPool.java

/**
 * Constructor//from  w w w .ja v  a2s.c  o m
 * @param dbName         - database name as defined in pool
 * @param serverContext      - web app context
 * @throws SQLException 
 */
public CommonConnectionPool(final String dbName, final ServletContext serverContext) throws SQLException {
    Assert.argumentNotNull(dbName, "Have you set the database name in your web.xml file?");
    Assert.argumentNotNull(serverContext);

    url = "jdbc:apache:commons:dbcp:/" + dbName;
    if (!isLoaded(dbName)) {
        load(dbName);
        final String driverName = serverContext.getInitParameter(DATABASE_DRIVER_NAME);
        Assert.notNull(driverName, "Have you set the database driver name in your web.xml file?");
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            if (log.isDebugEnabled())
                log.debug("fail to find database driver class '" + driverName + "'", e);
            throw new SQLException("fail to find database driver class '" + driverName + "'");
        }
    }
}

From source file:servlet.CustomerControl.java

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

    String req_msID = request.getParameter("msID");
    String req_seatIDs = request.getParameter("seatID");
    int msID = Integer.parseInt(req_msID);
    User user = (User) session.getAttribute("user");
    int userID;//from  w w w . j  ava2  s. c om
    int userCredit = 0;
    int userLP = 0;
    if (user != null) {
        userID = user.getUserID();
        userCredit = user.getCredit();
        userLP = user.getTradePoint();
    } else {
        out.println("require login");
        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");
    String db_q_chk_credit = "SELECT SUM(s.surcharge + ms.price)" + " FROM Seat s, House h, MovieSession ms"
            + " WHERE s.houseID = h.houseID" + " AND h.houseID = ms.houseID" + " AND ms.msID = ?"
            + " AND s.seatID IN (" + req_seatIDs + ");";
    String db_q_update_credit = "UPDATE \"User\" SET credit = credit - ?, tradePoint = tradePoint + ? WHERE userID = ?;";
    String db_q_update_loyaltyPoints = "UPDATE \"User\" SET tradePoint = tradePoint - ? WHERE userID = ?;";
    String db_q_check = "SELECT t.* FROM Ticket t WHERE t.userID = ? AND t.msID = ? AND t.seatID = ?;";
    String db_q_insert = "INSERT INTO Ticket (\"userID\", \"msID\", \"seatID\", \"state\") VALUES (?, ?, ?, 'purchased');";
    String db_q_insert_2 = "INSERT INTO Ticket (\"userID\", \"msID\", \"seatID\", \"state\") VALUES (?, ?, ?, 'redeemed');";
    String db_q_update = "UPDATE Ticket SET state = 'refunded' WHERE ticketID = ?;";

    String paymentMethod = request.getParameter("paymentMethod");

    try {
        Class.forName(db_driver);
        Connection conn = DriverManager.getConnection(db_url, db_user, db_password);
        PreparedStatement statmt1 = conn.prepareStatement(db_q_chk_credit);
        statmt1.setInt(1, msID);
        if (statmt1.execute()) {
            ResultSet rs1 = statmt1.getResultSet();
            if (rs1.next()) {
                int totalAmount = rs1.getInt(1);
                if (paymentMethod.equals("Cash")) {
                    if (totalAmount < userCredit) {
                        // purchase
                        String[] seatIDs = req_seatIDs.split(",");
                        for (int i = 0; i < seatIDs.length; i++) {
                            PreparedStatement statmt2 = conn.prepareStatement(db_q_check);
                            int seatID = Integer.parseInt(seatIDs[i]);
                            statmt2.setInt(1, userID);
                            statmt2.setInt(2, msID);
                            statmt2.setInt(3, seatID);
                            statmt2.execute();
                            ResultSet rs2 = statmt2.getResultSet();
                            boolean hasNext = rs2.next();
                            if (!hasNext || (hasNext && rs2.getString("state").equals("refunded"))) {
                                PreparedStatement statmt3 = conn.prepareStatement(db_q_insert);
                                statmt3.setInt(1, userID);
                                statmt3.setInt(2, msID);
                                statmt3.setInt(3, seatID);
                                statmt3.executeUpdate();
                            } else {
                                out.println("Seat is reserved");
                            }
                        }

                        PreparedStatement statmt4 = conn.prepareStatement(db_q_update_credit);
                        statmt4.setInt(1, totalAmount);
                        statmt4.setInt(2, totalAmount / 10);
                        statmt4.setInt(3, userID);
                        statmt4.executeUpdate();

                        out.println("true");
                    } else {
                        out.println("Your credit is not enough!");
                    }

                } else if (paymentMethod.equals("Loyalty Point")) {
                    // pay by loyalty points
                    if (totalAmount < userLP) {
                        // purchase
                        String[] seatIDs = req_seatIDs.split(",");
                        for (int i = 0; i < seatIDs.length; i++) {
                            PreparedStatement statmt2 = conn.prepareStatement(db_q_check);
                            int seatID = Integer.parseInt(seatIDs[i]);
                            statmt2.setInt(1, userID);
                            statmt2.setInt(2, msID);
                            statmt2.setInt(3, seatID);
                            statmt2.execute();
                            ResultSet rs2 = statmt2.getResultSet();
                            boolean hasNext = rs2.next();
                            if (!hasNext || (hasNext && rs2.getString("state").equals("refunded"))) {
                                PreparedStatement statmt3 = conn.prepareStatement(db_q_insert_2);
                                statmt3.setInt(1, userID);
                                statmt3.setInt(2, msID);
                                statmt3.setInt(3, seatID);
                                statmt3.executeUpdate();
                            } else {
                                out.println("Seat is reserved");
                            }
                        }

                        PreparedStatement statmt4 = conn.prepareStatement(db_q_update_loyaltyPoints);
                        statmt4.setInt(1, totalAmount);
                        statmt4.setInt(2, userID);
                        statmt4.executeUpdate();

                        out.println("true");
                    } else {
                        out.println("Your loyalty points is not enough!");
                    }

                }
            }
        }
        conn.close();

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