@Override public String getDescription(boolean includeClientInfo) { PortletRequest request = getRequest(); StringBuilder result = new StringBuilder(); result.append("context=").append(request.getContextPath()); if (includeClientInfo) { PortletSession session = request.getPortletSession(false); if (session != null) { result.append(";session=").append(session.getId()); } String user = getRequest().getRemoteUser(); if (StringUtils.hasLength(user)) { result.append(";user=").append(user); } } return result.toString(); }
/** * Register web-specific scopes ("request", "session", "globalSession") * with the given BeanFactory, as used by the Portlet ApplicationContext. * @param bf the BeanFactory to configure * @param pc the PortletContext that we're running within */ static void registerPortletApplicationScopes(ConfigurableListableBeanFactory bf, PortletContext pc) { bf.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope()); bf.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false)); bf.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true)); if (pc != null) { PortletContextScope appScope = new PortletContextScope(pc); bf.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope); // Register as PortletContext attribute, for ContextCleanupListener to detect it. pc.setAttribute(PortletContextScope.class.getName(), appScope); } bf.registerResolvableDependency(PortletRequest.class, new RequestObjectFactory()); bf.registerResolvableDependency(PortletResponse.class, new ResponseObjectFactory()); bf.registerResolvableDependency(PortletSession.class, new SessionObjectFactory()); bf.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory()); }
@Override public void setAttribute(String name, Object value, int scope) { if (scope == SCOPE_REQUEST) { if (!isRequestActive()) { throw new IllegalStateException( "Cannot set request attribute - request is not active anymore!"); } this.request.setAttribute(name, value); } else { PortletSession session = getSession(true); if (scope == SCOPE_GLOBAL_SESSION) { session.setAttribute(name, value, PortletSession.APPLICATION_SCOPE); this.globalSessionAttributesToUpdate.remove(name); } else { session.setAttribute(name, value); this.sessionAttributesToUpdate.remove(name); } } }
@Override public void removeAttribute(String name, int scope) { if (scope == SCOPE_REQUEST) { if (isRequestActive()) { this.request.removeAttribute(name); removeRequestDestructionCallback(name); } } else { PortletSession session = getSession(false); if (session != null) { if (scope == SCOPE_GLOBAL_SESSION) { session.removeAttribute(name, PortletSession.APPLICATION_SCOPE); this.globalSessionAttributesToUpdate.remove(name); } else { session.removeAttribute(name); this.sessionAttributesToUpdate.remove(name); } } } }
@Override public String[] getAttributeNames(int scope) { if (scope == SCOPE_REQUEST) { if (!isRequestActive()) { throw new IllegalStateException( "Cannot ask for request attributes - request is not active anymore!"); } return StringUtils.toStringArray(this.request.getAttributeNames()); } else { PortletSession session = getSession(false); if (session != null) { if (scope == SCOPE_GLOBAL_SESSION) { return StringUtils.toStringArray(session.getAttributeNames(PortletSession.APPLICATION_SCOPE)); } else { return StringUtils.toStringArray(session.getAttributeNames()); } } else { return new String[0]; } } }
@Override public void handleActionRequest(ActionRequest request, ActionResponse response) throws Exception { // Delegate to PortletContentGenerator for checking and preparing. check(request, response); // Execute in synchronized block if required. if (this.synchronizeOnSession) { PortletSession session = request.getPortletSession(false); if (session != null) { Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { handleActionRequestInternal(request, response); return; } } } handleActionRequestInternal(request, response); }
@Override public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { // If the portlet is minimized and we don't want to render then return null. if (WindowState.MINIMIZED.equals(request.getWindowState()) && !this.renderWhenMinimized) { return null; } // Delegate to PortletContentGenerator for checking and preparing. checkAndPrepare(request, response); // Execute in synchronized block if required. if (this.synchronizeOnSession) { PortletSession session = request.getPortletSession(false); if (session != null) { Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { return handleRenderRequestInternal(request, response); } } } return handleRenderRequestInternal(request, response); }
@Test public void testGlobalSessionScope() { WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_GLOBAL_SESSION); MockRenderRequest request = new MockRenderRequest(); PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { assertNull(request.getPortletSession().getAttribute(NAME, PortletSession.APPLICATION_SCOPE)); DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class); assertSame(bean, request.getPortletSession().getAttribute(NAME, PortletSession.APPLICATION_SCOPE)); assertSame(bean, ac.getBean(NAME)); request.getPortletSession().invalidate(); assertTrue(bean.wasDestroyed()); } finally { RequestContextHolder.setRequestAttributes(null); } }
@Override public void setAttribute(String name, Object value, int scope) { if (scope == PortletSession.PORTLET_SCOPE) { if (value != null) { this.portletAttributes.put(name, value); } else { this.portletAttributes.remove(name); } } else if (scope == PortletSession.APPLICATION_SCOPE) { if (value != null) { this.applicationAttributes.put(name, value); } else { this.applicationAttributes.remove(name); } } }
@Override public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException { System.out.println("=====serveResource======="); String domainNo = ParamUtil.getString(resourceRequest, "domainNo"); String administrationNo = ParamUtil.getString(resourceRequest, "administrationNo"); PrintWriter pw = resourceResponse.getWriter(); JSONObject juser = JSONFactoryUtil.createJSONObject(); juser.put("domainNo", domainNo); juser.put("administrationNo", administrationNo); pw.println(juser.toString()); PortletSession session = resourceRequest.getPortletSession(); // PortletMode portletMode= resourceRequest.getPortletMode(); // portletMode.s session.setAttribute("domainNo", domainNo); System.out.println(juser.toString()); }
@Override public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException { System.out.println("=====serveResource======="); String domainNo = ParamUtil.getString(resourceRequest, "domainNo"); String administrationNo = ParamUtil.getString(resourceRequest, "administrationNo"); PrintWriter pw = resourceResponse.getWriter(); JSONObject juser = JSONFactoryUtil.createJSONObject(); juser.put("domainNo", domainNo); juser.put("administrationNo", administrationNo); pw.println(juser.toString()); PortletSession session = resourceRequest.getPortletSession(); session.setAttribute("domainNo", domainNo); }
private List<String> getIdsOfPaginatedFriends(RenderRequest request, RenderResponse response, PortletSession session, FacebookClientWrapper facebookClient) throws PortletException, IOException { // Count total number of friends Integer friendsCount = getFriendsCount(session, facebookClient); // Obtain number of current page Integer currentPage = getCurrentPageNumber(request, session); Integer indexStart = (currentPage - 1) * ITEMS_PER_PAGE; List<NamedFacebookType> friendsToDisplay = facebookClient.getPageOfFriends(indexStart, ITEMS_PER_PAGE); getPaginatorUrls(friendsCount, response); // Collect IDS of friends to display List<String> ids = new ArrayList<String>(); for (NamedFacebookType current : friendsToDisplay) { ids.add(current.getId()); } return ids; }
public static void setErrorMessage(PortletRequest request, String errorMsg, Throwable t) { if ( errorMsg == null ) errorMsg = "null"; PortletSession pSession = request.getPortletSession(true); pSession.setAttribute("error.message",errorMsg); OutputStream oStream = new ByteArrayOutputStream(); PrintStream pStream = new PrintStream(oStream); log.error("{}", oStream); log.error("{}", pStream); // errorMsg = errorMsg .replaceAll("<","<").replaceAll(">",">"); StringBuffer errorOut = new StringBuffer(); errorOut.append("<p class=\"portlet-msg-error\">\n"); errorOut.append(FormattedText.escapeHtmlFormattedText(errorMsg)); errorOut.append("\n</p>\n<!-- Traceback for this error\n"); errorOut.append(oStream.toString()); errorOut.append("\n-->\n"); pSession.setAttribute("error.output",errorOut.toString()); Map map = request.getParameterMap(); pSession.setAttribute("error.map",map); }
public static void debugPrint(PortletRequest request, String line) { if ( line == null ) return; line = line.replaceAll("<","<").replaceAll(">",">"); PortletSession pSession = request.getPortletSession(true); String debugOut = null; try { debugOut = (String) pSession.getAttribute("debug.print"); } catch (Throwable t) { debugOut = null; } if ( debugOut == null ) { debugOut = line; } else { debugOut = debugOut + "\n" + line; } pSession.setAttribute("debug.print",debugOut); }
public void processActionReset(String action,ActionRequest request, ActionResponse response) throws PortletException, IOException { // TODO: Check Role log.debug("Removing preferences...."); clearSession(request); PortletSession pSession = request.getPortletSession(true); PortletPreferences prefs = request.getPreferences(); try { prefs.reset("sakai.descriptor"); for (String element : fieldList) { prefs.reset("imsti."+element); prefs.reset("sakai:imsti."+element); } log.debug("Preference removed"); } catch (ReadOnlyException e) { setErrorMessage(request, rb.getString("error.modify.prefs")) ; return; } prefs.store(); // Go back to the main edit page pSession.setAttribute("sakai.view", "edit"); }
@Test public void portletReturnsMainViewAndApplicationSessionContainsNonvalidatedUserInfo() throws Exception { Map<String,String> userInfoMap = new HashMap<String, String>(); userInfoMap.put("librarynumber", "TestingA"); userInfoMap.put("sn", "Testing"); PortletMvcResult result = existingApplicationContext(applicationContext).build() .perform(new CustomMockRenderRequestBuilder().attribute(PortletRequest.USER_INFO,userInfoMap)) .andExpect(view().name("main")) .andExpect(session().exists()) .andExpect(session().hasAttribute(UserInfo.SESSION_ATTR)) .andReturn(); UserInfo userInfo = (UserInfo) result.getRequest().getPortletSession(false).getAttribute(UserInfo.SESSION_ATTR,PortletSession.APPLICATION_SCOPE); assertFalse(userInfo.isValidated()); }
/** * Handles errors that occur during a process action request */ private void handleError(ActionRequest request, ActionResponse response, Throwable error) throws PortletException, IOException { // get the error bean from the session and set the error that occurred. PortletSession session = request.getPortletSession(); ErrorBean errorBean = (ErrorBean)session.getAttribute(ErrorBean.ERROR_BEAN_NAME, PortletSession.PORTLET_SCOPE); if (errorBean == null) { errorBean = new ErrorBean(); session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean, PortletSession.PORTLET_SCOPE); } errorBean.setLastError(error); response.setRenderParameter(ERROR_OCCURRED, "true"); }
/** * Sets a session attribute. * * @param context * the faces context * @param attributeName * the attribute name * @param value * the value * @param shared * set the attribute with shared (application) scope? */ public static void setPortletSessionAttribute(FacesContext context, String attributeName, Object value, boolean shared) { Object portletReq = context.getExternalContext().getRequest(); if (portletReq != null && portletReq instanceof PortletRequest) { PortletSession session = ((PortletRequest) portletReq).getPortletSession(); session.setAttribute(attributeName, value, shared ? PortletSession.APPLICATION_SCOPE : PortletSession.PORTLET_SCOPE); } else { context.getExternalContext().getSessionMap().put(attributeName, value); } }
/** * For no previous authentication or forced Guest - attempt Guest access * * @param ctx WebApplicationContext * @param auth AuthenticationService */ private static User portalGuestAuthenticate(WebApplicationContext ctx, PortletSession session, AuthenticationService auth) { User user = AuthenticationHelper.portalGuestAuthenticate(ctx, auth); if (user != null) { // store the User object in the Session - the authentication servlet will then proceed session.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user, PortletSession.APPLICATION_SCOPE); // Set the current locale I18NUtil.setLocale(getLanguage(session)); // remove the session invalidated flag session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); } return user; }
protected boolean validateChallenge(PortletRequest portletRequest) throws CaptchaException { PortletSession portletSession = portletRequest.getPortletSession(); String captchaText = (String)portletSession.getAttribute( WebKeys.CAPTCHA_TEXT); if (captchaText == null) { _log.error( "Captcha text is null. User " + portletRequest.getRemoteUser() + " may be trying to circumvent the captcha."); throw new CaptchaTextException(); } boolean valid = captchaText.equals( ParamUtil.getString(portletRequest, "captchaText")); if (valid) { portletSession.removeAttribute(WebKeys.CAPTCHA_TEXT); } return valid; }
/** * Copia os valores para a requisição. * * Se o valor existir na sessão, copia para a requisição Se não existir, e o * objeto tiver sido informado, utiliza-o Se não o objeto não for informado, * tenta obter da sessão. Se não conseguir, utiliza o default * * @param req * @param att * @param propName * @param obj * @param defaultValue */ public static void copyToRequest(PortletRequest req, String att, String propName, Object obj, Object defaultValue) { PortletSession session = req.getPortletSession(false); if (session != null) { Object val = session.getAttribute("FLASH_" + att); if (val != null) { req.setAttribute(att, val); session.removeAttribute("FLASH_" + att); return; } } // Não existe na sessão if (obj == null) { req.setAttribute(att, defaultValue); } else { // Obtem o valor do objeto e copia - aqui apenas strings try { Object value = PropertyUtils.getProperty(obj, propName); req.setAttribute(att, value); } catch (Exception e) { LOG.error("Erro ao copiar propriedade " + propName + " da classe " + obj.getClass().getName(), e); } } }
public String getDescription(boolean includeClientInfo) { PortletRequest request = getRequest(); StringBuilder result = new StringBuilder(); result.append("context=").append(request.getContextPath()); if (includeClientInfo) { PortletSession session = request.getPortletSession(false); if (session != null) { result.append(";session=").append(session.getId()); } String user = getRequest().getRemoteUser(); if (StringUtils.hasLength(user)) { result.append(";user=").append(user); } } return result.toString(); }
public void removeAttribute(String name, int scope) { if (scope == SCOPE_REQUEST) { if (isRequestActive()) { this.request.removeAttribute(name); removeRequestDestructionCallback(name); } } else { PortletSession session = getSession(false); if (session != null) { if (scope == SCOPE_GLOBAL_SESSION) { session.removeAttribute(name, PortletSession.APPLICATION_SCOPE); this.globalSessionAttributesToUpdate.remove(name); } else { session.removeAttribute(name); this.sessionAttributesToUpdate.remove(name); } } } }
public void handleEventRequest( EventRequest request, EventResponse response) throws Exception { if (!(this.portletInstance instanceof EventPortlet)) { logger.debug("Ignoring event request for non-event target portlet: " + this.portletInstance.getClass()); return; } EventPortlet eventPortlet = (EventPortlet) this.portletInstance; // Delegate to PortletContentGenerator for checking and preparing. check(request, response); // Execute in synchronized block if required. if (isSynchronizeOnSession()) { PortletSession session = request.getPortletSession(false); if (session != null) { Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { eventPortlet.processEvent(request, response); return; } } } eventPortlet.processEvent(request, response); }
public void handleActionRequest(ActionRequest request, ActionResponse response) throws Exception { // Delegate to PortletContentGenerator for checking and preparing. check(request, response); // Execute in synchronized block if required. if (this.synchronizeOnSession) { PortletSession session = request.getPortletSession(false); if (session != null) { Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { handleActionRequestInternal(request, response); return; } } } handleActionRequestInternal(request, response); }
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { // If the portlet is minimized and we don't want to render then return null. if (WindowState.MINIMIZED.equals(request.getWindowState()) && !this.renderWhenMinimized) { return null; } // Delegate to PortletContentGenerator for checking and preparing. checkAndPrepare(request, response); // Execute in synchronized block if required. if (this.synchronizeOnSession) { PortletSession session = request.getPortletSession(false); if (session != null) { Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { return handleRenderRequestInternal(request, response); } } } return handleRenderRequestInternal(request, response); }
public void testSimpleFormViewWithSessionAndBindOnNewForm() throws Exception { MockRenderRequest renderRequest = new MockRenderRequest(); MockRenderResponse renderResponse = new MockRenderResponse(); renderRequest.setParameter("action", "form-session-bind"); renderRequest.setParameter("age", "30"); TestBean testBean = new TestBean(); testBean.setAge(40); SimplePortletApplicationContext ac = (SimplePortletApplicationContext)simpleDispatcherPortlet.getPortletApplicationContext(); String formAttribute = ac.getFormSessionAttributeName(); PortletSession session = new MockPortletSession(); session.setAttribute(formAttribute, testBean); renderRequest.setSession(session); simpleDispatcherPortlet.doDispatch(renderRequest, renderResponse); assertEquals("35", renderResponse.getContentAsString()); }
public Enumeration<String> getAttributeNames(int scope) { // Return all attribute names in the nested HttpSession object. if (scope == PortletSession.APPLICATION_SCOPE) { return httpSession.getAttributeNames(); } // Return attribute names with the portlet-scoped prefix. Vector<String> portletScopedNames = new Vector<String>(); for (Enumeration<String> en = httpSession.getAttributeNames(); en.hasMoreElements(); ) { String name = en.nextElement(); if (isInCurrentPortletScope(name)) { portletScopedNames.add( PortletSessionUtil.decodeAttributeName(name)); } } return portletScopedNames.elements(); }
public void setAttribute(String name, Object value, int scope) { if (scope == PortletSession.PORTLET_SCOPE) { if (value != null) { this.portletAttributes.put(name, value); } else { this.portletAttributes.remove(name); } } else if (scope == PortletSession.APPLICATION_SCOPE) { if (value != null) { this.applicationAttributes.put(name, value); } else { this.applicationAttributes.remove(name); } } }
protected TestResult checkSetAppScopedAttributeElsewhereSeenHere( PortletSession session) { TestResult result = new TestResult(); result.setDescription("Ensure application scoped attributes set " + "elsewhere in portlet session can be seen here."); Object value = session.getAttribute(EXT_KEY, PortletSession.APPLICATION_SCOPE); if (VALUE.equals(value)) { result.setReturnCode(TestResult.PASSED); } else { result.setReturnCode(TestResult.WARNING); result.setResultMessage("This test will not pass until you have " + "opened the external resource using the link provided below."); } return result; }
public static Object getAttribute(String name, ExternalContext externalContext) { Object session = externalContext.getSession(false); if (session instanceof PortletSession) { return ((PortletSession) session).getAttribute(name, PortletSession.APPLICATION_SCOPE); } else if (session != null) { return externalContext.getSessionMap().get(name); } else { return null; } }
public static void setAttribute(String name, Object value, ExternalContext externalContext) { Object session = externalContext.getSession(true); if (session instanceof PortletSession) { ((PortletSession) session).setAttribute(name, value, PortletSession.APPLICATION_SCOPE); } else { externalContext.getSessionMap().put(name, value); } }
public static void removeAttribute(String name, ExternalContext externalContext) { Object session = externalContext.getSession(false); if (session instanceof PortletSession) { ((PortletSession) session).removeAttribute(name, PortletSession.APPLICATION_SCOPE); } else if (session != null) { externalContext.getSessionMap().remove(name); } }
public static String[] getAttributeNames(ExternalContext externalContext) { Object session = externalContext.getSession(false); if (session instanceof PortletSession) { return StringUtils.toStringArray( ((PortletSession) session).getAttributeNames(PortletSession.APPLICATION_SCOPE)); } else if (session != null) { return StringUtils.toStringArray(externalContext.getSessionMap().keySet()); } else { return new String[0]; } }
/** * Exposes the {@link PortletSession} that we're wrapping. * @param allowCreate whether to allow creation of a new session if none exists yet */ protected final PortletSession getSession(boolean allowCreate) { if (isRequestActive()) { return this.request.getPortletSession(allowCreate); } else { // Access through stored session reference, if any... if (this.session == null && allowCreate) { throw new IllegalStateException( "No session found and request already completed - cannot create new session!"); } return this.session; } }
@Override public ModelAndView handleResourceRequest( ResourceRequest request, ResourceResponse response) throws Exception { if (!(this.portletInstance instanceof ResourceServingPortlet)) { throw new NoHandlerFoundException("Cannot handle resource request - target portlet [" + this.portletInstance.getClass() + " does not implement ResourceServingPortlet"); } ResourceServingPortlet resourcePortlet = (ResourceServingPortlet) this.portletInstance; // Delegate to PortletContentGenerator for checking and preparing. checkAndPrepare(request, response); // Execute in synchronized block if required. if (isSynchronizeOnSession()) { PortletSession session = request.getPortletSession(false); if (session != null) { Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { resourcePortlet.serveResource(request, response); return null; } } } resourcePortlet.serveResource(request, response); return null; }