001/* 002 * jPOS Project [http://jpos.org] 003 * Copyright (C) 2000-2026 jPOS Software SRL 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Affero General Public License as 007 * published by the Free Software Foundation, either version 3 of the 008 * License, or (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Affero General Public License for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jpos.iso; 020 021 022/** 023 * Implements the Padder interface for padding strings and byte arrays on the 024 * Right. 025 * 026 * @author joconnor 027 * @version $Revision$ $Date$ 028 */ 029public class RightPadder implements Padder 030{ 031 /** 032 * A padder for padding spaces on the right. This is very common in 033 * alphabetic fields. 034 */ 035 public static final RightPadder SPACE_PADDER = new RightPadder(' '); 036 037 private char pad; 038 039 /** 040 * Creates a Right Padder with a specific pad character. 041 * 042 * @param pad 043 * The padding character. For binary padders, the pad character 044 * is truncated to lower order byte. 045 */ 046 public RightPadder(char pad) 047 { 048 this.pad = pad; 049 } 050 051 public String pad(String data, int maxLength) throws ISOException { 052 if (maxLength < 0) 053 throw new ISOException ("invalid maxLength " + maxLength); 054 int len = data.length(); 055 056 if (len < maxLength) { 057 StringBuilder padded = new StringBuilder(maxLength); 058 padded.append(data); 059 for (; len < maxLength; len++) { 060 padded.append(pad); 061 } 062 data = padded.toString(); 063 } 064 else if (len > maxLength) { 065 throw new ISOException("Data is too long. Max = " + maxLength); 066 } 067 return data; 068 } 069 070 public String unpad(String paddedData) 071 { 072 int len = paddedData.length(); 073 for (int i = len; i > 0; i--) 074 { 075 if (paddedData.charAt(i - 1) != pad) 076 { 077 return paddedData.substring(0, i); 078 } 079 } 080 return ""; 081 } 082}