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:alpha.portal.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}//from w w w .j a v  a2s  . com
 */
@SuppressWarnings("unchecked")
public void contextInitialized(final ServletContextEvent event) {
    StartupListener.log.debug("Initializing context...");

    final ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*
     * String[] beans = ctx.getBeanDefinitionNames(); for (String bean :
     * beans) { log.debug(bean); }
     */

    PasswordEncoder passwordEncoder = null;
    try {
        final ProviderManager provider = (ProviderManager) ctx
                .getBean("org.springframework.security.authentication.ProviderManager#0");
        for (final Object o : provider.getProviders()) {
            final AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (final NoSuchBeanDefinitionException n) {
        StartupListener.log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (StartupListener.log.isDebugEnabled()) {
        StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        StartupListener.log.debug("Populating drop-downs...");
    }

    StartupListener.setupContext(context);
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Parse init parameter for integer value, returning default if not found or invalid
 *///from ww  w .j a  v  a  2  s  . c om
protected static int getIntInitParameter(ServletContext servletContext, String parameterName,
        int defaultValue) {
    final String parameterString = servletContext.getInitParameter(parameterName);
    if (parameterString != null && parameterString.trim().length() > 0) {
        try {
            return Integer.parseInt(parameterString);
        } catch (NumberFormatException e) {
            // Do nothing, return default value
        }
    }
    return defaultValue;
}

From source file:com.chilmers.configbootstrapper.ConfigServletContextListener.java

private void overrideDefaults(ServletContext ctx) {
    this.configLocationPropertyKey = ctx.getInitParameter(OVERRIDE_DEFAULT_CONFIG_LOCATION_PROPERTY_KEY_PARAM);
    if (StringUtils.isBlank(this.configLocationPropertyKey)) {
        this.configLocationPropertyKey = DEFAULT_CONFIG_LOCATION_PROPERTY_KEY;
    }/*from  w  w  w .j  a v  a2 s. co  m*/
    this.log4jConfigLocationPropertyKey = ctx
            .getInitParameter(OVERRIDE_DEFAULT_LOG4J_CONFIG_LOCATION_PROPERTY_KEY_PARAM);
    if (StringUtils.isBlank(this.log4jConfigLocationPropertyKey)) {
        this.log4jConfigLocationPropertyKey = DEFAULT_LOG4J_CONFIG_LOCATION_PROPERTY_KEY;
    }
    this.fallbackConfigLocation = ctx.getInitParameter(OVERRIDE_DEFAULT_FALLBACK_CONFIG_LOCATION_PARAM);
    if (StringUtils.isBlank(this.fallbackConfigLocation)) {
        this.fallbackConfigLocation = DEFAULT_FALLBACK_CONFIG_LOCATION;
    }
    this.applicationName = ctx.getInitParameter(OVERRIDE_DEFAULT_APPLICATION_NAME_PARAM);
    if (StringUtils.isBlank(this.applicationName)) {
        this.applicationName = ctx.getServletContextName();
    }
    if (StringUtils.isBlank(this.applicationName)) {
        this.applicationName = DEFAULT_APPLICATION_NAME;
    }
    configHelper = new ConfigHelper(applicationName);
}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testCreateRolePerms() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);
    ApplicationContext appContext = mock(ApplicationContext.class);

    Principal p = mock(Principal.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")).thenReturn(null);
    when(context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE))
            .thenReturn(appContext);//from ww  w  . j  av  a2s . co m
    when(context.getInitParameter("contextAuthConfigLocation")).thenReturn("somewhere");
    when(appContext.getResource("somewhere")).thenReturn(
            new DefaultResourceLoader().getResource("com/betfair/tornjak/monitor/overlay/auth.properties"));

    when(request.getUserPrincipal()).thenReturn(p);
    when(request.isUserInRole("jmxadmin")).thenReturn(true);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);

    assertThat(auth, notNullValue());
    assertThat("User should be authorised", auth.check(), equalTo(AUTHORISED));
}

From source file:org.opencb.opencga.server.rest.OpenCGAWSServer.java

private void init() {
    logger = LoggerFactory.getLogger("org.opencb.opencga.server.rest.OpenCGAWSServer");
    logger.info("========================================================================");
    logger.info("| Starting OpenCGA REST server, initializing OpenCGAWSServer");
    logger.info("| This message must appear only once.");

    // We must load the configuration files and init catalogManager, storageManagerFactory and Logger only the first time.
    // We first read 'config-dir' parameter passed
    ServletContext context = httpServletRequest.getServletContext();
    String configDirString = context.getInitParameter("config-dir");
    if (StringUtils.isEmpty(configDirString)) {
        // If not environment variable then we check web.xml parameter
        if (StringUtils.isNotEmpty(context.getInitParameter("OPENCGA_HOME"))) {
            configDirString = context.getInitParameter("OPENCGA_HOME") + "/conf";
        } else if (StringUtils.isNotEmpty(System.getenv("OPENCGA_HOME"))) {
            // If not exists then we try the environment variable OPENCGA_HOME
            configDirString = System.getenv("OPENCGA_HOME") + "/conf";
        } else {/*from  w ww  .j a va2s.  c  o m*/
            logger.error("No valid configuration directory provided!");
        }
    }

    // Check and execute the init methods
    java.nio.file.Path configDirPath = Paths.get(configDirString);
    if (configDirPath != null && Files.exists(configDirPath) && Files.isDirectory(configDirPath)) {
        logger.info("|  * Configuration folder: '{}'", configDirPath.toString());
        initOpenCGAObjects(configDirPath);

        // Required for reading the analysis.properties file.
        // TODO: Remove when analysis.properties is totally migrated to configuration.yml
        Config.setOpenCGAHome(configDirPath.getParent().toString());

        // TODO use configuration.yml for getting the server.log, for now is hardcoded
        logger.info("|  * Server logfile: " + configDirPath.getParent().resolve("logs").resolve("server.log"));
        initLogger(configDirPath.getParent().resolve("logs"));
    } else {
        logger.error("No valid configuration directory provided: '{}'", configDirPath.toString());
    }

    logger.info("========================================================================\n");
}

From source file:servlet.CinemaControl.java

protected void doListMSsOfCinemas(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_movieSessions = "SELECT * FROM MovieSession WHERE houseID = ?;";
    String db_q_movies = "SELECT * FROM Movie WHERE movieID = ?;";
    String db_q1_0 = "SELECT categoryName" + " FROM category c, movie_category mc, movie m"
            + " WHERE c.categoryID = mc.categoryID" + " AND m.movieID = mc.movieID" + " AND m.movieID = ?;";
    String db_q1_1 = "SELECT actorName" + " FROM actor a, movie_actor ma, movie m"
            + " WHERE a.actorID = ma.actorID" + " AND ma.movieID = m.movieID" + " AND m.movieID = ?;";
    String db_q1_2 = "SELECT image FROM movie m, movieImage mi" + " WHERE m.movieID = mi.movieID"
            + " AND m.movieID = ?;";
    String db_q1_3 = "SELECT video" + " FROM movie m, movieVideo mv" + " WHERE m.movieID = mv.movieID"
            + " AND m.movieID = ?;";

    try {//from  w  w  w .  j a v a  2 s  . co  m
        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("movieSessions", jsa2);
                    PreparedStatement statmt3 = conn.prepareStatement(db_q_movieSessions);
                    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));
                            }
                            String playtime = jso3.getString("playtime");
                            jso3.put("date", playtime.substring(0, 10));
                            jso3.put("time", playtime.subSequence(11, 16));
                            int movieID = Integer.parseInt(jso3.getString("movieID"));
                            JSONArray jsa3 = new JSONArray();
                            jso3.put("movies", jsa3);
                            PreparedStatement statmt4 = conn.prepareStatement(db_q_movies);
                            statmt4.setInt(1, movieID);
                            if (statmt4.execute()) {
                                ResultSet rs4 = statmt4.getResultSet();
                                ResultSetMetaData rsmd4 = rs4.getMetaData();
                                int numOfColumns4 = rsmd4.getColumnCount();
                                while (rs4.next()) {
                                    JSONObject jso4 = new JSONObject();
                                    jsa3.put(jso4);
                                    for (int l = 1; l <= numOfColumns4; l++) {
                                        jso4.put(rsmd4.getColumnLabel(l), rs4.getString(l));
                                    }

                                    //add categories
                                    JSONArray jsa1_0 = new JSONArray();
                                    jso4.put("categories", jsa1_0);
                                    PreparedStatement statmt1_0 = conn.prepareStatement(db_q1_0);
                                    statmt1_0.setInt(1, movieID);
                                    if (statmt1_0.execute()) {
                                        ResultSet rs1_0 = statmt1_0.getResultSet();
                                        while (rs1_0.next()) {
                                            jsa1_0.put(rs1_0.getString(1));
                                        }
                                    }

                                    //add actors
                                    JSONArray jsa1_1 = new JSONArray();
                                    jso4.put("actors", jsa1_1);
                                    PreparedStatement statmt1_1 = conn.prepareStatement(db_q1_1);
                                    statmt1_1.setInt(1, movieID);
                                    if (statmt1_1.execute()) {
                                        ResultSet rs1_1 = statmt1_1.getResultSet();
                                        while (rs1_1.next()) {
                                            jsa1_1.put(rs1_1.getString(1));
                                        }
                                    }

                                    //add images
                                    JSONArray jsa1_2 = new JSONArray();
                                    jso4.put("movieImages", jsa1_2);
                                    PreparedStatement statmt1_2 = conn.prepareStatement(db_q1_2);
                                    statmt1_2.setInt(1, movieID);
                                    if (statmt1_2.execute()) {
                                        ResultSet rs1_2 = statmt1_2.getResultSet();
                                        while (rs1_2.next()) {
                                            jsa1_2.put(rs1_2.getString(1));
                                        }
                                    }

                                    //add videos
                                    JSONArray jsa1_3 = new JSONArray();
                                    jso4.put("movieVideos", jsa1_3);
                                    PreparedStatement statmt1_3 = conn.prepareStatement(db_q1_3);
                                    statmt1_3.setInt(1, movieID);
                                    if (statmt1_3.execute()) {
                                        ResultSet rs1_3 = statmt1_3.getResultSet();
                                        while (rs1_3.next()) {
                                            jsa1_3.put(rs1_3.getString(1));
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
        }
        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.yes.cart.cluster.node.impl.AbstractWsNodeServiceImpl.java

void initNodeFromServletContext(final ServletContext servletContext) {

    final Enumeration parameters = servletContext.getInitParameterNames();
    while (parameters.hasMoreElements()) {

        final String key = String.valueOf(parameters.nextElement());
        final String value = servletContext.getInitParameter(key);

        configuration.put(key, value);//  w w  w .  j a  v a 2s .c  o  m

    }

    final String luceneDisabled = configuration.get(LUCENE_INDEX_DISABLED);
    final String luceneDisabledValue = luceneDisabled != null ? Boolean.valueOf(luceneDisabled).toString()
            : Boolean.FALSE.toString();
    configuration.put(LUCENE_INDEX_DISABLED, luceneDisabledValue);

    NodeImpl node = new NodeImpl(true, configuration.get(NODE_ID), configuration.get(NODE_TYPE),
            configuration.get(NODE_CONFIG), configuration.get(CLUSTER_ID),
            Boolean.valueOf(luceneDisabledValue));
    node.setChannel(configuration.get(CHANNEL_URI));
    this.node = node;
    this.cluster.add(node);

    LOG = LoggerFactory.getLogger(node.getClusterId() + "." + node.getNodeId());

    if (LOG.isInfoEnabled()) {

        final StringBuilder stats = new StringBuilder();

        stats.append("\nLoading configuration for node...");
        stats.append("\nNode: ").append(node.getId());

        for (final Map.Entry<String, String> entry : configuration.entrySet()) {
            stats.append('\n').append(entry.getKey()).append(": ").append(entry.getValue());
        }

        LOG.info(stats.toString());
    }

}

From source file:com.dominion.salud.pedicom.configuration.PEDICOMInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.scan("com.dominion.salud.pedicom.configuration");
    ctx.setServletContext(servletContext);
    PEDICOMConstantes._NOMBRE_CONFIG = servletContext.getInitParameter("NOMBRE_CONFIG");
    System.setProperty("pedicom.conf.home", findConfigurationAndLogger(ctx));
    ctx.refresh();/*from  ww w. j av a2  s . c om*/

    // Spring Dispatcher
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(ctx));
    dispatcher.setInitParameter("contextClass", ctx.getClass().getName());
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
    dispatcher.addMapping("/controller/*");
    servletContext.addListener(new ContextLoaderListener(ctx));

    // Configuracion general
    PEDICOMConstantes._HOME = StringUtils.endsWith(servletContext.getRealPath("/"), File.separator)
            ? servletContext.getRealPath("/")
            : servletContext.getRealPath("/") + File.separator;
    PEDICOMConstantes._CONF_HOME = ctx.getEnvironment().getProperty("pedicom.conf.home");
    PEDICOMConstantes._TEMP = PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "temp" + File.separator;
    PEDICOMConstantes._VERSION = ResourceBundle.getBundle("version").getString("version");
    PEDICOMConstantes._LOGS = PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "classes" + File.separator
            + "logs";
    PEDICOMConstantes._CONTEXT_NAME = servletContext.getServletContextName();
    PEDICOMConstantes._CONTEXT_PATH = servletContext.getContextPath();
    PEDICOMConstantes._CONTEXT_SERVER = servletContext.getServerInfo();
    PEDICOMConstantes._ENABLE_TECHNICAL_INFORMATION = StringUtils.isNotBlank(
            ResourceBundle.getBundle("application").getString("pedicom.enable.technical.information"))
                    ? Boolean.parseBoolean(ResourceBundle.getBundle("application")
                            .getString("pedicom.enable.technical.information"))
                    : false;
    PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = StringUtils
            .isNotBlank(ResourceBundle.getBundle("application").getString("pedicom_scheduler_send_mail_cron"))
                    ? PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = ResourceBundle.getBundle("application")
                            .getString("pedicom_scheduler_send_mail_cron")
                    : PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON;
    PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON = StringUtils.isNotBlank(
            ResourceBundle.getBundle("application").getString("pedicom_scheduler_update_existencias_cron"))
                    ? PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = ResourceBundle.getBundle("application")
                            .getString("pedicom_scheduler_update_existencias_cron")
                    : PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON;

    // Configuracion de LOGS DEL MODULO
    if (StringUtils.isBlank(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())) {
        ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE"))
                .setFile(PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "classes" + File.separator
                        + "logs" + File.separator + "mpr-desktop.log");
    }
    PEDICOMConstantes._LOGS = new File(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())
                    .getParent();

    Environment env = ctx.getEnvironment();

    XmlUnmarshaler xml = new XmlUnmarshaler();
    Datos datos = (Datos) xml.unmarshal();
    logger.info("          Datasources");
    for (Datasources dat : datos.getDatasources()) {
        if (dat.getNombreDatasource().equals("Central")) {
            PEDICOMConstantes.EXISTENCIAS_EXISTE = true;
        }
        logger.info("               codCentro: " + dat.getCodCentro());
        logger.info("               nombreDatasource: " + dat.getNombreDatasource());
        logger.info("               driverClassName: " + dat.getDriverClassName());
        logger.info("               jndi: " + dat.getJndi());
        logger.info("               url: " + dat.getUrl());
        logger.info("               username: " + dat.getUsername());
        logger.info("               usernameEmail: " + dat.getUsernameEmail());
        logger.info("               passwordEmail: " + dat.getPasswordEmail());
        logger.info("               from: " + dat.getFrom());
        logger.info("               host: " + dat.getHost());
        logger.info("               port: " + dat.getPort());
        logger.info("               TLS: " + dat.getTLS());
        logger.info("               SSL: " + dat.getSSL());
    }
    //        ctx.refresh();
    //        PropertyConfigurator.configureAndWatch("log4j");

    logger.info("          Configuracion general del sistema");
    logger.info("               pedicom.home: " + PEDICOMConstantes._HOME);
    logger.info("               pedicom.conf.home: " + PEDICOMConstantes._CONF_HOME);
    logger.info("               pedicom.temp: " + PEDICOMConstantes._TEMP);
    logger.info("               pedicom.version: " + PEDICOMConstantes._VERSION);
    logger.info("               pedicom.logs: " + PEDICOMConstantes._LOGS);
    logger.info("               pedicom.context.name: " + PEDICOMConstantes._CONTEXT_NAME);
    logger.info("               pedicom.context.path: " + PEDICOMConstantes._CONTEXT_PATH);
    logger.info("               pedicom.context.server: " + PEDICOMConstantes._CONTEXT_SERVER);
    logger.info("          Parametrizacion del sistema");
    logger.info("               pedicom.enable.technical.information: "
            + PEDICOMConstantes._ENABLE_TECHNICAL_INFORMATION);
    logger.info(
            "               pedicom_scheduler_send_mail_cron: " + PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON);
    logger.info("               pedicom_scheduler_update_existencias_cron: "
            + PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON);
    logger.info("     Modulo configurado correctamente");
    logger.info("MODULO INICIADO CORRECTAMENTE");
}

From source file:servlet.MovieControl.java

protected void doListMovies(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_q1 = "SELECT * FROM Movie;";
    String db_q1_0 = "SELECT categoryName" + " FROM category c, movie_category mc, movie m"
            + " WHERE c.categoryID = mc.categoryID" + " AND m.movieID = mc.movieID" + " AND m.movieID = ?;";
    String db_q1_1 = "SELECT actorName" + " FROM actor a, movie_actor ma, movie m"
            + " WHERE a.actorID = ma.actorID" + " AND ma.movieID = m.movieID" + " AND m.movieID = ?;";
    String db_q1_2 = "SELECT image FROM movie m, movieImage mi" + " WHERE m.movieID = mi.movieID"
            + " AND m.movieID = ?;";
    String db_q1_3 = "SELECT video" + " FROM movie m, movieVideo mv" + " WHERE m.movieID = mv.movieID"
            + " AND m.movieID = ?;";
    String db_q2 = "SELECT DISTINCT c.cinemaID, c.cinemaName, c.cinemaAddress, c.numOfVote, c.rank, c.image1"
            + " FROM Cinema c, Movie m, House h, MovieSession ms" + " WHERE h.cinemaID = c.cinemaID"
            + " AND h.houseID = ms.houseID" + " AND ms.movieID = m.movieID" + " AND ms.movieID = ?;";
    String db_q3 = "SELECT DISTINCT h.houseID, h.cinemaID, h.seatNums"
            + " FROM House h, Movie m, MovieSession ms" + " WHERE h.cinemaID = ?"
            + " AND h.houseID = ms.houseID" + " AND ms.movieID = m.movieID" + " AND m.movieID = ?;";
    String db_q4 = "SELECT ms.*" + " FROM movieSession ms, house h" + " WHERE ms.houseID = h.houseID"
            + " AND h.houseID = ?" + " AND ms.movieID = ?;";

    try {//  w ww.j av a 2s .  c om
        Class.forName(db_driver);
        Connection conn = DriverManager.getConnection(db_url, db_user, db_password);
        Statement statmt1 = conn.createStatement();
        ResultSet rs1 = statmt1.executeQuery(db_q1);
        ResultSetMetaData rsmd1 = rs1.getMetaData();
        int numOfColumns1 = rsmd1.getColumnCount();
        JSONObject jso0 = new JSONObject();
        JSONArray jsa0 = new JSONArray();
        jso0.put("movies", jsa0);
        while (rs1.next()) {
            JSONObject jso1 = new JSONObject();
            jsa0.put(jso1);
            for (int i = 1; i <= numOfColumns1; i++) {
                //add movie.*
                jso1.put(rsmd1.getColumnName(i), rs1.getString(i));
            }
            int movieID = rs1.getInt("movieID");
            //add categories
            JSONArray jsa1_0 = new JSONArray();
            jso1.put("categories", jsa1_0);
            PreparedStatement statmt1_0 = conn.prepareStatement(db_q1_0);
            statmt1_0.setInt(1, movieID);
            if (statmt1_0.execute()) {
                ResultSet rs1_0 = statmt1_0.getResultSet();
                while (rs1_0.next()) {
                    jsa1_0.put(rs1_0.getString(1));
                }
            }

            //add actors
            JSONArray jsa1_1 = new JSONArray();
            jso1.put("actors", jsa1_1);
            PreparedStatement statmt1_1 = conn.prepareStatement(db_q1_1);
            statmt1_1.setInt(1, movieID);
            if (statmt1_1.execute()) {
                ResultSet rs1_1 = statmt1_1.getResultSet();
                while (rs1_1.next()) {
                    jsa1_1.put(rs1_1.getString(1));
                }
            }

            //add images
            JSONArray jsa1_2 = new JSONArray();
            jso1.put("movieImages", jsa1_2);
            PreparedStatement statmt1_2 = conn.prepareStatement(db_q1_2);
            statmt1_2.setInt(1, movieID);
            if (statmt1_2.execute()) {
                ResultSet rs1_2 = statmt1_2.getResultSet();
                while (rs1_2.next()) {
                    jsa1_2.put(rs1_2.getString(1));
                }
            }

            //add videos
            JSONArray jsa1_3 = new JSONArray();
            jso1.put("movieVideos", jsa1_3);
            PreparedStatement statmt1_3 = conn.prepareStatement(db_q1_3);
            statmt1_3.setInt(1, movieID);
            if (statmt1_3.execute()) {
                ResultSet rs1_3 = statmt1_3.getResultSet();
                while (rs1_3.next()) {
                    jsa1_3.put(rs1_3.getString(1));
                }
            }

            //add cinemas
            JSONArray jsa1 = new JSONArray();
            jso1.put("cinemas", jsa1);
            PreparedStatement statmt2 = conn.prepareStatement(db_q2);
            statmt2.setInt(1, movieID);
            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++) {
                        //add cinema.*
                        jso2.put(rsmd2.getColumnName(j), rs2.getString(j));
                    }
                    //add houses
                    JSONArray jsa2 = new JSONArray();
                    jso2.put("houses", jsa2);
                    PreparedStatement statmt3 = conn.prepareStatement(db_q3);
                    int cinemaID = rs2.getInt("cinemaID");
                    statmt3.setInt(1, cinemaID);
                    statmt3.setInt(2, movieID);
                    if (statmt3.execute()) {
                        ResultSet rs3 = statmt3.executeQuery();
                        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++) {
                                //add house.*
                                jso3.put(rsmd3.getColumnName(k), rs3.getString(k));
                            }
                            //add moviesessions
                            JSONArray jsa3 = new JSONArray();
                            jso3.put("movieSessions", jsa3);
                            PreparedStatement statmt4 = conn.prepareStatement(db_q4);
                            int houseID = rs3.getInt("houseID");
                            statmt4.setInt(1, houseID);
                            statmt4.setInt(2, movieID);
                            if (statmt4.execute()) {
                                ResultSet rs4 = statmt4.getResultSet();
                                ResultSetMetaData rsmd4 = rs4.getMetaData();
                                int numOfColumns4 = rsmd4.getColumnCount();
                                while (rs4.next()) {
                                    JSONObject jso4 = new JSONObject();
                                    jsa3.put(jso4);
                                    for (int l = 1; l < numOfColumns4; l++) {
                                        //add moviesession.*
                                        jso4.put(rsmd4.getColumnName(l), rs4.getString(l));
                                    }
                                    // format playtime
                                    String playtime = jso4.getString("playtime");
                                    jso4.put("playdate", playtime.substring(0, 10));
                                    jso4.put("time", playtime.substring(11, 16));
                                }
                                rs4.close();
                            }

                        }
                        rs3.close();
                    }

                }
                rs2.close();
            }

            // format value
            jso1.put("releaseDate", rs1.getString("releaseDate").substring(0, 10));
        }
        rs1.close();
        out.println(jso0.toString());
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(MovieControl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(MovieControl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(MovieControl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:servlet.MovieControl.java

protected void doListMovieByID(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_q1 = "SELECT * FROM Movie WHERE movieID = ?;";
    String db_q1_0 = "SELECT categoryName" + " FROM category c, movie_category mc, movie m"
            + " WHERE c.categoryID = mc.categoryID" + " AND m.movieID = mc.movieID" + " AND m.movieID = ?;";
    String db_q1_1 = "SELECT actorName" + " FROM actor a, movie_actor ma, movie m"
            + " WHERE a.actorID = ma.actorID" + " AND ma.movieID = m.movieID" + " AND m.movieID = ?;";
    String db_q1_2 = "SELECT image FROM movie m, movieImage mi" + " WHERE m.movieID = mi.movieID"
            + " AND m.movieID = ?;";
    String db_q1_3 = "SELECT video" + " FROM movie m, movieVideo mv" + " WHERE m.movieID = mv.movieID"
            + " AND m.movieID = ?;";
    String db_q2 = "SELECT DISTINCT c.cinemaID, c.cinemaName, c.cinemaAddress, c.numOfVote, c.rank, c.image1"
            + " FROM Cinema c, Movie m, House h, MovieSession ms" + " WHERE h.cinemaID = c.cinemaID"
            + " AND h.houseID = ms.houseID" + " AND ms.movieID = m.movieID" + " AND ms.movieID = ?;";
    String db_q3 = "SELECT DISTINCT h.houseID, h.cinemaID, h.seatNums"
            + " FROM House h, Movie m, MovieSession ms" + " WHERE h.cinemaID = ?"
            + " AND h.houseID = ms.houseID" + " AND ms.movieID = m.movieID" + " AND m.movieID = ?;";
    String db_q4 = "SELECT ms.*" + " FROM movieSession ms, house h" + " WHERE ms.houseID = h.houseID"
            + " AND h.houseID = ?" + " AND ms.movieID = ?;";

    int movieID = Integer.parseInt(request.getParameter("movieID"));

    try {//from w w  w .ja  va  2  s  .  c  o m
        Class.forName(db_driver);
        Connection conn = DriverManager.getConnection(db_url, db_user, db_password);
        PreparedStatement statmt1 = conn.prepareStatement(db_q1);
        statmt1.setInt(1, movieID);
        statmt1.execute();
        ResultSet rs1 = statmt1.getResultSet();
        ResultSetMetaData rsmd1 = rs1.getMetaData();
        int numOfColumns1 = rsmd1.getColumnCount();
        JSONObject jso0 = new JSONObject();
        JSONArray jsa0 = new JSONArray();
        jso0.put("movies", jsa0);
        if (rs1.next()) {
            JSONObject jso1 = new JSONObject();
            jsa0.put(jso1);
            for (int i = 1; i <= numOfColumns1; i++) {
                //add movie.*
                jso1.put(rsmd1.getColumnName(i), rs1.getString(i));
            }
            //add categories
            JSONArray jsa1_0 = new JSONArray();
            jso1.put("categories", jsa1_0);
            PreparedStatement statmt1_0 = conn.prepareStatement(db_q1_0);
            statmt1_0.setInt(1, movieID);
            if (statmt1_0.execute()) {
                ResultSet rs1_0 = statmt1_0.getResultSet();
                while (rs1_0.next()) {
                    jsa1_0.put(rs1_0.getString(1));
                }
            }

            //add actors
            JSONArray jsa1_1 = new JSONArray();
            jso1.put("actors", jsa1_1);
            PreparedStatement statmt1_1 = conn.prepareStatement(db_q1_1);
            statmt1_1.setInt(1, movieID);
            if (statmt1_1.execute()) {
                ResultSet rs1_1 = statmt1_1.getResultSet();
                while (rs1_1.next()) {
                    jsa1_1.put(rs1_1.getString(1));
                }
            }

            //add images
            JSONArray jsa1_2 = new JSONArray();
            jso1.put("movieImages", jsa1_2);
            PreparedStatement statmt1_2 = conn.prepareStatement(db_q1_2);
            statmt1_2.setInt(1, movieID);
            if (statmt1_2.execute()) {
                ResultSet rs1_2 = statmt1_2.getResultSet();
                while (rs1_2.next()) {
                    jsa1_2.put(rs1_2.getString(1));
                }
            }

            //add videos
            JSONArray jsa1_3 = new JSONArray();
            jso1.put("movieVideos", jsa1_3);
            PreparedStatement statmt1_3 = conn.prepareStatement(db_q1_3);
            statmt1_3.setInt(1, movieID);
            if (statmt1_3.execute()) {
                ResultSet rs1_3 = statmt1_3.getResultSet();
                while (rs1_3.next()) {
                    jsa1_3.put(rs1_3.getString(1));
                }
            }

            //add cinemas
            JSONArray jsa1 = new JSONArray();
            jso1.put("cinemas", jsa1);
            PreparedStatement statmt2 = conn.prepareStatement(db_q2);
            statmt2.setInt(1, movieID);
            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++) {
                        //add cinema.*
                        jso2.put(rsmd2.getColumnName(j), rs2.getString(j));
                    }
                    //add houses
                    JSONArray jsa2 = new JSONArray();
                    jso2.put("houses", jsa2);
                    PreparedStatement statmt3 = conn.prepareStatement(db_q3);
                    int cinemaID = rs2.getInt("cinemaID");
                    statmt3.setInt(1, cinemaID);
                    statmt3.setInt(2, movieID);
                    if (statmt3.execute()) {
                        ResultSet rs3 = statmt3.executeQuery();
                        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++) {
                                //add house.*
                                jso3.put(rsmd3.getColumnName(k), rs3.getString(k));
                            }
                            //add moviesessions
                            JSONArray jsa3 = new JSONArray();
                            jso3.put("movieSessions", jsa3);
                            PreparedStatement statmt4 = conn.prepareStatement(db_q4);
                            int houseID = rs3.getInt("houseID");
                            statmt4.setInt(1, houseID);
                            statmt4.setInt(2, movieID);
                            if (statmt4.execute()) {
                                ResultSet rs4 = statmt4.getResultSet();
                                ResultSetMetaData rsmd4 = rs4.getMetaData();
                                int numOfColumns4 = rsmd4.getColumnCount();
                                while (rs4.next()) {
                                    JSONObject jso4 = new JSONObject();
                                    jsa3.put(jso4);
                                    for (int l = 1; l < numOfColumns4; l++) {
                                        //add moviesession.*
                                        jso4.put(rsmd4.getColumnName(l), rs4.getString(l));
                                    }
                                    // format playtime
                                    String playtime = jso4.getString("playtime");
                                    jso4.put("playdate", playtime.substring(0, 10));
                                    jso4.put("time", playtime.substring(11, 16));
                                }
                                rs4.close();
                            }

                        }
                        rs3.close();
                    }

                }
                rs2.close();
            }

            // format value
            jso1.put("releaseDate", rs1.getString("releaseDate").substring(0, 10));
        }
        rs1.close();
        out.println(jso0.toString());
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(MovieControl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(MovieControl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(MovieControl.class.getName()).log(Level.SEVERE, null, ex);
    }
}