001// Copyright 2010, 2013 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.tapestry5.internal;
016
017import java.util.Optional;
018
019import org.apache.tapestry5.EventContext;
020
021public abstract class AbstractEventContext implements EventContext
022{
023    public String[] toStrings()
024    {
025        int count = getCount();
026
027        String[] result = new String[count];
028
029        for (int i = 0; i < count; i++)
030        {
031            result[i] = get(String.class, i);
032        }
033
034        return result;
035    }
036
037    @Override
038    public String toString()
039    {
040        StringBuilder builder = new StringBuilder("<EventContext");
041
042        String[] values = toStrings();
043
044        String sep = ": ";
045
046        for (int i = 0; i < values.length; i++)
047        {
048            builder.append(sep).append(values[i]);
049            sep = ", ";
050        }
051
052        return builder.append('>').toString();
053    }
054    
055
056    @Override
057    public boolean isEmpty()
058    {
059        return getCount() == 0;
060    }
061
062    @Override
063    public <T> Optional<T> tryGet(Class<T> desiredType, int index)
064    {
065        if (index >= getCount())
066        {
067            return Optional.empty();
068        }
069
070        try
071        {
072            T value = get(desiredType, index);
073            return Optional.ofNullable(value);
074        } catch (RuntimeException e)
075        {
076            // Ignore any RuntimeException
077        }
078
079        return Optional.empty();
080    }
081
082}