001/*
002 * JRecordBind, fixed-length file (un)marshaller
003 * Copyright 2019, Federico Fissore, and individual contributors. See
004 * AUTHORS.txt in the distribution for a full listing of individual
005 * contributors.
006 *
007 * This is free software; you can redistribute it and/or modify it
008 * under the terms of the GNU Lesser General Public License as
009 * published by the Free Software Foundation; either version 2.1 of
010 * the License, or (at your option) any later version.
011 *
012 * This software is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * You should have received a copy of the GNU Lesser General Public
018 * License along with this software; if not, write to the Free
019 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
021 */
022
023package org.fissore.jrecordbind.util;
024
025import java.lang.reflect.Method;
026
027/**
028 * Given an object, looks for methods that start with "get" or "is" and return a String.
029 * Then it replaces that String, trimmed, by getting and setting it
030 */
031public class Trimmer {
032
033  public void trim(Object obj) throws TrimmerException {
034    try {
035      for (Method readMethod : obj.getClass().getMethods()) {
036        String fieldName = null;
037        String readMethodName = readMethod.getName();
038        if (readMethodName.startsWith("is")) {
039          fieldName = readMethodName.substring(2);
040        } else if (readMethodName.startsWith("get")) {
041          fieldName = readMethodName.substring(3);
042        }
043
044        if (fieldName != null && String.class.isAssignableFrom(readMethod.getReturnType())) {
045          Method writeMethod = obj.getClass().getMethod("set" + fieldName, String.class);
046          if (writeMethod != null) {
047            String value = (String) readMethod.invoke(obj);
048            if (value != null) {
049              value = value.trim();
050              writeMethod.invoke(obj, value);
051            }
052          }
053        }
054      }
055    } catch (Exception e) {
056      throw new TrimmerException(e);
057    }
058  }
059}