001// Copyright 2005 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry.portlet.bindings;
016
017import java.util.Map;
018
019import javax.portlet.PortletRequest;
020
021import org.apache.hivemind.ApplicationRuntimeException;
022import org.apache.hivemind.Location;
023import org.apache.hivemind.util.Defense;
024import org.apache.tapestry.binding.AbstractBinding;
025import org.apache.tapestry.coerce.ValueConverter;
026
027/**
028 * Allows access to a Portlet user attrbute.
029 * 
030 * @author Howard M. Lewis Ship
031 * @since 4.0
032 */
033public class UserAttributeBinding extends AbstractBinding
034{
035    private final PortletRequest _request;
036
037    private final String _attributeName;
038
039    public UserAttributeBinding(String description, ValueConverter valueConverter,
040            Location location, PortletRequest request, String attributeName)
041    {
042        super(description, valueConverter, location);
043
044        Defense.notNull(request, "request");
045        Defense.notNull(attributeName, "attributeName");
046
047        _request = request;
048        _attributeName = attributeName;
049    }
050
051    public boolean isInvariant()
052    {
053        // These can always be changed.
054        return false;
055    }
056
057    private Map getUserInfo()
058    {
059        Map result = (Map) _request.getAttribute(PortletRequest.USER_INFO);
060
061        if (result == null)
062            throw new ApplicationRuntimeException(BindingsMessages.noUserInfo(), getLocation(),
063                    null);
064
065        return result;
066    }
067
068    public Object getObject()
069    {
070        return getUserInfo().get(_attributeName);
071    }
072
073    public void setObject(Object value)
074    {
075        String asString = (String) getValueConverter().coerceValue(value, String.class);
076
077        getUserInfo().put(_attributeName, asString);
078    }
079}