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