/** * Creates a new job on the Links Discovery Component. * * @param id the job identifier associated with this instance. * @return a response which includes the info of the new job. * @since 1.0 */ @POST @Path("/jobs") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response newJob( @Context final HttpServletRequest request, @FormParam("jobid") final Integer jobid) { LOGGER.debug(MessageCatalog._00021_NEW_JOB_REQUEST); if (jobid == null) { LOGGER.error(MessageCatalog._00022_MISSING_INPUT_PARAM, "jobid"); return Response.status(Status.BAD_REQUEST).build(); } // Get configuration parameters final DBConnectionManager dbConn = (DBConnectionManager) context.getAttribute("db"); final JobConfiguration jobConf = dbConn.getJobConfiguration(jobid); if (jobConf == null) { LOGGER.error(MessageCatalog._00023_JOB_CONFIGURATION_NOT_FOUND, jobid); return Response.status(Status.BAD_REQUEST).build(); } final DDBBParams ddbbParams = new DDBBParams(); ddbbParams.setUsername(context.getInitParameter("ddbb.username")); ddbbParams.setPassword(context.getInitParameter("ddbb.password")); ddbbParams.setDriverClassName(context.getInitParameter("ddbb.driverClassName")); ddbbParams.setUrl(context.getInitParameter("ddbb.url")); // Program linking processes final LinksDiscovery linksDisc = new LinksDiscovery(); final Job job = linksDisc.programLinkingProcesses(jobConf, dbConn, ddbbParams); return Response.created(uriInfo.getAbsolutePathBuilder().build()).entity(job).build(); }
/** * Get the data path to be used for this application. By default the servlet context * init-parameter {@link #INIT_PARAMETER_DATA_PATH} is evaluated. If non is present, the servlet * context path is used. * * @param aSC The servlet context. Never <code>null</code>. * @return The data path to use. May neither be <code>null</code> nor empty. */ @Nonnull @Nonempty @OverrideOnDemand protected String getDataPath(@Nonnull final ServletContext aSC) { String sDataPath = aSC.getInitParameter(INIT_PARAMETER_DATA_PATH); if (StringHelper.hasNoText(sDataPath)) { // Use legacy parameter name sDataPath = aSC.getInitParameter("storagePath"); if (StringHelper.hasText(sDataPath)) { s_aLogger.error( "You are using the old 'storagePath' parameter. Please use '" + INIT_PARAMETER_DATA_PATH + "' instead!"); } } if (StringHelper.hasNoText(sDataPath)) { // No storage path provided in web.xml sDataPath = getServletContextPath(aSC); if (GlobalDebug.isDebugMode() && s_aLogger.isInfoEnabled()) s_aLogger.info( "No servlet context init-parameter '" + INIT_PARAMETER_DATA_PATH + "' found! Defaulting to servlet context path '" + sDataPath + "'"); } return sDataPath; }
/** * Load config. * * @param servletContext the servlet context * @return the configuration */ Configuration loadConfig(ServletContext servletContext) { String handlers = servletContext.getInitParameter(ContextConfigParams.PARAM_HANDLERS); String layout = servletContext.getInitParameter(ContextConfigParams.PARAM_LAYOUT); String filters = servletContext.getInitParameter(ContextConfigParams.PARAM_FILTERS); String options = servletContext.getInitParameter(ContextConfigParams.PARAM_OPTIONS); String metaData = servletContext.getInitParameter(ContextConfigParams.PARAM_META_DATA); String properties = servletContext.getInitParameter(ContextConfigParams.PARAM_PROPERTIES); Configuration config = Configuration.INSTANCE; if (handlers != null && !handlers.equals("")) { config.setHandlers(new ReflectUtil<Handler>().getNewInstanceList(handlers.split(";"))); } config.setLayout(new ReflectUtil<Layout>().getNewInstance(layout)); if (filters != null && !filters.equals("")) { config.setFilters(new ReflectUtil<AuditEventFilter>().getNewInstanceList(filters.split(";"))); } config.setCommands(options); config.setMetaData(new ReflectUtil<MetaData>().getNewInstance(metaData)); if (properties != null && !properties.equals("")) { String[] propertiesList = properties.split(";"); for (String property : propertiesList) { String[] keyValue = property.split(":"); config.addProperty(keyValue[0], keyValue[1]); } } return config; }
@Override public void contextInitialized(ServletContextEvent sce) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated // methods, choose Tools | Templates. ServletContext sc = sce.getServletContext(); String db = sc.getInitParameter("Database"); String user = sc.getInitParameter("User"); String password = sc.getInitParameter("Password"); // String vendor = sc.getInitParameter("vendor"); try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/" + db.trim(), user.trim(), password.trim()); // conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db.trim(), "root", ""); } catch (ClassNotFoundException | SQLException e) { sc.setAttribute("error", e); } // DBBean dbBean = new DBBean(); // dbBean.setTable(table); // sc.setAttribute("db", dbBean); sc.setAttribute("connection", conn); }
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // ServletConfig conf=getServletConfig(); PrintWriter out = response.getWriter(); ServletContext ctx = getServletContext(); String place = ctx.getInitParameter("pl"); String email = ctx.getInitParameter("em"); String name = ctx.getInitParameter("nm"); Student s = new Student(); s.id = 12; s.name = "raju"; ctx.setAttribute("stu", s); String[] frtArr = {"mango", "orange", "grapes"}; ctx.setAttribute("arr", frtArr); out.println( "<html><body bgcolor='yellow'>" + "<h1>ONE</h1>" + "<p>" + place + "<br>" + email + "<br>" + name + "</p>" + "<a href='TwoServ'>two</a>" + "</body></html>"); out.close(); }
/** * Used to lookup parent spring ApplicationContext. This allows a parent spring ApplicatonContet * to be provided in the same way you would configure a parent ApplicationContext for a spring * WebAppplicationContext * * @param servletContext * @return * @throws BeansException */ protected ApplicationContext loadParentContext(ServletContext servletContext) throws BeansException { ApplicationContext parentContext = null; String locatorFactorySelector = servletContext.getInitParameter(ContextLoader.LOCATOR_FACTORY_SELECTOR_PARAM); String parentContextKey = servletContext.getInitParameter(ContextLoader.LOCATOR_FACTORY_KEY_PARAM); if (parentContextKey != null) { // locatorFactorySelector may be null, indicating the default // "classpath*:beanRefContext.xml" BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance(locatorFactorySelector); if (logger.isDebugEnabled()) { logger.debug( "Getting parent context definition: using parent context key of '" + parentContextKey + "' with BeanFactoryLocator"); } parentContext = (ApplicationContext) locator.useBeanFactory(parentContextKey).getFactory(); } return parentContext; }
public void init() { ctx = this.getServletContext(); server = ctx.getInitParameter("server"); dbname = ctx.getInitParameter("dbname"); user = ctx.getInitParameter("user"); pwd = ctx.getInitParameter("password"); }
public static GrailsRuntimeConfigurator determineGrailsRuntimeConfiguratorFromServletContext( GrailsApplication application, ServletContext servletContext, ApplicationContext parent) { GrailsRuntimeConfigurator configurator = null; if (servletContext.getInitParameter(GrailsRuntimeConfigurator.BEAN_ID + "Class") != null) { // try to load configurator class as specified in servlet context String configuratorClassName = servletContext.getInitParameter(GrailsRuntimeConfigurator.BEAN_ID + "Class").toString(); Class<?> configuratorClass = null; try { configuratorClass = ClassUtils.forName(configuratorClassName, application.getClassLoader()); } catch (Exception e) { String msg = "failed to create Grails runtime configurator as specified in web.xml: " + configuratorClassName; LOG.error("[GrailsContextLoader] " + msg, e); throw new IllegalArgumentException(msg); } if (!GrailsRuntimeConfigurator.class.isAssignableFrom(configuratorClass)) { throw new IllegalArgumentException( "class " + configuratorClassName + " is not assignable to " + GrailsRuntimeConfigurator.class.getName()); } Constructor<?> constr = ClassUtils.getConstructorIfAvailable( configuratorClass, GrailsApplication.class, ApplicationContext.class); configurator = (GrailsRuntimeConfigurator) BeanUtils.instantiateClass(constr, application, parent); } return configurator; }
/*1.初始化servlet 容器上下文*/ public void contextInitialized(ServletContextEvent sce) { sc = sce.getServletContext(); contextPath = sc.getContextPath(); realPath = sc.getRealPath("/") + "/"; String quartz_configFile = sc.getInitParameter("quartz-config-file"); URL quartzConfigFileURL = Thread.currentThread().getContextClassLoader().getResource(quartz_configFile); if (null != quartzConfigFileURL) { logger.info("quartz定时调度线程信息:" + quartzConfigFileURL.getFile()); } String shutdownUnload = sc.getInitParameter("shutdown-on-unload"); if (null != shutdownUnload) { performShutdown = Boolean.valueOf(shutdownUnload).booleanValue(); } /*参数配置*/ StdSchedulerFactory factory; try { if (quartz_configFile != null) factory = new StdSchedulerFactory(quartz_configFile); else factory = new StdSchedulerFactory(); scheduler = factory.getScheduler(); // 添加quartz任务监听日志 scheduler.addSchedulerListener(new SchedulerListenerImpl()); scheduler.addJobListener(new JobListenerImpl()); scheduler.addTriggerListener(new TriggerListenerImpl()); scheduler.start(); } catch (Exception e) { e.printStackTrace(); } }
public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); String appPath = event.getServletContext().getRealPath(""); String config = context.getInitParameter(CONFIG_PARAM); String extensions = context.getInitParameter(CONFIG_EXTENSIONS_PARAM); if (config == null) { throw new RuntimeException( String.format("failure to specify context init-param - %s", CONFIG_PARAM)); } if (extensions == null) { throw new RuntimeException( String.format("failure to specify context init-param - %s", CONFIG_EXTENSIONS_PARAM)); } InputStream is = null; Properties properties = new Properties(); try { is = getResourceStream(appPath + config, context); properties.load(is); addCsrfExcludeProperties(appPath + extensions, properties); CsrfGuard.load(properties); } catch (Exception e) { throw new RuntimeException(e); } finally { Streams.close(is); } String printConfig = context.getInitParameter(CONFIG_PRINT_PARAM); if (printConfig != null && Boolean.parseBoolean(printConfig)) { context.log(CsrfGuard.getInstance().toString()); } }
public void contextInitialized(ServletContextEvent event) { this.context = event.getServletContext(); RepositorySystem sys = newRepositorySystem(); // setting repository system this.context.setAttribute("RepositorySystem", sys); Settings settings = null; try { settings = loadSettings( context.getInitParameter("user-settings"), context.getInitParameter("global-settings")); } catch (SettingsBuildingException e) { this.context.log(e.getMessage(), e); } List<RemoteRepository> repos = new ArrayList<RemoteRepository>(); RemoteRepository central = new RemoteRepository("central", "default", getDefaultRemoteRepository()); this.context.log("using remote repo : " + central.getUrl()); repos.add(central); if (context.getInitParameter("snapshots-remote-repo") != null) { this.context.log( "using snapshot remote repo : " + context.getInitParameter("snapshots-remote-repo")); RemoteRepository snaps = new RemoteRepository( "snapshot", "default", context.getInitParameter("snapshots-remote-repo")); snaps.setPolicy(true, null); repos.add(snaps); } // setting remote repositories this.context.setAttribute("repositories", repos); // setting default session this.context.setAttribute("session", newSystemSession(sys, settings)); }
/** * The doPost method of the servlet. <br> * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext ctx = getServletContext(); driver = ctx.getInitParameter("driver"); url = ctx.getInitParameter("url"); dname = ctx.getInitParameter("dname"); dpass = ctx.getInitParameter("dpass"); String target = "AdminHome.jsp?status=Password Changed Failed"; HttpSession session = request.getSession(); try { System.out.println("request.getParameter(isbn)" + request.getParameter("isbn")); Class.forName(driver); con = DriverManager.getConnection(url, dname, dpass); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String stuid = request.getParameter("stuid"); String newpass = request.getParameter("newpass"); Statement st = con.createStatement(); int i = st.executeUpdate( "update lms_login set password='******' where user_id='" + stuid + "'"); if (i > 0) target = "AdminHome.jsp?status=Password Changed Success"; else target = "AdminHome.jsp?status=Password Changed Failed"; } catch (Exception e) { e.printStackTrace(); target = "AdminHome.jsp?status=Password Changed Failed"; } response.sendRedirect(target); }
@Override public void contextInitialized(ServletContextEvent evt) { try { ServletContext context = evt.getServletContext(); String awsAccessKey = ParamUtils.coalesce( context.getInitParameter(ServletInitOptions.AWS_ACCESS_KEY), System.getenv().get(ServletInitOptions.AWS_ACCESS_KEY)); String awsSecretKey = ParamUtils.coalesce( context.getInitParameter(ServletInitOptions.AWS_SECRET_KEY), System.getenv().get(ServletInitOptions.AWS_SECRET_KEY)); awsCredentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); Stage stage = ParamUtils.asEnum( Stage.class, context.getInitParameter(ServletInitOptions.GUICE_STAGE), Stage.PRODUCTION); Injector injector = getInjector(context, stage); context.setAttribute(INJECTOR_NAME, injector); } catch (Throwable t) { log.fatal("DI Initialization Failed!", t); } }
/* * Populates taglib map described in web.xml. * * This is not kept in sync with o.a.c.startup.TldConfig as the Jasper only * needs the URI to TLD mappings from scan web.xml whereas TldConfig needs * to scan the actual TLD files. */ private void tldScanWebXml() throws Exception { WebXml webXml = null; try { webXml = new WebXml(ctxt); if (webXml.getInputSource() == null) { return; } boolean validate = Boolean.parseBoolean(ctxt.getInitParameter(Constants.XML_VALIDATION_TLD_INIT_PARAM)); String blockExternalString = ctxt.getInitParameter(Constants.XML_BLOCK_EXTERNAL_INIT_PARAM); boolean blockExternal; if (blockExternalString == null) { blockExternal = Constants.IS_SECURITY_ENABLED; } else { blockExternal = Boolean.parseBoolean(blockExternalString); } // Parse the web application deployment descriptor ParserUtils pu = new ParserUtils(validate, blockExternal); TreeNode webtld = null; webtld = pu.parseXMLDocument(webXml.getSystemId(), webXml.getInputSource()); // Allow taglib to be an element of the root or jsp-config (JSP2.0) TreeNode jspConfig = webtld.findChild("jsp-config"); if (jspConfig != null) { webtld = jspConfig; } Iterator<TreeNode> taglibs = webtld.findChildren("taglib"); while (taglibs.hasNext()) { // Parse the next <taglib> element TreeNode taglib = taglibs.next(); String tagUri = null; String tagLoc = null; TreeNode child = taglib.findChild("taglib-uri"); if (child != null) tagUri = child.getBody(); child = taglib.findChild("taglib-location"); if (child != null) tagLoc = child.getBody(); // Save this location if appropriate if (tagLoc == null) continue; if (uriType(tagLoc) == NOROOT_REL_URI) tagLoc = "/WEB-INF/" + tagLoc; TldLocation location; if (tagLoc.endsWith(JAR_EXT)) { location = new TldLocation("META-INF/taglib.tld", ctxt.getResource(tagLoc).toString()); } else { location = new TldLocation(tagLoc); } mappings.put(tagUri, location); } } finally { if (webXml != null) { webXml.close(); } } }
public GmailMailer(ServletContext context) { SMTP_HOST_NAME = "gmail-smtp.l.google.com"; String[] mailString = context.getInitParameter("EMail").split("\\?pwd="); SMTP_AUTH_USER = mailString[0]; SMTP_AUTH_PWD = mailString[1]; DOMAIN = context.getInitParameter("Domain"); SERVER_NAME = context.getInitParameter("ServerName"); }
public void init() { // reads SMTP server setting from web.xml fil ServletContext context = getServletContext(); host = context.getInitParameter("host"); port = context.getInitParameter("port"); user = context.getInitParameter("user"); pass = context.getInitParameter("pass"); }
private String getParameter(String name, String defaultValue) { assert name != null; assert defaultValue != null; if (context.getInitParameter(name) != null) { return context.getInitParameter(name); } else { return defaultValue; } }
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); File homeDir = null; if (servletContext.getAttribute("homedir") != null) { homeDir = new File((String) servletContext.getAttribute("homedir")); } if (homeDir == null && servletContext.getInitParameter("homedir") != null) { homeDir = new File(servletContext.getInitParameter("homedir")); } boolean autoMigrate = false; if (servletContext.getAttribute("autoMigrate") != null) { autoMigrate = (boolean) servletContext.getAttribute("autoMigrate"); } if (autoMigrate == false && servletContext.getInitParameter("autoMigrate") != null) { autoMigrate = Boolean.valueOf(servletContext.getInitParameter("autoMigrate")); } String realPath = servletContext.getRealPath("/"); if (!realPath.endsWith("/")) { realPath = realPath + "/"; } File baseDir = new File(realPath + "www/WEB-INF"); if (homeDir == null) { homeDir = baseDir; } ResourceFetcher resourceFetcher = new WarResourceFetcher(servletContext, homeDir); BimServerConfig config = new BimServerConfig(); config.setAutoMigrate(autoMigrate); config.setHomeDir(homeDir); config.setResourceFetcher(resourceFetcher); config.setClassPath(makeClassPath(resourceFetcher.getFile("lib"))); config.setStartEmbeddedWebServer(false); bimServer = new BimServer(config); Logger LOGGER = LoggerFactory.getLogger(WarServerInitializer.class); LOGGER.info("Servlet Context Name: " + servletContext.getServletContextName()); File file = resourceFetcher.getFile("plugins"); try { bimServer.getPluginManager().loadAllPluginsFromDirectoryOfJars(file); bimServer.start(); } catch (ServerException e) { LOGGER.error("", e); } catch (DatabaseInitException e) { LOGGER.error("", e); } catch (BimserverDatabaseException e) { LOGGER.error("", e); } catch (PluginException e) { LOGGER.error("", e); } catch (DatabaseRestartRequiredException e) { LOGGER.error("", e); } servletContext.setAttribute("bimserver", bimServer); }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") public void contextInitialized(ServletContextEvent event) { log.debug("Initializing context..."); 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)); } ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); /*String[] beans = ctx.getBeanDefinitionNames(); for (String bean : beans) { log.debug(bean); }*/ PasswordEncoder passwordEncoder = null; try { ProviderManager provider = (ProviderManager) ctx.getBean("org.springframework.security.authentication.ProviderManager#0"); for (Object o : provider.getProviders()) { 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 (NoSuchBeanDefinitionException n) { 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 (log.isDebugEnabled()) { log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled")); if (passwordEncoder != null) { log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName()); } log.debug("Populating drop-downs..."); } setupContext(context); }
public Connection getCon() throws Exception { ServletContext ctx = Config.getServletContext(); dbUrl = ctx.getInitParameter("UserDburl"); dbUserName = ctx.getInitParameter("dbUserName"); dbPassword = ctx.getInitParameter("dbPassword"); jdbcName = ctx.getInitParameter("jdbcName"); Class.forName(jdbcName); Connection con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword); return con; }
private DatabaseQueryExecutor initDatabaseConnection(ServletContext ctx) { String url = ctx.getInitParameter("dbURL"); String user = ctx.getInitParameter("dbUser"); String pass = ctx.getInitParameter("dbPassword"); // Java trickery to get round the password being set to nothing if (pass.equals("null")) { pass = ""; } DatabaseQueryExecutor db = new DatabaseQueryExecutor(url, user, pass); return db; }
public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); String emailAddress = context.getInitParameter("emailAddress"); String emailPassword = context.getInitParameter("emailPassword"); if (emailAddress == null || emailPassword == null) { throw new IllegalArgumentException("emailAddress or emailPassword not specified"); } Authenticator emailAuthenticator = new EmailAuthenticator(emailAddress, emailPassword); emailTimer = new Timer("Email decoder timer", true); emailTimer.schedule( new DecodeEmailTask(emailAddress, emailAuthenticator), 0L, EMAIL_CHECK_INTERVAL); }
/* * (non-Javadoc) * * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent sce) { ServletContext servletContext = sce.getServletContext(); String location = servletContext.getInitParameter(THIRD_LIB_PATH); // 判断配置的propertiesConfigLocation是否为空 if (StringUtils.hasText(location)) { if (location.startsWith(FILE_URL_PREFIX)) { location = location.substring(FILE_URL_PREFIX.length()); } else if (location.startsWith(CLASSPATH_URL_PREFIX)) { // 如果配置的是ClassPath方式,在location中取出classpath: location = location.substring(CLASSPATH_URL_PREFIX.length()); URL url = getDefaultClassLoader().getResource(location); location = url.getFile(); } else if (!StartupListener.isUrl(location)) { if (!location.startsWith("/")) { location = "/" + location; } // 根据serlvet上下文获取文件真实地址 location = servletContext.getRealPath(location); } // 获取加载间隔时长 String intervalString = servletContext.getInitParameter(THIRD_LIB_REFRESH_INTERVAL); // 加载Lib文件 ClassLoaderUtil.loadJarPath(location); long interval; try { interval = Long.parseLong(intervalString); } catch (NumberFormatException ex) { interval = DEFAULT_INTERVAL_SECONDS; } FileWatchdog fw = new FileWatchdog(location) { @Override protected void doOnChange(File file) { ClassLoaderUtil.loadJarFile(file); System.gc(); } }; // 启动文件监控线程 fw.setDelay(interval * 1000); fw.start(); } }
/** * Gets the GoogleBaseService object created by {@link AuthenticationFilter} or creates a new one * if <code>AuthenticationFilter</code> has not been applied yet. * * @param req * @param servletContext * @return a GoogleBaseService object */ public static GoogleBaseService getGoogleBaseService( HttpServletRequest req, ServletContext servletContext) { GoogleBaseService service; service = (GoogleBaseService) req.getAttribute(AuthenticationFilter.SERVICE_ATTRIBUTE); if (service == null) { service = new GoogleBaseService( servletContext.getInitParameter(APPLICATION_NAME_PARAMETER), servletContext.getInitParameter(DEVELOPER_KEY_PARAMETER)); req.setAttribute(AuthenticationFilter.SERVICE_ATTRIBUTE, service); } return service; }
public GenericWebAppContext( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, SessionProvider sessionProvider, ManageableRepository repository) { initialize(servletContext, request, response); this.sessionProvider = sessionProvider; this.repository = repository; // log.info("WEb context ---------------"); // initialize context with all props Enumeration en = servletContext.getInitParameterNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, servletContext.getInitParameter(name)); LOG.debug("ServletContext init param: " + name + "=" + servletContext.getInitParameter(name)); } en = servletContext.getAttributeNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, servletContext.getAttribute(name)); LOG.debug("ServletContext: " + name + "=" + servletContext.getAttribute(name)); } HttpSession session = request.getSession(false); if (session != null) { en = session.getAttributeNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, session.getAttribute(name)); LOG.debug("Session: " + name + "=" + session.getAttribute(name)); } } en = request.getAttributeNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, request.getAttribute(name)); } en = request.getParameterNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, request.getParameter(name)); LOG.debug("Request: " + name + "=" + request.getParameter(name)); } }
public void init(ServletConfig config) throws ServletException { super.init(config); ServletContext ctx = config.getServletContext(); ServiceAuthenticator sAuthenticator = ServiceAuthenticator.getInstance(); sAuthenticator.setAccessUsername(ctx.getInitParameter(ClientConstants.ACCESS_USERNAME)); sAuthenticator.setAccessPassword(ctx.getInitParameter(ClientConstants.ACCESS_PASSWORD)); String trustStorePath = ctx.getInitParameter(ClientConstants.TRUSTSTORE_PATH); System.setProperty( ClientConstants.TRUSTSTORE_PROPERTY, Thread.currentThread().getContextClassLoader().getResource(trustStorePath).getPath()); }
@Override public void init() { ApplicationContext ctx = getContext(); WebApplicationContext webCtx = (WebApplicationContext) ctx; ServletContext scx = webCtx.getHttpSession().getServletContext(); setUrl(scx.getInitParameter("url")); setDbName(scx.getInitParameter("dbName")); setDriver(scx.getInitParameter("driver")); setUserName(scx.getInitParameter("userName")); setPassword(scx.getInitParameter("password")); initLayout(); }
public void init(ServletContext context) throws EventHandlerException { String delegatorName = context.getInitParameter("entityDelegatorName"); this.delegator = DelegatorFactory.getDelegator(delegatorName); this.dispatcher = GenericDispatcher.getLocalDispatcher(delegator.getDelegatorName(), delegator); this.setHandlerMapping(new ServiceRpcHandler()); String extensionsEnabledString = context.getInitParameter("xmlrpc.enabledForExtensions"); if (UtilValidate.isNotEmpty(extensionsEnabledString)) { enabledForExtensions = Boolean.valueOf(extensionsEnabledString); } String exceptionsEnabledString = context.getInitParameter("xmlrpc.enabledForExceptions"); if (UtilValidate.isNotEmpty(exceptionsEnabledString)) { enabledForExceptions = Boolean.valueOf(exceptionsEnabledString); } }
public void contextInitialized(ServletContextEvent sce) { // retrieve appropriate initialization parameters ServletContext app = sce.getServletContext(); String grantingTimeoutString = app.getInitParameter("edu.yale.its.tp.cas.grantingTimeout"); String serviceTimeoutString = app.getInitParameter("edu.yale.its.tp.cas.serviceTimeout"); String loginTimeoutString = app.getInitParameter("edu.yale.its.tp.cas.loginTimeout"); int grantingTimeout, serviceTimeout, loginTimeout; try { grantingTimeout = Integer.parseInt(grantingTimeoutString); } catch (NumberFormatException ex) { grantingTimeout = GRANTING_TIMEOUT_DEFAULT; } catch (NullPointerException ex) { grantingTimeout = GRANTING_TIMEOUT_DEFAULT; } try { serviceTimeout = Integer.parseInt(serviceTimeoutString); } catch (NumberFormatException ex) { serviceTimeout = SERVICE_TIMEOUT_DEFAULT; } catch (NullPointerException ex) { serviceTimeout = SERVICE_TIMEOUT_DEFAULT; } try { loginTimeout = Integer.parseInt(loginTimeoutString); } catch (NumberFormatException ex) { loginTimeout = LOGIN_TIMEOUT_DEFAULT; } catch (NullPointerException ex) { loginTimeout = LOGIN_TIMEOUT_DEFAULT; } // set up the caches... GrantorCache tgcCache = new GrantorCache(TicketGrantingTicket.class, grantingTimeout); GrantorCache pgtCache = new GrantorCache(ProxyGrantingTicket.class, grantingTimeout); ServiceTicketCache stCache = new ServiceTicketCache(ServiceTicket.class, serviceTimeout); ServiceTicketCache ptCache = new ServiceTicketCache(ProxyTicket.class, serviceTimeout); LoginTicketCache ltCache = new LoginTicketCache(loginTimeout); // ... and share them app.setAttribute("tgcCache", tgcCache); app.setAttribute("pgtCache", pgtCache); app.setAttribute("stCache", stCache); app.setAttribute("ptCache", ptCache); app.setAttribute("ltCache", ltCache); }
/** * Получение соединения внутри сервлета * * @param servletContext * @return * @throws SQLException */ public static Connection getConnection(ServletContext servletContext) throws SQLException { Connection connection = null; // String connectionUrl = servletContext.getInitParameter("webdicom.connection.url"); if (connectionUrl != null) { Properties props = new Properties(); // connection properties props.put("user", "user1"); // FIXME взять из конфига props.put("password", "user1"); // FIXME взять из конфига connection = DriverManager.getConnection(connectionUrl + ";create=true", props); } else { // for Tomcat try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/webdicom"); connection = ds.getConnection(); } catch (NamingException e) { throw new SQLException("JNDI error " + e); } } return connection; }