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.sakaiproject.component.impl.ContextLoader.java

/**
 * Initialize the local ApplicationContext, link it to the shared context, and load shared definitions into the shared context.
 * //from  w ww .j a v a 2  s.co m
 * @param servletContext
 *        current servlet context
 * @return the new WebApplicationContext
 * @throws BeansException
 *         if the context couldn't be initialized
 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws BeansException {
    WebApplicationContext rv = super.initWebApplicationContext(servletContext);

    // if we have a parent and any shared bean definitions, load them into the parent
    ConfigurableApplicationContext parent = (ConfigurableApplicationContext) rv.getParent();
    if (parent != null) {
        String sharedConfig = servletContext.getInitParameter(SHARED_LOCATION_PARAM);
        if (sharedConfig != null) {
            String[] locations = StringUtils.tokenizeToStringArray(sharedConfig,
                    ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS);
            if (locations != null) {
                XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
                        (BeanDefinitionRegistry) parent.getBeanFactory());

                for (int i = 0; i < locations.length; i++) {
                    try {
                        reader.loadBeanDefinitions(rv.getResources(locations[i]));
                    } catch (IOException e) {
                        M_log.warn("exception loading into parent: " + e);
                    }
                }
            }
        }
    }

    return rv;
}

From source file:servlet.CinemaControl.java

protected void doListSeatsByMS(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");
    String db_q_seat_available = "SELECT DISTINCT s.seatID, s.houseID, s.rowName, s.seatName, s.surcharge, s.state, ms.price"
            + " FROM Seat s, MovieSession ms" + " WHERE s.seatID NOT IN"
            + " (SELECT seatID FROM Ticket WHERE state NOT IN ('refunded') AND msID = ?)"
            + " AND ms.houseID = s.houseID" + " AND ms.msID = ?";
    String db_q_seat_booked = "SELECT DISTINCT s.seatID, s.houseID, s.rowName, s.seatName, s.surcharge, s.state, ms.price"
            + " FROM Seat s, MovieSession ms" + " WHERE s.seatID IN"
            + " (SELECT seatID FROM Ticket WHERE state NOT IN ('refunded') AND msID = ?)"
            + " AND ms.houseID = s.houseID" + " AND ms.msID = ?";
    int msID = Integer.parseInt(request.getParameter("msID"));
    try {/* w  w  w .j  a  va2s.co  m*/
        JSONObject jso0 = new JSONObject();
        JSONArray jsa0 = new JSONArray();
        jso0.put("seats", jsa0);
        Class.forName(db_driver);
        Connection conn = DriverManager.getConnection(db_url, db_user, db_password);
        // available seat
        PreparedStatement statmt1 = conn.prepareStatement(db_q_seat_available);
        statmt1.setInt(1, msID);
        statmt1.setInt(2, msID);
        if (statmt1.execute()) {
            ResultSet rs = statmt1.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.getColumnName(i), rs.getString(i));
                }
            }
        }
        // unavailable seat
        PreparedStatement statmt2 = conn.prepareStatement(db_q_seat_booked);
        statmt2.setInt(1, msID);
        statmt2.setInt(2, msID);
        if (statmt2.execute()) {
            ResultSet rs = statmt2.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.getColumnName(i), rs.getString(i));
                    jso1.put("state", "unavailable");
                }
            }
        }

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

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

From source file:org.kuali.ext.mm.web.listener.StandaloneInitializeListener.java

/**
 * Translates context parameters from the web.xml into entries in a Properties file.
 *//*from  w w w.j a  v a 2 s.c o  m*/
protected Properties getContextParameters(ServletContext context) {
    Properties properties = new Properties();
    Enumeration paramNames = context.getInitParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        properties.put(paramName, context.getInitParameter(paramName));
    }
    return properties;
}

From source file:org.openestate.is24.restapi.webapp.VerificationServlet.java

/**
 * Servlet is initialized by the servlet engine.
 *
 * @throws ServletException// www .  j av  a 2 s  .  co m
 */
