public String redirectToServiceDetails() { logger.logDebug("entering redirectToServiceDetails"); FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = Marketplace.MARKETPLACE_ROOT + "/serviceDetails.jsf"; try { viewId = extContext.getRequestContextPath() + viewId + ui.getSelectedServiceKeyQueryPart(String.valueOf(model .getSelectedServiceKey())) + ui.getMarketplaceIdQueryPart(); String urlLink = context.getExternalContext().encodeActionURL( viewId); JSFUtils.redirect(extContext, urlLink); } catch (IOException e) { extContext.log( getClass().getName() + ".redirectToServiceDetails()", e); } finally { // reset requested key; model.setSelectedServiceKey(null); } return null; }
@Override protected void encodeAllAsElement( FacesContext context, RenderingContext rc, UIComponent component, FacesBean bean ) throws IOException { // call super... super.encodeAllAsElement(context, rc, component, bean); // now evaluate the EL // We need to evaluate it here and store it on the sessionMap because // during UploadedFileProcessor.processFile() there is no FacesContext RequestContext requestContext = RequestContext.getCurrentInstance(); Object maxMemory = requestContext.getUploadedFileMaxMemory(); Object maxDiskSpace = requestContext.getUploadedFileMaxDiskSpace(); Object tempDir = requestContext.getUploadedFileTempDir(); ExternalContext external = context.getExternalContext(); Map<String, Object> sessionMap = external.getSessionMap(); sessionMap.put(UploadedFileProcessor.MAX_MEMORY_PARAM_NAME, maxMemory); sessionMap.put(UploadedFileProcessor.MAX_DISK_SPACE_PARAM_NAME, maxDiskSpace); sessionMap.put(UploadedFileProcessor.TEMP_DIR_PARAM_NAME, tempDir); }
private static <E extends Enum> Collection<E> _parseDisplayNameParam( ExternalContext external, String paramName, Class<E> enumClass, E defaultValue ) throws InvalidConfigException { try { return Enums.parseDisplayNameEnumRequestParameter(external, paramName, enumClass, defaultValue); } catch (EnumParseException e) { throw new InvalidConfigException(e.getMessage()); } }
public ParamPregenConfig(FacesContext context) throws InvalidConfigException { ExternalContext external = context.getExternalContext(); _containerTypes = _parseDisplayNameParam(external, "containerType", ContainerType.class, ContainerType.SERVLET); _requestTypes = _parseDisplayNameParam(external, "requestType", RequestType.class, RequestType.NONSECURE); _styleClassTypes = _parseDisplayNameParam(external, "styleClassType", StyleClassType.class, StyleClassType.COMPRESSED); _targetDirectoryPath = _getTargetDirectoryPath(context); }
/** *Returns the servlet context object from the FacesContext * * @param context * @return */ private Object _getServletContextFromFacesContext(FacesContext context) { ExternalContext ec = null; Object sc = null; if (context != null) { ec = context.getExternalContext(); if (ec != null) { sc = ec.getContext(); } } return sc; }
/** * given the skinId, pass back the Skin. * * @param context FacesContext. If not available, pass in null. * @param skinId * @return Skin that is in this SkinFactory and has the skinId. * @deprecated use SkinProvider to query skins */ @Deprecated @Override public Skin getSkin(FacesContext context, String skinId) { context = SkinUtils.getNonNullFacesContext(context); if (skinId == null) { _LOG.warning("CANNOT_GET_SKIN_WITH_NULL_SKINID"); return null; } ExternalContext ec = context.getExternalContext(); SkinMetadata skinMetadata = new SkinMetadata.Builder().id(skinId).build(); return SkinProvider.getCurrentInstance(ec).getSkin(ec, skinMetadata); }
public String getSelectedServiceKeyQueryPart(String selectedServiceKey) { String selectedService = ""; ExternalContext extContext = getFacesContext().getExternalContext(); String charEncoding = extContext.getRequestCharacterEncoding(); try { String name = URLEncoder.encode("selectedServiceKey", charEncoding); String value = URLEncoder.encode(selectedServiceKey, charEncoding); selectedService = '?' + name + '=' + value; } catch (UnsupportedEncodingException e) { extContext.log(getClass().getName() + ".getSelectedServiceQueryPart()", e); } return selectedService; }
@Before public void setup() { validator = new CaptchaValidator(); sessionMock = new HttpSessionStub(Locale.ENGLISH); context = new FacesContextStub(Locale.ENGLISH) { @Override public ExternalContext getExternalContext() { ExternalContext exContext = spy(new ExternalContextStub( Locale.ENGLISH)); doReturn(sessionMock).when(exContext).getSession(false); return exContext; } }; inputField = new HtmlInputText() { @Override public String getClientId(FacesContext ctx) { return ""; } }; }
/** * Saves the current state to the session. Running this is only manditory if you need to preserve a request across * the natural request boundry in a portlet environment. Executing this function outside of a portlet environment will * not alter operation of his class. * * @param ec the ExternalContext to save the stateMap to. */ public void saveState(ExternalContext ec) { RequestType type = ExternalContextUtils.getRequestType(ec); if(type.isPortlet() && !type.isResponseWritable()) { try { //TODO: use reflection here but it can be replaced.. Object actionResp = ec.getResponse(); Method m = actionResp.getClass().getMethod("setRenderParameter", String.class, String.class); String uuid = UUID.randomUUID().toString(); ec.getSessionMap().put(_STATE_MAP+"."+uuid, this); m.invoke(actionResp, _STATE_MAP, uuid); } catch(Throwable t) { //TODO: Log exception t.printStackTrace(); } } }
public static void registerFacesDependencies(ConfigurableListableBeanFactory beanFactory) { beanFactory.registerResolvableDependency(FacesContext.class, new ObjectFactory<FacesContext>() { @Override public FacesContext getObject() { return FacesContext.getCurrentInstance(); } @Override public String toString() { return "Current JSF FacesContext"; } }); beanFactory.registerResolvableDependency(ExternalContext.class, new ObjectFactory<ExternalContext>() { @Override public ExternalContext getObject() { return FacesContext.getCurrentInstance().getExternalContext(); } @Override public String toString() { return "Current JSF ExternalContext"; } }); }
@Override protected void setUp() throws IOException { MFacesContext ctx = new MFacesContext(MApplication.sharedInstance(), true); ExternalContext externalContext = ctx.getExternalContext(); Map<String, Object> applicationMap = externalContext.getApplicationMap(); applicationMap.put(TrinidadSkinProvider.TRINDIAD_SKIN_PROVIDER_KEY, new TrinidadSkinProvider()); applicationMap.put(ExternalSkinProvider.EXTERNAL_SKIN_PROVIDER_KEY, new ExternalSkinProvider()); applicationMap.put(SkinProvider.SKIN_PROVIDER_INSTANCE_KEY, new SkinProviderRegistry()); _facesContext = ctx; _externalContext = externalContext; _provider = SkinProvider.getCurrentInstance(_externalContext); if (SkinFactory.getFactory() == null) SkinFactory.setFactory(new SkinFactoryImpl()); RenderKitBootstrap.setFactories(_facesConfigInfo); }
/** * @inheritDoc */ @Override @Deprecated public void reloadSkins(ExternalContext externalContext, SkinFactory skinFactory) { // ask all subordinate configurators to reload their skins // We do not load the base skins and trinidad-skins eagerly. // When any configurator tries to register its skins to the SKinFactory, // it may be calling skinFactory.getSkin(...) to get hold of a base skin. // As SkinFactory is now under SkinProvider SPI, it makes sure that internally all parents are lazy loaded. // thus the caller will get a base Skin which he wants, but we do not load all skins eagerly. for (final Configurator config: _services) { config.reloadSkins(externalContext, skinFactory); } }
public TrinidadComponentHandler(ComponentConfig config) { super(config); if (_markInitialState == null) { // Can't imagine why this wouldn't always run during // a Faces request... FacesContext context = FacesContext.getCurrentInstance(); if (context != null) { ExternalContext external = context.getExternalContext(); String restoreMode = external.getInitParameter( StateManager.PARTIAL_STATE_SAVING_PARAM_NAME); if (Boolean.valueOf(restoreMode)) { _markInitialState = Boolean.TRUE; _LOG.severe("PARTIAL_STATE_SAVING_NOT_SUPPORTED"); } else { _markInitialState = Boolean.FALSE; } } } }
/** * Returns the value of the PPR optimization parameter. We currently support "on" and "off" * @param context * @return */ private static String _getPprOptimization(FacesContext context) { ExternalContext external = context.getExternalContext(); Map<String, Object> applicationMap = external.getApplicationMap(); // first check if this has been overridden at the application level String pprOptimization = (String)applicationMap.get(_PPR_OPTIMIZATION_PROP); if (pprOptimization == null) { // the value hasn't been set, so check the initialization parameter pprOptimization = external.getInitParameter(_PPR_OPTIMIZATION_PROP); // default to "off" if (pprOptimization == null) pprOptimization = "off"; // cache in the application so that we don't need to fetch this again applicationMap.put(_PPR_OPTIMIZATION_PROP, pprOptimization); } return pprOptimization; }
/** * This fires during the Render Response phase, saving state. */ public static final String construct(Object object, ExternalContext ctx) { byte[] bytes = getAsByteArray(object, ctx); if( enableCompression(ctx) ) { bytes = compress(bytes); } if(isSecure(ctx)) { bytes = encrypt(bytes, ctx); } bytes = encode(bytes); try { return new String(bytes, ZIP_CHARSET); } catch (UnsupportedEncodingException e) { throw new FacesException(e); } }
private StyleSheetNamingStrategy _getInitParamFileNamingStrategy() { ExternalContext external = _arc.getFacesContext().getExternalContext(); String strategyParam = external.getInitParameter(_NAMING_STRATEGY_PARAM); if (strategyParam != null) { strategyParam = strategyParam.trim(); if (strategyParam.length() > 0) { try { return StyleSheetNamingStrategy.valueOfDisplayName(strategyParam); } catch (IllegalArgumentException e) { _LOG.warning("INVALID_ENUM_IN_CONFIG", new Object[] { strategyParam, _NAMING_STRATEGY_PARAM });; } } } return StyleSheetNamingStrategy.STABLE; }
private static ResponseWriter _getResponseWriter(FacesContext context) throws IOException { ExternalContext external = context.getExternalContext(); String contentType = "text/html"; String encoding = "UTF-8"; external.setResponseContentType(contentType); external.setResponseCharacterEncoding(encoding); ResponseWriter rw = context.getRenderKit().createResponseWriter( external.getResponseOutputWriter(), contentType, encoding); context.setResponseWriter(rw); return rw; }
private ExternalContext _createExternalContext(ServletRequest request, ServletResponse response) { // potentially wrap the ServletContext in order to check managed bean HA ExternalContext externalContext = new ServletExternalContext( _getPotentiallyWrappedServletContext(request), request, response); if (_isMultipartHttpServletRequest(externalContext)) { // We need to wrap the ExternalContext for multipart form posts in order to avoid // premature reads on the request input stream. See MultipartExternalContextWrapper // class doc for details. // // Note: we only appply this fix for HttpServlet use cases, as the fix requires access // to the query string, and I don't see how to get at the query string for portlet // requests. It is possible that this means that trinidad file uploads may still be broken // for portlets when running against JSF 2.2. externalContext = new MultipartExternalContextWrapper(externalContext); } return externalContext; }
/** * Returns the current windowId, if any * @param external * @param trinContext * @return */ static private String _getCurrWindowId(ExternalContext external, RequestContext trinContext) { if (trinContext != null) { WindowManager wm = trinContext.getWindowManager(); if (wm != null) { Window currWindow = wm.getCurrentWindow(external); if (currWindow != null) { return currWindow.getId(); } } } return null; }
public static GenericConverterFactory getCurrentInstance(ExternalContext extContext) { // TODO: once getCurrentInstance() taking ExternalContext is in ADE, // we need to modify FacesDatabindingConfigurator to pass in the context. // Then we can switch to storing factory instance on the application map /*if (extContext == null) extContext = FacesContext.getCurrentInstance().getExternalContext(); Map appMap = extContext.getApplicationMap(); GenericConverterFactory factory = (GenericConverterFactory)appMap.get(_INSTANCE_KEY); if (factory == null) { factory = new GenericConverterFactory(); appMap.put(_INSTANCE_KEY, factory); } return factory;*/ return _INSTANCE; }
/** * Returns the name of the underlying context or <code>null</code> if something * went wrong in trying to retrieve the context. * * @param ec the current external context * @return a String containing the context name */ public static String getContextName(ExternalContext ec) { try { if (isPortlet(ec)) { return (String) _runMethod(ec.getContext(), "getPortletContextName"); } else { return ((ServletContext) ec.getContext()).getServletContextName(); } } catch (final ClassCastException e) { _LOG.severe(e); } return null; }
public String getLogoutPage(ExternalContext externalContext) { String rootUrl = getRootUrl(externalContext); String logoutPage = octopusJSFConfiguration.getLogoutPage(); if (logoutPage.startsWith("/")) { rootUrl += logoutPage; } else { rootUrl = logoutPage; } for (LogoutURLProcessor processor : logoutURLProcessors) { rootUrl = processor.postProcessLogoutUrl(rootUrl); } return rootUrl; }
public void logout() { //super.logout(); ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); try { externalContext.redirect(logoutHandler.getLogoutPage(externalContext)); } catch (IOException e) { throw new AtbashUnexpectedException(e); } }
/** * Init and return testing bean */ private TemplateBean getTestBean() throws Exception { InitialContext context = new InitialContext(); context.bind(APPTemplateService.JNDI_NAME, templateService); templateService = new APPTemplateServiceMockup(); facesContext = Mockito.mock(FacesContext.class); externalContext = Mockito.mock(ExternalContext.class); httpSession = Mockito.mock(HttpSession.class); application = Mockito.mock(Application.class); controllerAccess = Mockito.mock(ControllerAccess.class); viewRoot = Mockito.mock(UIViewRoot.class); Mockito.when(facesContext.getExternalContext()) .thenReturn(externalContext); Mockito.when(facesContext.getApplication()).thenReturn(application); Mockito.when(externalContext.getSession(Matchers.anyBoolean())) .thenReturn(httpSession); Mockito.when(httpSession.getAttribute(Matchers.anyString())) .thenReturn("aValue"); Mockito.when(facesContext.getViewRoot()).thenReturn(viewRoot); Mockito.when(viewRoot.getLocale()).thenReturn(new Locale("en")); Mockito.when(controllerAccess.getControllerId()) .thenReturn("ess.common"); // Init testing bean TemplateBean bean = new TemplateBean() { @Override protected FacesContext getContext() { return facesContext; } }; bean.setTemplateService(templateService); bean.setControllerAccess(controllerAccess); return bean; }
/** * Returns the added parameters * * @param externalContext * @return */ static public Map<String, String[]> getAddedParameters(ExternalContext externalContext) { @SuppressWarnings("unchecked") Map<String, String[]> map = (Map<String, String[]>) externalContext.getRequestMap().get(_PARAMS); return map; }
public String registraSaida() { FacesContext fc = FacesContext.getCurrentInstance(); ExternalContext ec = fc.getExternalContext(); HttpSession session = (HttpSession) ec.getSession(false); session.removeAttribute("usuario"); return "/login"; }
@Test public void redirectToIdpLogoutTest() throws IOException { //given FacesContext mockContext = mock(FacesContext.class); ExternalContext mockExternalContext = mock(ExternalContext.class); doReturn(mockContext).when(sessionBean).getFacesContext(); doReturn(mockExternalContext).when(mockContext).getExternalContext(); doReturn("someLogoutRequest").when(sessionBean).getSamlLogoutRequest(); //when sessionBean.redirectToIdpLogout(); //then verify(mockExternalContext, times(1)).redirect(any(String.class)); }
/** * Returns the contextPath of the ServletContext or <code>null</code> for portlets * * @param ec the current external context * @return a String containing the servletContextPath */ public static String getServletContextPath(ExternalContext ec) { if(!isPortlet(ec)) { return ((ServletContext) ec.getContext()).getContextPath(); } else { return null; } }
@Override public Collection<SkinMetadata> getSkinMetadata(ExternalContext externalContext) { Collection<SkinMetadata> metadata = new ArrayList<SkinMetadata>(); for (SkinProvider provider : _providers) metadata.addAll(provider.getSkinMetadata(externalContext)); return Collections.unmodifiableCollection(metadata); }
@Override public ExternalContext getExternalContext() { if (externalContextStub == null) { externalContextStub = new ExternalContextStub(usedLocale); } return externalContextStub; }
/** * Gets a TokenCache from the session, creating it if needed. */ @SuppressWarnings("unchecked") static public TokenCache getTokenCacheFromSession( ExternalContext extContext, String cacheName, boolean createIfNeeded, int defaultSize) { Map<String, Object> sessionMap = extContext.getSessionMap(); TokenCache cache = (TokenCache)sessionMap.get(cacheName); if (cache == null) { if (createIfNeeded) { Object session = extContext.getSession(true); // Synchronize on the session object to ensure that // we don't ever create two different caches synchronized (session) { cache = (TokenCache)sessionMap.get(cacheName); if (cache == null) { // create the TokenCache with the crytographically random seed cache = new TokenCache(defaultSize, _getSeed(), cacheName); sessionMap.put(cacheName, cache); } } } } return cache; }
protected int getContentHandlerId() { FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); Map<String, Object> scopeMap = externalContext.getApplicationMap(); AtomicInteger counter = (AtomicInteger) scopeMap.get(_CACHED_MODELS_ID_CNTR_KEY); return counter.getAndIncrement(); }
@Override public ExternalContext getExternalContext(ExternalContext externalContext) { //Wrap only if there are parameters present Map<String, String[]> addedParams = getAddedParameters(externalContext); if(addedParams != null) { return _getExternalContextWrapper(externalContext, addedParams); } return externalContext; }
private static byte[] findMacSecret(ExternalContext ctx, String algorithm) { String secret = ctx.getInitParameter(INIT_MAC_SECRET); if (secret == null) { secret = ctx.getInitParameter(INIT_MAC_SECRET.toLowerCase()); } return findMacSecret(secret, algorithm); }
/** * {@inheritDoc} */ @Override public Collection<SkinMetadata> getSkinMetadata(ExternalContext context) { synchronized (this) { return Collections.unmodifiableCollection(_skins.keySet()); } }
private void _writeFormActionScript() throws IOException { String viewId = _facesContext.getViewRoot().getViewId(); // HACK: don't write out an "action" for PPR on a GenericEntry page // (basically entirely for the InlineDatePicker case) if (!GenericEntry.getViewId().equals(viewId)) { _xml.startElement(_ELEMENT_EVAL, null); _xml.startCDATA(); StringBuilder script = new StringBuilder(128); script.append("TrPage.getInstance().__handlePprResponseAction('"); String actionURL = _facesContext.getApplication(). getViewHandler().getActionURL(_facesContext, viewId); ExternalContext external = _facesContext.getExternalContext(); script.append(external.encodeActionURL(actionURL)); script.append("');"); _xml.write(script.toString()); _xml.endCDATA(); _xml.endElement(_ELEMENT_EVAL); } }
/** * Returns an instance of the RequestStateMap. If the RequestStateMap is not present, this class will attempt to find * a version that was saved from {@link #saveState(ExternalContext)}. If no state was saved, then it will create a new * map and return it. * <p/> * Please keep in mind that regardless of whether a map was already present on the request or not, executing this method * will ALWAYS clear any state which might have been saved to the session. This is what enforces the "single restore" * type functionality. * * @param ec an ExternalContext * @return the RequestStateMap for this ExternalContext */ static public RequestStateMap getInstance(ExternalContext ec) { Map<String, Object> reqMap = ec.getRequestMap(); RequestStateMap map = (RequestStateMap)reqMap.get(_STATE_MAP); //For now, always check this on a render so it can be removed from the session. //This can be optimized to only save the state when request attributes are NOT preserved if(!ExternalContextUtils.isRequestFromClient(ec)) { String uuid = ec.getRequestParameterMap().get(_STATE_MAP); if(uuid!= null) { RequestStateMap myMap= (RequestStateMap)ec.getSessionMap().remove(_STATE_MAP+"."+uuid); if(map == null) { map = myMap; reqMap.put(_STATE_MAP, map); } else { //TODO: put optimization code here } } } if(map == null) { map = new RequestStateMap(); reqMap.put(_STATE_MAP, map); } return map; }
/** * Returns the map of uploaded files for the current request. */ @SuppressWarnings("unchecked") static public UploadedFiles getUploadedFiles(ExternalContext externalContext) { Map<String, Object> requestMap = externalContext.getRequestMap(); return (UploadedFiles) requestMap.get(_UPLOADED_FILES_KEY); }
/** * Returns a URLEncoder if one has been set. If it has not been set, it * creates a new URLEncoder using the provided ExternalContext. * * @return a URLEncoder for the given request * @throws IllegalStateException if no controller has been set and the ExternalContext object * is null */ public URLEncoder getURLEncoder(ExternalContext ec) { //even though we should wait until we have a faces context and throw an error //if we don't, go ahead and fudge it if the threadlocal is not null. This just //means that a URLEncoder has already been set for this thread. URLEncoder enc = _local.get(); if(null != enc) { return enc; } if(null == ec) { throw new IllegalStateException("An ExternalContext must be a available"); } if(ExternalContextUtils.isPortlet(ec)) { setURLEncoder(new PortletURLEncoder(ec)); } else { setURLEncoder(new ExternalContextURLEncoder(ec)); } return _local.get(); }
/** * @inheritDoc */ @Override public Skin createSkin(ExternalContext externalContext, SkinMetadata skinMetadata) { if (externalContext == null || skinMetadata == null) throw new NullPointerException(_LOG.getMessage("NULL_FC_SKIN_METADATA")); if (skinMetadata.getBaseSkinId() == null) throw new NullPointerException(_LOG.getMessage("NULL_BASE_SKIN_ID")); SkinMetadata baseSkinMetadata = new SkinMetadata.Builder().id(skinMetadata.getBaseSkinId()).build(); return createSkin(externalContext, baseSkinMetadata, skinMetadata); }