public TestBean() { random = new Random(4143); FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = (null != context) ? context.getExternalContext() : null; servletContext = (null != extContext) ? (ServletContext) extContext.getContext() : null; oneElementList = new ArrayList<String>(1); oneElementList.add("hello"); }
/** * Return the WebConfiguration instance for this application. * * @param extContext the ExternalContext for this request * @return the WebConfiguration for this application */ public static WebConfiguration getInstance(ExternalContext extContext) { WebConfiguration config = (WebConfiguration) extContext.getApplicationMap().get(WEB_CONFIG_KEY); if (config == null) { return getInstance((ServletContext) extContext.getContext()); } else { return config; } }
/** @return true if an exception have been detected. */ public boolean isException() { if (isPortletMode()) { FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); PortletRequest request = (PortletRequest) externalContext.getRequest(); ContextUtils.bindRequestAndContext(request, (PortletContext) externalContext.getContext()); } return ExceptionUtils.getMarkedExceptionService() != null; }
public boolean mediaIsValid() { boolean returnValue = true; // check if file is too big FacesContext context = FacesContext.getCurrentInstance(); ExternalContext external = context.getExternalContext(); Long fileSize = (Long) ((ServletContext) external.getContext()).getAttribute("TEMP_FILEUPLOAD_SIZE"); Long maxSize = (Long) ((ServletContext) external.getContext()).getAttribute("FILEUPLOAD_SIZE_MAX"); // log.info("**** filesize is ="+fileSize); // log.info("**** maxsize is ="+maxSize); ((ServletContext) external.getContext()).removeAttribute("TEMP_FILEUPLOAD_SIZE"); if (fileSize != null) { float fileSize_float = fileSize.floatValue() / 1024; int tmp = Math.round(fileSize_float * 10.0f); fileSize_float = (float) tmp / 10.0f; float maxSize_float = maxSize.floatValue() / 1024; int tmp0 = Math.round(maxSize_float * 10.0f); maxSize_float = (float) tmp0 / 10.0f; String err1 = (String) ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "file_upload_error"); String err2 = (String) ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "file_uploaded"); String err3 = (String) ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "max_size_allowed"); String err4 = (String) ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "upload_again"); String err = err2 + fileSize_float + err3 + maxSize_float + err4; context.addMessage("file_upload_error", new FacesMessage(err1)); context.addMessage("file_upload_error", new FacesMessage(err)); returnValue = false; } return returnValue; }
/** * Default constructor * * @param wrapped original ExternalContext */ public RedirectExternalContext(ExternalContext wrapped) { super(); this.wrapped = wrapped; ServletContext servletContext = (ServletContext) wrapped.getContext(); this.redirectHelper = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) .getBean(RedirectHelper.class); Assert.notNull(this.redirectHelper); }
@Override public void afterPhase(PhaseEvent event) { FacesContext facesContext = event.getFacesContext(); if (facesContext.getViewRoot() == null) { try { ExternalContext econtext = facesContext.getExternalContext(); String contextPath = ((ServletContext) econtext.getContext()).getContextPath(); econtext.redirect(contextPath + "/"); } catch (IOException ex) { Logger.getLogger(DefaultPhaseListener.class.getName()).log(Level.SEVERE, null, ex); } } }
public FactoryManagerCacheKey( FacesContext facesContext, ClassLoader cl, Map<FactoryManagerCacheKey, FactoryManager> factoryMap) { this.cl = cl; boolean resolveValueFromFactoryMap = false; if (null == facesContext) { resolveValueFromFactoryMap = true; } else { ExternalContext extContext = facesContext.getExternalContext(); context = extContext.getContext(); if (null == context) { resolveValueFromFactoryMap = true; } else { Map<String, Object> appMap = extContext.getApplicationMap(); Long val = (Long) appMap.get(KEY); if (null == val) { marker = new Long(System.currentTimeMillis()); appMap.put(KEY, marker); } else { marker = val; } } } if (resolveValueFromFactoryMap) { // We don't have a FacesContext. // Our only recourse is to inspect the keys of the // factoryMap and see if any of them has a classloader // equal to our argument cl. Set<FactoryManagerCacheKey> keys = factoryMap.keySet(); FactoryManagerCacheKey match = null; for (FactoryManagerCacheKey cur : keys) { if (this.cl.equals(cur.cl)) { if (null != cur && null != match) { LOGGER.log( Level.WARNING, "Multiple JSF Applications found on same ClassLoader. Unable to safely determine which FactoryManager instance to use. Defaulting to first match."); break; } match = cur; } } if (null != match) { this.marker = match.marker; } } }
GroovyHelperImpl() throws Exception { FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext extContext = facesContext.getExternalContext(); ClassLoader curLoader = Thread.currentThread().getContextClassLoader(); URL combinedRoots[] = getResourceRoots(extContext, curLoader); if (0 < combinedRoots.length) { GroovyScriptEngine engine = new GroovyScriptEngine(combinedRoots, curLoader); // Class<?> c = Util.loadClass("groovy.util.GroovyScriptEngine", // GroovyHelperFactory.class); // Constructor<?> ctor = c.getConstructor(URL[].class, ClassLoader.class); // GroovyScriptEngine engine = (GroovyScriptEngine)ctor.newInstance(combinedRoots, // curLoader); loader = new MojarraGroovyClassLoader(engine); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Groovy support enabled."); } extContext.getApplicationMap().put("com.sun.faces.groovyhelper", this); ((ServletContext) (extContext.getContext())).setAttribute("com.sun.faces.groovyhelper", this); } }
public void generateReport(String reportType) { System.out.println("Pozvao metod"); FacesContext facesContext = FacesContext.getCurrentInstance(); try { ExternalContext externalContext = facesContext.getExternalContext(); context = (ServletContext) externalContext.getContext(); reportsDirectory = context.getRealPath("/") + "/WEB-INF/classes/jasper/"; response = (HttpServletResponse) externalContext.getResponse(); if (reportType.equals("allOsobeGroupByBirthDate")) { List<Osoba> data = OsobaManager.getAllOsoba(); params.put("datumKreiranja", new Date()); jasperFile = reportsDirectory + "allOsobeGroupByBirthDate.jasper"; if (data.size() == 0) { jasperPrint = JasperFillManager.fillReport(jasperFile, params, emptyDataSource); } else { dataSource = new JRBeanCollectionDataSource(data, false); // important, // solve // error jasperPrint = JasperFillManager.fillReport(jasperFile, params, dataSource); } } ServletOutputStream servletOutputStream = response.getOutputStream(); response.setContentType("application/pdf"); JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { facesContext.responseComplete(); } }
public TestBean() { random = new Random(4143); FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = (null != context) ? context.getExternalContext() : null; servletContext = (null != extContext) ? (ServletContext) extContext.getContext() : null; }
@PostConstruct protected void initialize() { if (logger.isInfoEnabled()) { logger.info("Reading configuration parameters."); } FacesContext context = FacesContext.getCurrentInstance(); ExternalContext externalContext = context.getExternalContext(); ProjectStage stage = context.getApplication().getProjectStage(); String path = StringUtils.trimToNull(externalContext.getInitParameter(APPLICATION_HOME)); if (path == null) { if (logger.isInfoEnabled()) { logger.info("Parameter 'applicationHome' is not set. Using the default path."); } path = System.getProperty("user.home") + File.separator + ".pivot4j"; } else if (path.endsWith(File.separator)) { path = path.substring(0, path.length() - File.separator.length()); } if (logger.isInfoEnabled()) { logger.info("Using application home : {}", path); } this.applicationHome = new File(path); if (!applicationHome.exists()) { applicationHome.mkdirs(); } InputStream in = null; try { String configPath = StringUtils.trimToNull(externalContext.getInitParameter(CONFIG_FILE)); if (configPath == null || stage == ProjectStage.UnitTest) { configPath = path + File.separator + "pivot4j-config.xml"; File configFile = new File(configPath); if (!configFile.exists() || stage == ProjectStage.UnitTest) { String defaultConfig = "/WEB-INF/pivot4j-config.xml"; if (logger.isInfoEnabled()) { logger.info("Config file does not exist. Using default : " + defaultConfig); } ServletContext servletContext = (ServletContext) externalContext.getContext(); String location = servletContext.getRealPath(defaultConfig); if (location != null) { configFile = new File(location); } } if (!configFile.exists()) { String msg = "Unable to read the default config : " + configFile; throw new FacesException(msg); } in = new FileInputStream(configFile); } else { URL url; if (configPath.startsWith("classpath:")) { url = new URL(null, configPath, new ClasspathStreamHandler()); } else { url = new URL(configPath); } in = url.openStream(); if (in == null) { String msg = "Unable to read config from URL : " + url; throw new FacesException(msg); } } this.configuration = readConfiguration(context, in); } catch (IOException e) { String msg = "Failed to read application config : " + e; throw new FacesException(msg, e); } catch (ConfigurationException e) { String msg = "Invalid application config : " + e; throw new FacesException(msg, e); } finally { IOUtils.closeQuietly(in); } if (logger.isInfoEnabled()) { logger.info("Pivot4J Analytics has been initialized successfully."); } configuration.addConfigurationListener( new ConfigurationListener() { @Override public void configurationChanged(ConfigurationEvent event) { onConfigurationChanged(event); } }); }
public static RequestContextBean parseConfigFile(ExternalContext externalContext) { RequestContextBean bean = new RequestContextBean(); InputStream in = externalContext.getResourceAsStream(_CONFIG_FILE); if (in != null) { try { InputSource input = new InputSource(); input.setByteStream(in); input.setPublicId(_CONFIG_FILE); XMLReader reader = _SAX_PARSER_FACTORY.newSAXParser().getXMLReader(); reader.setContentHandler(new Handler(bean, externalContext)); reader.parse(input); } catch (IOException ioe) { _LOG.warning(ioe); } catch (ParserConfigurationException pce) { _LOG.warning(pce); } catch (SAXException saxe) { _LOG.warning(saxe); } finally { try { in.close(); } catch (IOException ioe) { // Ignore ; } } } String classNameString = (String) bean.getProperty(RequestContextBean.UPLOADED_FILE_PROCESSOR_KEY); if (classNameString != null) { classNameString = classNameString.trim(); // check if this contains multiple class names for chained processors usecase. // Usually the class named are separated by space char. String classNames[] = classNameString.split("[ ]+"); if (classNames.length == 1) { // This could be a single processor full override usecase or a chained // processor usecase that has only one processor. try { Class<UploadedFileProcessor> clazz = (Class<UploadedFileProcessor>) ClassLoaderUtils.loadClass(classNames[0]); if (ChainedUploadedFileProcessor.class.isAssignableFrom(clazz)) { // this single chained processor case ChainedUploadedFileProcessor cufp[] = { (ChainedUploadedFileProcessor) clazz.newInstance() }; bean.setProperty( RequestContextBean.UPLOADED_FILE_PROCESSOR_KEY, new CompositeUploadedFileProcessorImpl(Arrays.asList(cufp))); } else { // this is full override usecase bean.setProperty(RequestContextBean.UPLOADED_FILE_PROCESSOR_KEY, clazz.newInstance()); } } catch (Exception e) { _LOG.severe("CANNOT_INSTANTIATE_UPLOADEDFILEPROCESSOR", e); bean.setProperty( RequestContextBean.UPLOADED_FILE_PROCESSOR_KEY, new CompositeUploadedFileProcessorImpl()); } } else { try { // chained processors usecase, Multiple processors List<ChainedUploadedFileProcessor> processors = new ArrayList<ChainedUploadedFileProcessor>(classNames.length); for (String className : classNames) { Class<ChainedUploadedFileProcessor> clazz = (Class<ChainedUploadedFileProcessor>) ClassLoaderUtils.loadClass(className); processors.add(clazz.newInstance()); } bean.setProperty( RequestContextBean.UPLOADED_FILE_PROCESSOR_KEY, new CompositeUploadedFileProcessorImpl(processors)); } catch (Exception e) { _LOG.severe("CANNOT_INSTANTIATE_UPLOADEDFILEPROCESSOR", e); bean.setProperty( RequestContextBean.UPLOADED_FILE_PROCESSOR_KEY, new CompositeUploadedFileProcessorImpl()); } } } else { // nothing specified, hence use default. bean.setProperty( RequestContextBean.UPLOADED_FILE_PROCESSOR_KEY, new CompositeUploadedFileProcessorImpl()); } UploadedFileProcessor ufp = (UploadedFileProcessor) bean.getProperty(RequestContextBean.UPLOADED_FILE_PROCESSOR_KEY); ufp.init(externalContext.getContext()); if (_LOG.isInfo()) { Object debug = bean.getProperty(RequestContextBean.DEBUG_OUTPUT_KEY); if (Boolean.TRUE.equals(debug)) _LOG.info("RUNNING_IN_DEBUG_MODE", _CONFIG_FILE); } return bean; }