@Override
public void init() throws ServletException {
    super.init();
    final ServletContext context = this.getServletContext();
    List<String> errors = new ArrayList<String>();

    this.webserviceUrl = StringUtils.trimToNull(context.getInitParameter("WebserviceUrl"));
    if (this.webserviceUrl == null) {
        errors.add("No 'WebserviceUrl' is configured.");
    }

    this.consumerKey = StringUtils.trimToNull(context.getInitParameter("ConsumerKey"));
    if (this.consumerKey == null) {
        errors.add("No 'ConsumerKey' is configured.");
    }

    this.consumerSecret = StringUtils.trimToNull(context.getInitParameter("ConsumerSecret"));
    if (this.consumerSecret == null) {
        errors.add("No 'ConsumerSecret' is configured.");
    }

    if (!errors.isEmpty()) {
        throw new ServletException("Can't init servlet: " + StringUtils.join(errors, ", "));
    }

    // trust all SSL certificates / disable host name verification
    String trustAllCertificates = StringUtils.trimToNull(context.getInitParameter("TrustAllCertificates"));
    if ("1".equals(trustAllCertificates) || "true".equalsIgnoreCase(trustAllCertificates)) {
        try {
            // install all-trusting trust manager
            SslUtils.disableCertificateChecks();

            // install all-trusting host verifier
            SslUtils.disableHostnameVerification();
        } catch (Exception ex) {
            throw new ServletException("Can't setup insecure SSL context!", ex);
        }
    }
}

From source file:nl.b3p.kaartenbalie.core.server.persistence.MyEMFDatabase.java

public void initGlobalContextParams(ServletConfig config) {
    ServletContext context = config.getServletContext();

    String value = context.getInitParameter(MyEMFDatabase.MAPFILE_DIR);
    if (value != null && value.length() > 0) {
        mapfiles = value;/*from ww  w . j  av a2 s  .co m*/
    }
    value = context.getInitParameter(MyEMFDatabase.UPLOAD_DIR);
    if (value != null && value.length() > 0) {
        upload = value;
    }
    value = context.getInitParameter(MyEMFDatabase.DEFAULT_ORGANIZATION);
    if (value != null && value.length() > 0) {
        defaultOrganization = value;
    }

    value = context.getInitParameter(MyEMFDatabase.LDAP_USELDAP);
    if (value != null && value.length() > 0) {
        ldapUseLdap = new Boolean(value);
    }
    value = context.getInitParameter(MyEMFDatabase.LDAP_DEFAULTGROUP);
    if (value != null && value.length() > 0) {
        ldapDefaultGroup = value;
    }
    value = context.getInitParameter(MyEMFDatabase.LDAP_HOST);
    if (value != null && value.length() > 0) {
        ldapHost = value;
    }
    value = context.getInitParameter(MyEMFDatabase.LDAP_PORT);
    if (value != null && value.length() > 0) {
        ldapPort = new Integer(value);
    }
    value = context.getInitParameter(MyEMFDatabase.LDAP_USERSUFFIX);
    if (value != null && value.length() > 0) {
        ldapUserSuffix = value;
    }
}

From source file:servlet.CinemaControl.java

