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 * left. 025 * 026 * @author joconnor 027 * @version $Revision$ $Date$ 028 */ 029public class LeftPadder implements Padder 030{ 031 /** 032 * A padder for padding zeros on the left. This is very common in numeric 033 * fields. 034 */ 035 public static final LeftPadder ZERO_PADDER = new LeftPadder('0'); 036 037 private char pad; 038 039 /** 040 * Creates a Left 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 LeftPadder(char pad) 047 { 048 this.pad = pad; 049 } 050 051 /** 052 */ 053 public String pad(String data, int maxLength) throws ISOException 054 { 055 StringBuilder padded = new StringBuilder(maxLength); 056 int len = data.length(); 057 if (len > maxLength) 058 { 059 throw new ISOException("Data is too long. Max = " + maxLength); 060 } else 061 { 062 for (int i = maxLength - len; i > 0; i--) 063 { 064 padded.append(pad); 065 } 066 padded.append(data); 067 } 068 return padded.toString(); 069 } 070 071 /** 072 * (non-Javadoc) 073 * 074 */ 075 public String unpad(String paddedData) 076 { 077 int i = 0; 078 int len = paddedData.length(); 079 while (i < len) 080 { 081 if (paddedData.charAt(i) != pad) 082 { 083 return paddedData.substring(i); 084 } 085 i++; 086 } 087 return ""; 088 } 089}