View Javadoc

1   /*
2    *  Copyright (c) 2005, 2006 Imola Informatica.
3    *  All rights reserved. This program and the accompanying materials
4    *  are made available under the terms of the LGPL License v2.1
5    *  which accompanies this distribution, and is available at
6    *  http://www.gnu.org/licenses/lgpl.html
7    */
8   
9   
10  package it.imolinfo.jbi4cics.typemapping.cobol;
11  
12  import it.imolinfo.jbi4cics.Logger;
13  import it.imolinfo.jbi4cics.LoggerFactory;
14  import it.imolinfo.jbi4cics.exception.FormatException;
15  import java.math.BigInteger;
16  import java.util.Arrays;
17  
18  final class IntegerMarshaller {
19  
20      /**
21       * The logger for this class.
22       */
23      private static final Logger LOG
24              = LoggerFactory.getLogger(IntegerMarshaller.class);
25  
26      private IntegerMarshaller() {
27      }
28  
29      static void marshallInteger(BigInteger value, byte[] buffer, int offset,
30              int size, boolean isBigEndian) throws FormatException {
31          byte[] array = value.toByteArray();
32          int length = array.length;
33          byte filler;
34  
35          if (LOG.isDebugEnabled()) {
36              LOG.debug("value.toString: " + value);
37          }
38          if (length > size) {
39              Object[] args = new Object[] { size, value, length };
40  
41              LOG.error("CIC002114_Unexpected_size", args);
42              throw new FormatException("CIC002114_Unexpected_size", args);
43          }
44          if (value.signum() == -1) {
45              filler = (byte) 0xff;                       // complemento a 2
46          } else {
47              filler = 0;
48          }
49          if (isBigEndian) {
50              System.arraycopy(array, 0, buffer, offset + size - length, length);
51              Arrays.fill(buffer, offset, offset + size - length, filler);
52          } else {
53              array = reverse(array);
54              System.arraycopy(array, 0, buffer, offset, length);
55              Arrays.fill(buffer, offset + length, offset + size - length, filler);
56          }
57      }
58  
59      static BigInteger unmarshallInteger(byte[] buffer, int offset, int size, 
60                                          boolean isBigEndian) {
61          byte[] array = new byte[size];
62  
63          System.arraycopy(buffer, offset, array, 0, size);
64          if (!isBigEndian) {
65              array = reverse(array);
66          }
67          return new BigInteger(array);
68      }
69  
70      private static byte[] reverse(byte[] array) {
71          int length = array.length;
72          byte[] result = new byte[length];
73  
74          for (int i = length - 1; i >= 0; --i) {
75              result[i] = array[length - i - 1];
76          }
77          return result;
78      }
79  }