001/* 002 * Copyright 2021 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.web; 017 018import java.util.Optional; 019 020import org.apache.avalon.framework.component.Component; 021import org.apache.avalon.framework.context.Context; 022import org.apache.avalon.framework.context.ContextException; 023import org.apache.avalon.framework.context.Contextualizable; 024import org.apache.cocoon.components.ContextHelper; 025import org.apache.cocoon.environment.Request; 026import org.apache.cocoon.environment.Session; 027 028import org.ametys.core.util.SessionAttributeProvider; 029import org.ametys.core.util.URIUtils; 030import org.ametys.runtime.plugin.component.AbstractLogEnabled; 031 032/** 033 * Component for getting a session attribute, potentially proxied by the front-office. 034 */ 035public class WebSessionAttributeProvider extends AbstractLogEnabled implements SessionAttributeProvider, Component, Contextualizable 036{ 037 private Context _context; 038 039 public void contextualize(Context context) throws ContextException 040 { 041 _context = context; 042 } 043 044 /** 045 * Retrieve the session attribute, either proxied by the back-office, or in the back-office session. 046 * @param name the attribute name 047 * @return the value stored either in the front-office session, or in the back-office session, or null if none 048 */ 049 public Optional<Object> getSessionAttribute(String name) 050 { 051 Request request = ContextHelper.getRequest(_context); 052 if (request != null) 053 { 054 String attributeFromHeader = request.getHeader("X-Ametys-Session-" + URIUtils.encodeHeader(name)); 055 if (attributeFromHeader != null) 056 { 057 return Optional.of(attributeFromHeader); 058 } 059 060 Session session = request.getSession(false); 061 if (session != null) 062 { 063 Object attribute = session.getAttribute(name); 064 if (attribute instanceof String str) 065 { 066 return Optional.of(str); 067 } 068 else if (attribute != null) 069 { 070 throw new UnsupportedOperationException("Only attribute of type String are supported by the WebSessionAttributeProvider."); 071 } 072 } 073 } 074 return Optional.empty(); 075 } 076}