protected void doListSeats(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");
    String db_q_cinemas = "SELECT * FROM Cinema;";
    String db_q_houses = "SELECT * FROM House WHERE cinemaID = ?;";
    String db_q_seats = "SELECT * FROM Seat WHERE houseID = ?;";
    try {/*from ww  w .j  a v a2  s  .  com*/
        JSONObject jso0 = new JSONObject();
        JSONArray jsa0 = new JSONArray();
        jso0.put("cinemas", jsa0);
        Class.forName(db_driver);
        Connection conn = DriverManager.getConnection(db_url, db_user, db_password);
        Statement statmt1 = conn.createStatement();
        ResultSet rs1 = statmt1.executeQuery(db_q_cinemas);
        ResultSetMetaData rsmd1 = rs1.getMetaData();
        int numOfColumns1 = rsmd1.getColumnCount();
        while (rs1.next()) {
            JSONObject jso1 = new JSONObject();
            jsa0.put(jso1);
            for (int i = 1; i <= numOfColumns1; i++) {
                jso1.put(rsmd1.getColumnLabel(i), rs1.getString(i));
            }
            int cinemaID = Integer.parseInt(jso1.getString("cinemaID"));
            JSONArray jsa1 = new JSONArray();
            jso1.put("houses", jsa1);
            PreparedStatement statmt2 = conn.prepareStatement(db_q_houses);
            statmt2.setInt(1, cinemaID);
            if (statmt2.execute()) {
                ResultSet rs2 = statmt2.getResultSet();
                ResultSetMetaData rsmd2 = rs2.getMetaData();
                int numOfColumns2 = rsmd2.getColumnCount();
                while (rs2.next()) {
                    JSONObject jso2 = new JSONObject();
                    jsa1.put(jso2);
                    for (int j = 1; j <= numOfColumns2; j++) {
                        jso2.put(rsmd2.getColumnLabel(j), rs2.getString(j));
                    }
                    int houseID = Integer.parseInt(jso2.getString("houseID"));
                    JSONArray jsa2 = new JSONArray();
                    jso2.put("seats", jsa2);
                    PreparedStatement statmt3 = conn.prepareStatement(db_q_seats);
                    statmt3.setInt(1, houseID);
                    if (statmt3.execute()) {
                        ResultSet rs3 = statmt3.getResultSet();
                        ResultSetMetaData rsmd3 = rs3.getMetaData();
                        int numOfColumns3 = rsmd3.getColumnCount();
                        while (rs3.next()) {
                            JSONObject jso3 = new JSONObject();
                            jsa2.put(jso3);
                            for (int k = 1; k <= numOfColumns3; k++) {
                                jso3.put(rsmd3.getColumnLabel(k), rs3.getString(k));
                            }
                        }
                    }
                }
            }
        }
        out.println(jso0.toString());
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(CinemaControl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(CinemaControl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(CinemaControl.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.nuxeo.runtime.deployment.NuxeoStarter.java

protected void findEnv(ServletContext servletContext) {
    for (String param : Arrays.asList( //
            NUXEO_RUNTIME_HOME, //
            NUXEO_CONFIG_DIR, //
            NUXEO_DATA_DIR, //
            NUXEO_LOG_DIR, //
            NUXEO_TMP_DIR, //
            NUXEO_WEB_DIR)) {/*from  w  w w . ja  v a 2  s  .  co m*/
        String value = servletContext.getInitParameter(param);
        if (value != null && !"".equals(value.trim())) {
            env.put(param, value);
        }
    }
    // default env values
    if (!env.containsKey(NUXEO_CONFIG_DIR)) {
        String webinf = servletContext.getRealPath("/WEB-INF");
        env.put(NUXEO_CONFIG_DIR, webinf);
    }
    if (!env.containsKey(NUXEO_RUNTIME_HOME)) {
        File home = new File(DEFAULT_HOME);
        env.put(NUXEO_RUNTIME_HOME, home.getAbsolutePath());
    }
    // host
    if (getClass().getClassLoader().getClass().getName().startsWith("org.jboss.classloader")) {
        env.put(FrameworkLoader.HOST_NAME, JBOSS_HOST);
    } else if (servletContext.getClass().getName().startsWith("org.apache.catalina")) {
        env.put(FrameworkLoader.HOST_NAME, TOMCAT_HOST);
    }
}

From source file:org.apache.tapestry5.internal.spring.SpringModuleDef.java

public SpringModuleDef(ServletContext servletContext) {
    this.servletContext = servletContext;

    compatibilityMode = Boolean//from  www  .j ava 2  s.c o  m
            .parseBoolean(servletContext.getInitParameter(SpringConstants.USE_EXTERNAL_SPRING_CONTEXT));

    final ApplicationContext externalContext = compatibilityMode ? locateExternalContext() : null;

    if (compatibilityMode)
        addServiceDefsForSpringBeans(externalContext);

    ServiceDef applicationContextServiceDef = new ServiceDef() {
        @Override
        public ObjectCreator createServiceCreator(final ServiceBuilderResources resources) {
            if (compatibilityMode)
                return new StaticObjectCreator(externalContext,
                        "externally configured Spring ApplicationContext");

            ApplicationContextCustomizer customizer = resources.getService("ApplicationContextCustomizer",
                    ApplicationContextCustomizer.class);

            return constructObjectCreatorForApplicationContext(resources, customizer);
        }

        @Override
        public String getServiceId() {
            return SERVICE_ID;
        }

        @Override
        public Set<Class> getMarkers() {
            return Collections.emptySet();
        }

        @Override
        public Class getServiceInterface() {
            return compatibilityMode ? externalContext.getClass() : ConfigurableWebApplicationContext.class;
        }

        @Override
        public String getServiceScope() {
            return ScopeConstants.DEFAULT;
        }

        @Override
        public boolean isEagerLoad() {
            return false;
        }
    };

    services.put(SERVICE_ID, applicationContextServiceDef);
}

From source file:net.wastl.webmail.config.ExtConfigListener.java

public void contextInitialized(ServletContextEvent sce) {
    Helper.logThreads("Top of ExtCongigListener.contextInitialized()");
    final ServletContext sc = sce.getServletContext();
    contextPath = sc.getInitParameter("default.contextpath");
    try {/*from   www  .j  ava 2s .  c o m*/
        final Object o = new InitialContext().lookup("java:comp/env/app.contextpath");
        contextPath = (String) o;
        log.debug("app.contextpath set by webapp env property");
    } catch (final NameNotFoundException nnfe) {
    } catch (final NamingException nnfe) {
        log.fatal("Runtime failure when looking up env property", nnfe);
        throw new RuntimeException("Runtime failure when looking up env property", nnfe);
    }
    if (contextPath == null) {
        log.fatal("Required setting 'app.contextpath' is not set as either "
                + "a app webapp JNDI env param, nor by default context "
                + "init parameter 'default.contextpath'");
        throw new IllegalStateException("Required setting 'app.contextpath' is not set as either "
                + "a app webapp JNDI env param, nor by default context "
                + "init parameter 'default.contextpath'");
    }
    if (contextPath.equals("/ROOT")) {
        log.fatal("Refusing to use context path of '/ROOT' to avoid " + "ambiguity with default context path");
        throw new IllegalStateException(
                "Refusing to use context path of '/ROOT' to avoid " + "ambiguity with default context path");
    }
    deploymentName = generateDeploymentName();
    log.info("Initializing configs for runtime deployment name '" + deploymentName + "'");
    String dirProp = System.getProperty("webapps.rtconfig.dir");
    if (dirProp == null) {
        dirProp = System.getProperty("user.home");
        System.setProperty("webapps.rtconfig.dir", dirProp);
    }
    final File rtConfigDir = new File(dirProp, deploymentName);
    final File metaFile = new File(rtConfigDir, "meta.properties");
    lockFile = new File(rtConfigDir, "lock.txt");
    if (lockFile.exists()) {
        log.fatal("Presence of lock file '" + lockFile.getAbsolutePath()
                + "' indicates the instance is already running");
        lockFile = null;
        throw new IllegalStateException("Presence of lock file " + "indicates the instance is already running");
    }
    // From this point on, we know that:
    // IF LOCK FILE EXISTS, we have created it and all is well
    // IF LOCK FILE DOES NOT EXIST, we need to create it ASAP
    if (rtConfigDir.isDirectory()) {
        mkLockFile();
    }
    // We create lock file as early as possible.
    // If we can't make it here, it will be created in installXmlStorage.
    if (!rtConfigDir.isDirectory() || !metaFile.isFile()) {
        try {
            installXmlStorage(rtConfigDir, metaFile);
            log.warn("New XML storage system successfully loaded.  " + "Metadata file '"
                    + metaFile.getAbsolutePath() + "'");
        } catch (final IOException e) {
            log.fatal("Failed to set up a new XML storage system", e);
            throw new IllegalStateException("Failed to set up a new XML storage system", e);
        }
    }
    if (!lockFile.exists()) {
        // Being extra safe
        log.fatal("Assertion failed.  Internal locking error in " + getClass().getName() + '.');
        lockFile = null;
        throw new IllegalStateException(
                "Assertion failed.  Internal locking error in " + getClass().getName() + '.');
    }
    final ExpandableProperties metaProperties = new ExpandableProperties();
    try {
        metaProperties.load(new FileInputStream(metaFile));
    } catch (final IOException ioe) {
        log.fatal("Failed to read meta props file '" + metaFile.getAbsolutePath() + "'", ioe);
        throw new IllegalStateException("Failed to read meta props file '" + metaFile.getAbsolutePath() + "'",
                ioe);
    }
    final Properties expandProps = new Properties();
    expandProps.setProperty("rtconfig.dir", rtConfigDir.getAbsolutePath());
    expandProps.setProperty("app.contextpath", contextPath);
    expandProps.setProperty("deployment.name", deploymentName);
    try {
        metaProperties.expand(expandProps); // Expand ${} properties
    } catch (final Throwable t) {
        log.fatal("Failed to expand properties in meta file '" + metaFile.getAbsolutePath() + "'", t);
        throw new IllegalStateException(
                "Failed to expand properties in meta file '" + metaFile.getAbsolutePath() + "'", t);
    }
    String requiredKeysString;
    requiredKeysString = sc.getInitParameter("required.metaprop.keys");
    if (requiredKeysString != null) {
        final Set<String> requiredKeys = new HashSet<String>(
                Arrays.asList(requiredKeysString.split("\\s*,\\s*", -1)));
        requiredKeys.removeAll(metaProperties.keySet());
        if (requiredKeys.size() > 0) {
            log.fatal("Meta properties file '" + metaFile.getAbsolutePath() + "' missing required property(s): "
                    + requiredKeys);
            throw new IllegalStateException("Meta properties file '" + metaFile.getAbsolutePath()
                    + "' missing required property(s): " + requiredKeys);
        }
    }
    sc.setAttribute("app.contextpath", contextPath);
    sc.setAttribute("deployment.name", deploymentName);
    sc.setAttribute("rtconfig.dir", rtConfigDir);
    sc.setAttribute("meta.properties", metaProperties);

    log.debug("'app.contextpath', 'rtconfig.dir', 'meta.properties' "
            + "successfully published to app context for " + deploymentName);
}

From source file:com.haulmont.cuba.web.sys.CubaVaadinServletService.java

public CubaVaadinServletService(VaadinServlet servlet, DeploymentConfiguration deploymentConfiguration)
        throws ServiceException {
    super(servlet, deploymentConfiguration);

    Configuration configuration = AppBeans.get(Configuration.NAME);
    webConfig = configuration.getConfig(WebConfig.class);
    webAuthConfig = configuration.getConfig(WebAuthConfig.class);
    testMode = configuration.getConfig(GlobalConfig.class).getTestMode();

    ServletContext sc = servlet.getServletContext();
    String resourcesTimestamp = sc.getInitParameter("webResourcesTs");
    if (StringUtils.isNotEmpty(resourcesTimestamp)) {
        this.webResourceTimestamp = resourcesTimestamp;
    } else {//from  ww w .  j a  va 2  s. c o  m
        this.webResourceTimestamp = "DEBUG";
    }

    addSessionInitListener(event -> {
        WrappedSession wrappedSession = event.getSession().getSession();
        wrappedSession.setMaxInactiveInterval(webConfig.getHttpSessionExpirationTimeoutSec());

        HttpSession httpSession = wrappedSession instanceof WrappedHttpSession
                ? ((WrappedHttpSession) wrappedSession).getHttpSession()
                : null;

        log.debug("HttpSession {} initialized, timeout={}sec", httpSession,
                wrappedSession.getMaxInactiveInterval());
    });

    addSessionDestroyListener(event -> {
        WrappedSession wrappedSession = event.getSession().getSession();
        HttpSession httpSession = wrappedSession instanceof WrappedHttpSession
                ? ((WrappedHttpSession) wrappedSession).getHttpSession()
                : null;

        log.debug("HttpSession destroyed: {}", httpSession);
        App app = event.getSession().getAttribute(App.class);
        if (app != null) {
            app.cleanupBackgroundTasks();
        }
    });

    setSystemMessagesProvider(systemMessagesInfo -> {
        Locale locale = systemMessagesInfo.getLocale();

        CustomizedSystemMessages msgs = new CustomizedSystemMessages();

        if (AppContext.isStarted()) {
            try {
                Messages messages = AppBeans.get(Messages.NAME);

                msgs.setInternalErrorCaption(messages.getMainMessage("internalErrorCaption", locale));
                msgs.setInternalErrorMessage(messages.getMainMessage("internalErrorMessage", locale));

                msgs.setCommunicationErrorCaption(messages.getMainMessage("communicationErrorCaption", locale));
                msgs.setCommunicationErrorMessage(messages.getMainMessage("communicationErrorMessage", locale));

                msgs.setSessionExpiredCaption(messages.getMainMessage("sessionExpiredErrorCaption", locale));
                msgs.setSessionExpiredMessage(messages.getMainMessage("sessionExpiredErrorMessage", locale));
            } catch (Exception e) {
                log.error("Unable to set system messages", e);
                throw new RuntimeException("Unable to set system messages. "
                        + "It usually happens when the middleware web application is not responding due to "
                        + "errors on start. See logs for details.", e);
            }
        }

        String redirectUri;
        if (RequestContext.get() != null) {
            HttpServletRequest request = RequestContext.get().getRequest();
            redirectUri = StringUtils.replace(request.getRequestURI(), "/UIDL", "");
        } else {
            String webContext = AppContext.getProperty("cuba.webContextName");
            redirectUri = "/" + webContext;
        }

        msgs.setInternalErrorURL(redirectUri + "?restartApp");

        return msgs;
    });
}