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.List;
021
022import org.apache.commons.io.IOUtils;
023import org.apache.commons.lang3.StringUtils;
024import org.apache.log4j.Logger;
025
026/**
027 * A simple class for Double parameters
028 *
029 */
030public class DoubleParameter extends HTTPParameter{
031  private static final Logger LOGGER = Logger.getLogger(DoubleParameter.class);
032  private double[] _values = null;
033
034  @Override
035  public void initialize(List<String> parameterValues) throws IllegalArgumentException {
036    try{
037      int count = parameterValues.size();
038      double[] array = new double[count];
039      for(int i=0;i<count;++i){
040        array[i] = Double.parseDouble(parameterValues.get(i));
041      }
042      _values = array;
043    }catch(NumberFormatException ex){
044      LOGGER.debug(ex, ex);
045      throw new IllegalArgumentException("Invalid value for parameter: "+getParameterName());
046    }
047  }
048
049  /**
050   * 
051   * @return values for this parameter
052   */
053  public double[] getValues(){
054    return _values;
055  }
056  
057  @Override
058  public Double getValue(){
059    return (hasValues() ? _values[0] : null);
060  }
061
062  @Override
063  public boolean hasValues() {
064    return (_values != null);
065  }
066
067  @Override
068  public void initialize(String parameterValue) throws IllegalArgumentException {
069    if(StringUtils.isBlank(parameterValue)){
070      _values = null;
071      return; // do nothing on empty value
072    }
073    try{
074      _values = new double[]{Double.parseDouble(parameterValue)};
075    }catch(NumberFormatException ex){
076      LOGGER.debug(ex, ex);
077      throw new IllegalArgumentException("Invalid value: "+parameterValue+" for parameter: "+getParameterName());
078    }
079  }
080  
081  @Override
082  public void initialize(InputStream stream) throws IllegalArgumentException {
083    try {
084      _values = new double[]{Double.parseDouble(IOUtils.toString(stream))};
085    } catch (IOException | NumberFormatException ex) {
086      LOGGER.error(ex, ex);
087      throw new IllegalArgumentException("Failed to read HTTP body.");
088    }
089  }
090}