001// Copyright 2004, 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.multipart;
016
017import java.util.ArrayList;
018import java.util.List;
019
020/**
021 * A portion of a multipart request that stores a value, or values, for a parameter.
022 * 
023 * @author Howard Lewis Ship
024 * @since 2.0.1
025 */
026
027public class ValuePart
028{
029    private int _count;
030
031    // Stores either String or List of String
032    private Object _value;
033
034    public ValuePart(String value)
035    {
036        _count = 1;
037        _value = value;
038    }
039
040    public int getCount()
041    {
042        return _count;
043    }
044
045    /**
046     * Returns the value, or the first value (if multi-valued).
047     */
048
049    public String getValue()
050    {
051        if (_count == 1)
052            return (String) _value;
053
054        List l = (List) _value;
055
056        return (String) l.get(0);
057    }
058
059    /**
060     * Returns the values as an array of strings. If there is only one value, it is returned wrapped
061     * as a single element array.
062     */
063
064    public String[] getValues()
065    {
066        if (_count == 1)
067            return new String[]
068            { (String) _value };
069
070        List l = (List) _value;
071
072        return (String[]) l.toArray(new String[_count]);
073    }
074
075    public void add(String newValue)
076    {
077        if (_count == 1)
078        {
079            List l = new ArrayList();
080            l.add(_value);
081            l.add(newValue);
082
083            _value = l;
084            _count++;
085            return;
086        }
087
088        List l = (List) _value;
089        l.add(newValue);
090        _count++;
091    }
092
093    /**
094     * Does nothing.
095     */
096
097    public void cleanup()
098    {
099    }
100}