/contrib-imola/cics-bc/jbi4cics/src/main/java/it/imolinfo/jbi4cics/typemapping/cobol/IntegerMarshaller.java

https://bitbucket.org/ssteinmetz/openesb-components · Java · 79 lines · 56 code · 13 blank · 10 comment · 9 complexity · 8c62a54db6aa3225175a8f4ebf7c7eb7 MD5 · raw file

  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. package it.imolinfo.jbi4cics.typemapping.cobol;
  9. import it.imolinfo.jbi4cics.Logger;
  10. import it.imolinfo.jbi4cics.LoggerFactory;
  11. import it.imolinfo.jbi4cics.exception.FormatException;
  12. import java.math.BigInteger;
  13. import java.util.Arrays;
  14. final class IntegerMarshaller {
  15. /**
  16. * The logger for this class.
  17. */
  18. private static final Logger LOG
  19. = LoggerFactory.getLogger(IntegerMarshaller.class);
  20. private IntegerMarshaller() {
  21. }
  22. static void marshallInteger(BigInteger value, byte[] buffer, int offset,
  23. int size, boolean isBigEndian) throws FormatException {
  24. byte[] array = value.toByteArray();
  25. int length = array.length;
  26. byte filler;
  27. if (LOG.isDebugEnabled()) {
  28. LOG.debug("value.toString: " + value);
  29. }
  30. if (length > size) {
  31. Object[] args = new Object[] { size, value, length };
  32. LOG.error("CIC002114_Unexpected_size", args);
  33. throw new FormatException("CIC002114_Unexpected_size", args);
  34. }
  35. if (value.signum() == -1) {
  36. filler = (byte) 0xff; // complemento a 2
  37. } else {
  38. filler = 0;
  39. }
  40. if (isBigEndian) {
  41. System.arraycopy(array, 0, buffer, offset + size - length, length);
  42. Arrays.fill(buffer, offset, offset + size - length, filler);
  43. } else {
  44. array = reverse(array);
  45. System.arraycopy(array, 0, buffer, offset, length);
  46. Arrays.fill(buffer, offset + length, offset + size - length, filler);
  47. }
  48. }
  49. static BigInteger unmarshallInteger(byte[] buffer, int offset, int size,
  50. boolean isBigEndian) {
  51. byte[] array = new byte[size];
  52. System.arraycopy(buffer, offset, array, 0, size);
  53. if (!isBigEndian) {
  54. array = reverse(array);
  55. }
  56. return new BigInteger(array);
  57. }
  58. private static byte[] reverse(byte[] array) {
  59. int length = array.length;
  60. byte[] result = new byte[length];
  61. for (int i = length - 1; i >= 0; --i) {
  62. result[i] = array[length - i - 1];
  63. }
  64. return result;
  65. }
  66. }