001/**
002 * Copyright 2014 Tampere University of Technology, Pori Department
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 core.tut.pori.http.parameters;
017
018import java.io.IOException;
019import java.io.InputStream;
020import java.util.ArrayList;
021import java.util.List;
022
023import org.apache.commons.io.IOUtils;
024import org.apache.log4j.Logger;
025
026
027/**
028 * A simple class for String parameters
029 *
030 */
031public class StringParameter extends HTTPParameter {
032  private static final Logger LOGGER = Logger.getLogger(StringParameter.class);
033  private String _value = null;
034  private List<String> _values = null;
035
036  @Override
037  public void initialize(List<String> parameterValues) throws IllegalArgumentException {
038    _values = parameterValues;
039    _value = null;
040  }
041  
042  /**
043   * create empty, non-initializes StringParameter
044   */
045  public StringParameter() {
046    // nothing needed
047  }
048
049  /**
050   * 
051   * @return list of values or null if none
052   */
053  public List<String> getValues(){
054    if(_value != null){ // lazily initialize the array if requested for a single parameter
055      _values = new ArrayList<>(1);
056      _values.add(_value);
057      _value =  null;
058      return _values;
059    }else{
060      return _values;
061    }
062  }
063  
064  /**
065   * 
066   * @return first (or the only one) of the values or null if none available
067   */
068  @Override
069  public String getValue(){
070    if(_value != null){
071      return _value;
072    }else if(_values != null){
073      return _values.get(0);
074    }else{
075      return null;
076    }
077  }
078
079  @Override
080  public boolean hasValues() {
081    if(_values != null || _value != null){
082      return true;
083    }else{
084      return false;
085    }
086  }
087
088  @Override
089  public void initialize(String parameterValue) throws IllegalArgumentException {
090    _value = parameterValue;
091    _values = null;
092  }
093
094  @Override
095  public void initialize(InputStream stream) throws IllegalArgumentException {
096    try {
097      _value = IOUtils.toString(stream);
098    } catch (IOException ex) {
099      LOGGER.error(ex, ex);
100      throw new IllegalArgumentException("Failed to read HTTP body.");
101    }
102  }
103}