001/*
002 * (C) Copyright 2006 Nuxeo SA (http://nuxeo.com/) and others.
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 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.project.sample;
020
021import javax.faces.application.FacesMessage;
022import javax.faces.component.UIComponent;
023import javax.faces.context.FacesContext;
024import javax.faces.convert.Converter;
025import javax.faces.convert.ConverterException;
026
027public class BookIntegerConverter implements Converter {
028
029    public Object getAsObject(FacesContext context, UIComponent component, String value) {
030        Integer result;
031        if (value.trim().length() == 0) {
032            result = Integer.valueOf(0);
033        } else {
034            try {
035                result = Integer.valueOf(Integer.parseInt(value));
036            } catch (NumberFormatException e) {
037                FacesMessage message = new FacesMessage();
038                message.setDetail("The value must be an integer");
039                message.setSummary("Not an integer");
040                message.setSeverity(FacesMessage.SEVERITY_ERROR);
041                throw new ConverterException(message);
042            }
043        }
044        return result;
045    }
046
047    public String getAsString(FacesContext context, UIComponent component, Object value) {
048        int v = ((Integer) value).intValue();
049        if (v == 0) {
050            return "";
051        } else {
052            return Integer.toString(v);
053        }
054    }
055
056}