Beispiel #1
0
  /**
   * Returns the value of the "list status indicator" field returned by QGY* API's.
   *
   * @param listInformation The "list information" structure returned by a QGY* API (that requested
   *     the building of a list).
   * @return The converted value of the "list status information" field. Possible values are '0',
   *     '1', '2', '3', '4', or '5'.
   * @throws ErrorCompletingRequestException if the List Status Information is other than
   *     "complete", "being built", or "pending"; or if the Information Complete Indicator is
   *     "interrupted".
   */
  private static char checkListStatus(byte[] listInformation)
      throws ErrorCompletingRequestException {
    char infoCompleteIndicator, listStatusIndicator;
    try {
      // Convert the two CHAR(1) fields from EBCDIC to Unicode.
      byte[] arry = {listInformation[16]}; // ICI is at offset 16
      infoCompleteIndicator = new CharConverter(37).byteArrayToString(arry, 0, 1).charAt(0);
      arry[0] = listInformation[30]; // LSI is at offset 30
      listStatusIndicator = new CharConverter(37).byteArrayToString(arry, 0, 1).charAt(0);
    } catch (java.io.UnsupportedEncodingException e) { // will never happen
      throw new InternalErrorException(InternalErrorException.UNEXPECTED_EXCEPTION, e.getMessage());
    }

    switch (listStatusIndicator) {
      case LIST_COMPLETE:
        break; // This is the indicator that we normally expect.

      case LIST_BEING_BUILT:
      case LIST_PENDING:
        // These status values are unusual, but aren't necessarily error conditions
        // (even if we indicated we wanted the list built synchronously).
        if (Trace.traceOn_)
          Trace.log(Trace.DIAGNOSTIC, "List status indicator:", listStatusIndicator);
        break;

      default: // any other status
        StringBuffer msg = new StringBuffer("Unable to synchronously build object list on server.");

        try {
          msg.append("\n  List status indicator: " + listStatusIndicator);
          msg.append("\n  Info complete indicator: " + infoCompleteIndicator);
          msg.append("\n  Total records:    " + BinaryConverter.byteArrayToInt(listInformation, 0));
          msg.append("\n  Records returned: " + BinaryConverter.byteArrayToInt(listInformation, 4));
        } catch (Throwable t) {
        } // will never happen
        finally {
          Trace.log(Trace.ERROR, msg.toString());
        }
        throw new ErrorCompletingRequestException(ErrorCompletingRequestException.AS400_ERROR);
    }

    if (infoCompleteIndicator == INFORMATION_INTERRUPTED) {
      Trace.log(Trace.ERROR, "Info complete indicator: " + infoCompleteIndicator);
      throw new ErrorCompletingRequestException(ErrorCompletingRequestException.AS400_ERROR);
    }

    return listStatusIndicator;
  }
Beispiel #2
0
 // @PDA jdbc40
 public String getNString() throws SQLException {
   truncated_ = 0;
   outOfBounds_ = false;
   // This is written in terms of getBytes(), since it will
   // handle truncating to the max field size if needed.
   return BinaryConverter.bytesToHexString(getBytes());
 }
Beispiel #3
0
 public Clob getClob() throws SQLException {
   truncated_ = 0;
   outOfBounds_ = false;
   // This is written in terms of getString(), since it will
   // handle truncating to the max field size if needed.
   String string = BinaryConverter.bytesToHexString(getBytes());
   return new AS400JDBCClob(string, string.length());
 }
Beispiel #4
0
  public Reader getCharacterStream() throws SQLException {
    truncated_ = 0;
    outOfBounds_ = false;
    // return new InputStreamReader(new AS400JDBCInputStream(new JDLobLocator(locator_)));

    // fix this to use a Stream
    return new StringReader(BinaryConverter.bytesToHexString(getBytes()));
  }
 public void convertFromRawBytes(
     byte[] rawBytes, int offset, ConvTable ccsidConverter, boolean ignoreConversionErrors)
     throws SQLException {
   int locatorHandle = BinaryConverter.byteArrayToInt(rawBytes, offset);
   locator_.setHandle(locatorHandle);
   locator_.setColumnIndex(columnIndex_);
   // @J5A reset saved handle after setting new value
   savedObject_ = null;
 }
Beispiel #6
0
  public void convertFromRawBytes(byte[] rawBytes, int offset, ConvTable ccsidConverter) // @P0C
      throws SQLException {
    value_ = BinaryConverter.byteArrayToInt(rawBytes, offset); // @D0C

    if (scale_ > 0) { // @C0A
      bigDecimalValue_ = (new BigDecimal(Integer.toString(value_))).movePointLeft(scale_); // @A0A
      value_ = bigDecimalValue_.intValue(); // @A0A
    } // @C0A
  }
Beispiel #7
0
 public Blob getBlob() throws SQLException {
   truncated_ = 0;
   try {
     return new AS400JDBCBlob(BinaryConverter.stringToBytes(value_), maxLength_);
   } catch (NumberFormatException nfe) {
     // this field contains non-hex characters
     JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, nfe);
     return null;
   }
 }
Beispiel #8
0
 public byte[] getBytes() throws SQLException {
   truncated_ = 0;
   try {
     return BinaryConverter.stringToBytes(getString());
   } catch (NumberFormatException nfe) {
     // this Clob contains non-hex characters
     JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, nfe);
     return null;
   }
 }
  /**
   * Positions the overlay structure. This reads the cached data only when it was not previously set
   * by the constructor.
   */
  public void overlay(byte[] rawBytes, int offset) {
    rawBytes_ = rawBytes;
    offset_ = offset;

    if (numberOfFields_ == -1) {
      numberOfFields_ = BinaryConverter.byteArrayToShort(rawBytes_, offset + 4);
      length_ = 8 + numberOfFields_ * REPEATED_LENGTH_;
    } else {
      setNumberOfFields(numberOfFields_);
    }
  }
Beispiel #10
0
 public byte[] getBytes() throws SQLException {
   truncated_ = 0;
   outOfBounds_ = false;
   try {
     return BinaryConverter.stringToBytes(value_);
   } catch (NumberFormatException nfe) {
     // this field contains non-hex characters
     JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, nfe);
     return null;
   }
 }
Beispiel #11
0
  // @CRS - This is only called from AS400JDBCPreparedStatement in one place.
  public void convertToRawBytes(byte[] rawBytes, int offset, ConvTable ccsidConverter)
      throws SQLException {
    BinaryConverter.intToByteArray(locator_.getHandle(), rawBytes, offset);

    // Now we write our saved data to the system, because the prepared statement is being executed.
    // We used to write the data to the system on the call to set(), but this messed up
    // batch executes, since the host server only reserves temporary space for locator handles one
    // row at a time.
    // See the toObject() method in this class for more details.
    if (savedObject_ != null) writeToServer();
  }
Beispiel #12
0
 public Blob getBlob() throws SQLException {
   truncated_ = 0;
   try {
     byte[] bytes = BinaryConverter.stringToBytes(getString());
     return new AS400JDBCBlob(bytes, bytes.length);
   } catch (NumberFormatException nfe) {
     // this Clob contains non-hex characters
     JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, nfe);
     return null;
   }
 }
  public static void main(String[] args) {
    // 2c 2d 3s 4s 8s => 10106 wrong
    // 2c 3c 2d 2h 2s => 10062 wrong

    List<Card> cards = new ArrayList<Card>(5);
    cards.add(new Card(Rank.DEUCE, Suit.CLUBS));
    cards.add(new Card(Rank.THREE, Suit.CLUBS));
    cards.add(new Card(Rank.DEUCE, Suit.DIAMONDS));
    cards.add(new Card(Rank.DEUCE, Suit.HEARTS));
    cards.add(new Card(Rank.DEUCE, Suit.SPADES));

    System.out.println(getHandValue(BinaryConverter.cardsToLong(cards)));
  }
 /**
  * Returns the current object. Subsequent calls to get() may not return the same object, but in
  * stead might return a new object deserialized from same set of bytes. As a result, multiple
  * calls to get() should be avoided, and modifications to an object returned by get() may not
  * reflect even if this writable is serialized later. <br>
  * Please use set() to be certain of what object is serialized.<br>
  * <br>
  * The deserialization of the actual Protobuf/Thrift object is often delayed till the first call
  * to this method. <br>
  * In some cases the the parameterized proto class may not be known yet ( in case of default
  * construction. see {@link #setConverter(Class)} ), and this will throw an {@link
  * IllegalStateException}.
  */
 public M get() {
   // may be we should rename this method. the contract would be less
   // confusing with a different name.
   if (message == null && messageBytes != null) {
     checkConverter();
     try {
       return converter.fromBytes(messageBytes);
     } catch (DecodeException e) {
       throw new IllegalStateException("Converter failed to deserialize", e);
     }
   }
   return message;
 }
 /**
  * Converts the message to raw bytes, and caches the converted value.
  *
  * @return converted value, which may be null in case of null message or error.
  */
 private byte[] serialize() {
   if (messageBytes == null && message != null) {
     checkConverter();
     messageBytes = converter.toBytes(message);
     if (messageBytes == null) {
       // should we throw an IOException instead?
       LOG.warn("Could not serialize " + message.getClass());
     } else {
       message = null; // so that message and messageBytes don't go out of
       // sync.
     }
   }
   return messageBytes;
 }
Beispiel #16
0
  public InputStream getUnicodeStream() throws SQLException {
    truncated_ = 0;
    outOfBounds_ = false;
    // return new AS400JDBCInputStream(new JDLobLocator(locator_));

    // fix this to use a Stream
    try {
      return new ByteArrayInputStream(
          ConvTable.getTable(13488, null)
              .stringToByteArray(BinaryConverter.bytesToHexString(getBytes())));
    } catch (UnsupportedEncodingException e) {
      JDError.throwSQLException(this, JDError.EXC_INTERNAL, e);
      return null;
    }
  }
Beispiel #17
0
  public void convertFromRawBytes(byte[] rawBytes, int offset, ConvTable ccsidConverter)
      throws SQLException {
    length_ = BinaryConverter.byteArrayToUnsignedShort(rawBytes, offset);

    int bidiStringType = settings_.getBidiStringType();
    // if bidiStringType is not set by user, use ccsid to get value
    if (bidiStringType == -1) bidiStringType = ccsidConverter.bidiStringType_;
    BidiConversionProperties bidiConversionProperties =
        new BidiConversionProperties(bidiStringType);
    bidiConversionProperties.setBidiImplicitReordering(settings_.getBidiImplicitReordering());
    bidiConversionProperties.setBidiNumericOrderingRoundTrip(settings_.getBidiNumericOrdering());

    value_ =
        ccsidConverter.byteArrayToString(rawBytes, offset + 2, length_, bidiConversionProperties);
  }
  public static int getHandValue(long cards) {

    List<Card> cardList = BinaryConverter.longToCards(cards);
    PokerHandUtil phu = new PokerHandUtil(cardList);
    Hand bestHand = phu.getBestHand();

    int rankSum = 0;
    int factor = 10;
    for (Card c : bestHand.getCards()) {
      rankSum += c.getRank().getOrderValue() * factor;
      factor--;
      factor--;
    }

    return bestHand.getPokerHand().getOrderValue() * HAND_FACTOR + rankSum;
  }
Beispiel #19
0
  // Calls QGYGTLE to get the current "list information" on the progress of list-building.
  private static byte[] refreshListInformation(byte[] listHandle, ProgramCall pgmCall)
      throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException,
          IOException, ObjectDoesNotExistException {
    if (pgmCall.getParameterList().length == 0) {
      ProgramParameter[] parameters =
          new ProgramParameter[] {
            // Receiver variable, output, char(*).
            new ProgramParameter(8), // minimum length is 8 bytes
            // Length of receiver variable, input, binary(4).
            new ProgramParameter(BinaryConverter.intToByteArray(8)),
            // Request handle, input, char(4).
            new ProgramParameter(listHandle),
            // List information, output, char(80).
            new ProgramParameter(LIST_INFO_LENGTH),
            // Number of records to return, input, binary(4).
            // '0' indicates: "Only the list information is returned and no actual list entries are
            // returned."
            new ProgramParameter(new byte[] {0x00, 0x00, 0x00, 0x00}),
            // Starting record, input, binary(4).
            // '0' indicates: "The list information should be returned to the caller immediately."
            // '-1' indicates: "The whole list should be built before the list information is
            // returned to the caller."
            // new ProgramParameter(new byte[] { 0x00, 0x00, 0x00, 0x00} ),
            new ProgramParameter(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}),
            // Error code, I/0, char(*).
            new ErrorCodeParameter()
          };
      try {
        pgmCall.setProgram("/QSYS.LIB/QGY.LIB/QGYGTLE.PGM", parameters);
      } catch (java.beans.PropertyVetoException pve) {
      } // will never happen
    }

    if (!pgmCall.run()) {
      throw new AS400Exception(pgmCall.getMessageList());
    }

    return pgmCall.getParameterList()[3].getOutputData(); // the "List Information" structure
  }
Beispiel #20
0
  public void convertToRawBytes(byte[] rawBytes, int offset, ConvTable ccsidConverter)
      throws SQLException {
    try {
      int bidiStringType = settings_.getBidiStringType();
      // if bidiStringType is not set by user, use ccsid to get value
      if (bidiStringType == -1) bidiStringType = ccsidConverter.bidiStringType_;

      BidiConversionProperties bidiConversionProperties =
          new BidiConversionProperties(bidiStringType);
      bidiConversionProperties.setBidiImplicitReordering(settings_.getBidiImplicitReordering());
      bidiConversionProperties.setBidiNumericOrderingRoundTrip(settings_.getBidiNumericOrdering());

      // The length in the first 2 bytes is actually the length in characters.
      byte[] temp = ccsidConverter.stringToByteArray(value_, bidiConversionProperties);
      BinaryConverter.unsignedShortToByteArray(temp.length, rawBytes, offset);
      if (temp.length > maxLength_) {
        maxLength_ = temp.length;
        JDError.throwSQLException(this, JDError.EXC_INTERNAL);
      }
      System.arraycopy(temp, 0, rawBytes, offset + 2, temp.length);

      // The buffer we are filling with data is big enough to hold the entire field.
      // For varchar fields the actual data is often smaller than the field width.
      // That means whatever is in the buffer from the previous send is sent to the
      // system.  The data stream includes actual data length so the old bytes are not
      // written to the database, but the junk left over may decrease the affectiveness
      // of compression.  The following code will write hex 0s to the buffer when
      // actual length is less that field length.  Note the 0s are written only if
      // the field length is pretty big.  The data stream code (DBBaseRequestDS)
      // does not compress anything smaller than 1K.
      if ((maxLength_ > 256) && (maxLength_ - temp.length > 16)) {
        int stopHere = offset + 2 + maxLength_;
        for (int i = offset + 2 + temp.length; i < stopHere; i++) rawBytes[i] = 0x00;
      }
    } catch (Exception e) {
      JDError.throwSQLException(this, JDError.EXC_INTERNAL, e);
    }
  }
Beispiel #21
0
 public void convertFromRawBytes(byte[] rawBytes, int offset, ConvTable ccsidConverter)
     throws SQLException {
   length_ = BinaryConverter.byteArrayToUnsignedShort(rawBytes, offset);
   AS400ByteArray typeConverter = new AS400ByteArray(length_);
   value_ = (byte[]) typeConverter.toObject(rawBytes, offset + 2);
 }
Beispiel #22
0
 public Clob getClob() throws SQLException {
   truncated_ = 0;
   outOfBounds_ = false;
   String string = BinaryConverter.bytesToHexString(getBytes());
   return new AS400JDBCClob(string, string.length());
 }
Beispiel #23
0
  public void set(Object object, Calendar calendar, int scale) throws SQLException {
    // If it's a byte[] we can check for data truncation.
    if (object instanceof byte[]) {
      byte[] bytes = (byte[]) object;
      truncated_ = (bytes.length > maxLength_ ? bytes.length - maxLength_ : 0);
    } else if (object instanceof String) {
      byte[] bytes = null;
      try {
        bytes = BinaryConverter.stringToBytes((String) object);
      } catch (NumberFormatException nfe) {
        // the String contains non-hex characters
        JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, nfe);
      }
      object = bytes;
      truncated_ = 0;
      outOfBounds_ = false;
    } else if (object instanceof Reader) {
      int length = scale; // hack to get the length into the set method
      byte[] bytes = null;
      if (length >= 0) {
        try {
          int blockSize =
              length < AS400JDBCPreparedStatement.LOB_BLOCK_SIZE
                  ? length
                  : AS400JDBCPreparedStatement.LOB_BLOCK_SIZE;
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          HexReaderInputStream stream = new HexReaderInputStream((Reader) object);
          byte[] byteBuffer = new byte[blockSize];
          int totalBytesRead = 0;
          int bytesRead = stream.read(byteBuffer, 0, blockSize);
          while (bytesRead > -1 && totalBytesRead < length) {
            baos.write(byteBuffer, 0, bytesRead);
            totalBytesRead += bytesRead;
            int bytesRemaining = length - totalBytesRead;
            if (bytesRemaining < blockSize) {
              blockSize = bytesRemaining;
            }
            bytesRead = stream.read(byteBuffer, 0, blockSize);
          }

          bytes = baos.toByteArray();

          if (bytes.length < length) {
            // a length longer than the stream was specified
            JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH);
          }

          int objectLength = bytes.length;
          if (bytes.length > maxLength_) {
            byte[] newValue = new byte[maxLength_];
            System.arraycopy(bytes, 0, newValue, 0, maxLength_);
            bytes = newValue;
          }
          stream.close(); // @scan1
          object = bytes;
          truncated_ = objectLength - bytes.length;
        } catch (ExtendedIOException eie) {
          // the Reader contains non-hex characters
          JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, eie);
        } catch (IOException ie) {
          JDError.throwSQLException(JDError.EXC_INTERNAL, ie);
        }
      } else if (length == -2) // @readerlen new else-if block (read all data)
      {
        try {
          int blockSize = AS400JDBCPreparedStatement.LOB_BLOCK_SIZE;
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          HexReaderInputStream stream = new HexReaderInputStream((Reader) object);
          byte[] byteBuffer = new byte[blockSize];
          int totalBytesRead = 0;
          int bytesRead = stream.read(byteBuffer, 0, blockSize);
          while (bytesRead > -1) {
            baos.write(byteBuffer, 0, bytesRead);
            totalBytesRead += bytesRead;

            bytesRead = stream.read(byteBuffer, 0, blockSize);
          }

          bytes = baos.toByteArray();

          int objectLength = bytes.length;
          if (bytes.length > maxLength_) {
            byte[] newValue = new byte[maxLength_];
            System.arraycopy(bytes, 0, newValue, 0, maxLength_);
            bytes = newValue;
          }
          stream.close(); // @scan1
          object = bytes;
          truncated_ = objectLength - bytes.length;
        } catch (ExtendedIOException eie) {
          // the Reader contains non-hex characters
          JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, eie);
        } catch (IOException ie) {
          JDError.throwSQLException(JDError.EXC_INTERNAL, ie);
        }
      } else {
        JDError.throwSQLException(JDError.EXC_DATA_TYPE_MISMATCH);
      }
    } else if (!(object instanceof String)
        && (JDUtilities.JDBCLevel_ >= 20 && !(object instanceof Blob))
        && !(object instanceof Reader)
        && !(object instanceof InputStream)) {
      JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH);
    }
    savedObject_ = object;
    if (scale != -1) scale_ = scale; // Skip resetting it if we don't know the real length
  }
Beispiel #24
0
 public void convertFromRawBytes(byte[] rawBytes, int offset, ConvTable ccsidConverter)
     throws SQLException {
   int locatorHandle = BinaryConverter.byteArrayToInt(rawBytes, offset);
   locator_.setHandle(locatorHandle);
   locator_.setColumnIndex(columnIndex_);
 }
Beispiel #25
0
 // @PDA jdbc40
 public String getNString() throws SQLException {
   truncated_ = 0;
   outOfBounds_ = false; // @pdc
   return BinaryConverter.bytesToHexString(getBytes()); // @pdc
 }
Beispiel #26
0
 public void convertToRawBytes(byte[] rawBytes, int offset, ConvTable ccsidConverter)
     throws SQLException {
   AS400ByteArray typeConverter = new AS400ByteArray(length_);
   BinaryConverter.unsignedShortToByteArray(length_, rawBytes, offset);
   typeConverter.toBytes(value_, rawBytes, offset + 2);
 }
Beispiel #27
0
  public void set(Object object, Calendar calendar, int scale) throws SQLException {
    if (object instanceof String) {
      try {
        value_ = BinaryConverter.stringToBytes((String) object);
      } catch (NumberFormatException nfe) {
        // the String contains non-hex characters
        JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, nfe);
      }
    } else if (object instanceof byte[]) value_ = (byte[]) object;
    else if (object instanceof InputStream) {
      // value_ = JDUtilities.streamToBytes((InputStream)object, scale);

      int length = scale; // hack to get the length into the set method
      if (length >= 0) {
        InputStream stream = (InputStream) object;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int blockSize =
            length < AS400JDBCPreparedStatement.LOB_BLOCK_SIZE
                ? length
                : AS400JDBCPreparedStatement.LOB_BLOCK_SIZE;
        byte[] byteBuffer = new byte[blockSize];
        try {
          int totalBytesRead = 0;
          int bytesRead = stream.read(byteBuffer, 0, blockSize);
          while (bytesRead > -1 && totalBytesRead < length) {
            baos.write(byteBuffer, 0, bytesRead);
            totalBytesRead += bytesRead;
            int bytesRemaining = length - totalBytesRead;
            if (bytesRemaining < blockSize) {
              blockSize = bytesRemaining;
            }
            bytesRead = stream.read(byteBuffer, 0, blockSize);
          }
        } catch (IOException ie) {
          JDError.throwSQLException(this, JDError.EXC_INTERNAL, ie);
        }
        value_ = baos.toByteArray();
        if (value_.length < length) {
          // a length longer than the stream was specified
          JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH);
        }
      } else if (length == -2) // @readerlen new else-if block (read all data)
      {
        InputStream stream = (InputStream) object;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int blockSize = AS400JDBCPreparedStatement.LOB_BLOCK_SIZE;
        byte[] byteBuffer = new byte[blockSize];
        try {
          int totalBytesRead = 0;
          int bytesRead = stream.read(byteBuffer, 0, blockSize);
          while (bytesRead > -1) {
            baos.write(byteBuffer, 0, bytesRead);
            totalBytesRead += bytesRead;

            bytesRead = stream.read(byteBuffer, 0, blockSize);
          }
        } catch (IOException ie) {
          JDError.throwSQLException(this, JDError.EXC_INTERNAL, ie);
        }
        value_ = baos.toByteArray();
      } else {
        JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH);
      }
    } else if (object instanceof Reader) {
      // value_ = BinaryConverter.stringToBytes(JDUtilities.readerToString((Reader)object, scale));

      int length = scale; // hack to get the length into the set method
      if (length >= 0) {
        try {
          int blockSize =
              length < AS400JDBCPreparedStatement.LOB_BLOCK_SIZE
                  ? length
                  : AS400JDBCPreparedStatement.LOB_BLOCK_SIZE;
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          HexReaderInputStream stream = new HexReaderInputStream((Reader) object);
          byte[] byteBuffer = new byte[blockSize];
          int totalBytesRead = 0;
          int bytesRead = stream.read(byteBuffer, 0, blockSize);
          while (bytesRead > -1 && totalBytesRead < length) {
            baos.write(byteBuffer, 0, bytesRead);
            totalBytesRead += bytesRead;
            int bytesRemaining = length - totalBytesRead;
            if (bytesRemaining < blockSize) {
              blockSize = bytesRemaining;
            }
            bytesRead = stream.read(byteBuffer, 0, blockSize);
          }
          value_ = baos.toByteArray();
          stream.close(); // @scan1

          if (value_.length < length) {
            // a length longer than the stream was specified
            JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH);
          }
        } catch (ExtendedIOException eie) {
          // the Reader contains non-hex characters
          JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, eie);
        } catch (IOException ie) {
          JDError.throwSQLException(this, JDError.EXC_INTERNAL, ie);
        }
      } else if (length == -2) // @readerlen new else-if block (read all data)
      {
        try {
          int blockSize = AS400JDBCPreparedStatement.LOB_BLOCK_SIZE;
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          HexReaderInputStream stream = new HexReaderInputStream((Reader) object);
          byte[] byteBuffer = new byte[blockSize];
          int totalBytesRead = 0;
          int bytesRead = stream.read(byteBuffer, 0, blockSize);
          while (bytesRead > -1) {
            baos.write(byteBuffer, 0, bytesRead);
            totalBytesRead += bytesRead;

            bytesRead = stream.read(byteBuffer, 0, blockSize);
          }
          value_ = baos.toByteArray();
          stream.close(); // @scan1

        } catch (ExtendedIOException eie) {
          // the Reader contains non-hex characters
          JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, eie);
        } catch (IOException ie) {
          JDError.throwSQLException(this, JDError.EXC_INTERNAL, ie);
        }
      } else {
        JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH);
      }
    } else if (JDUtilities.JDBCLevel_ >= 20 && object instanceof Blob)
      value_ = ((Blob) object).getBytes(1, (int) ((Blob) object).length());
    else if (JDUtilities.JDBCLevel_ >= 20 && object instanceof Clob) {
      try {
        value_ =
            BinaryConverter.stringToBytes(
                ((Clob) object).getSubString(1, (int) ((Clob) object).length()));
      } catch (NumberFormatException nfe) {
        // the Clob contains non-hex characters
        JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, nfe);
      }
    } else JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH);

    // Truncate if necessary.
    int valueLength = value_.length;
    if (valueLength > maxLength_) {
      byte[] newValue = new byte[maxLength_];
      System.arraycopy(value_, 0, newValue, 0, maxLength_);
      value_ = newValue;
      truncated_ = valueLength - maxLength_;
      outOfBounds_ = false;
    } else truncated_ = 0;
    outOfBounds_ = false;

    length_ = value_.length;
  }
Beispiel #28
0
  /**
   * Calls QGYGTLE, repeatedly if necessary, to retrieve the specified number of list entries. This
   * assumes that the list has previously been built on the system.
   *
   * @param system The system where the list has been built.
   * @param listHandle The list handle for the list.
   * @param lengthOfReceiverVariable The value of the "Length of receiver variable" field.
   * @param number The number of list entries to return.
   * @param listOffset The offset into the list (0-based).
   * @param outputListInfoContainer Container in which to receive the generated "List information"
   *     structure. Ignored if null.
   */
  static byte[] retrieveListEntries(
      AS400 system,
      byte[] listHandle,
      int lengthOfReceiverVariable,
      int number,
      int listOffset,
      Object[] outputListInfoContainer)
      throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException,
          IOException, ObjectDoesNotExistException {
    ProgramParameter[] parameters =
        new ProgramParameter[] {
          // Receiver variable, output, char(*).
          new ProgramParameter(lengthOfReceiverVariable),
          // Length of receiver variable, input, binary(4).
          new ProgramParameter(BinaryConverter.intToByteArray(lengthOfReceiverVariable)),
          // Request handle, input, char(4).
          new ProgramParameter(listHandle),
          // List information, output, char(80).
          new ProgramParameter(LIST_INFO_LENGTH),
          // Number of records to return, input, binary(4).
          new ProgramParameter(BinaryConverter.intToByteArray(number)),

          // Starting record, input, binary(4).  (1-based: The first record is record number '1')
          // '0' indicates that the list information should be returned to the caller immediately.
          // The special value 0 is only allowed when the number of records to return parameter is
          // zero.
          // '-1' indicates that the whole list should be built before the list information is
          // returned to the caller.
          new ProgramParameter(
              BinaryConverter.intToByteArray(listOffset == -1 ? -1 : listOffset + 1)),

          // Error code, I/0, char(*).
          new ErrorCodeParameter()
        };

    ProgramCall pc =
        new ProgramCall(
            system, "/QSYS.LIB/QGY.LIB/QGYGTLE.PGM", parameters); // not a threadsafe API

    byte[] listInformation;
    int recordsReturned;

    // Call QGYGTLE, to retrieve the list entries.
    // If we discover that the "receiver variable" was too small, try calling again, with
    // progressively larger "receiver variable".
    do {
      if (pc.run()) {
        listInformation = parameters[3].getOutputData();
        checkListStatus(listInformation);
        recordsReturned = BinaryConverter.byteArrayToInt(listInformation, 4);
      } else // the call to QGYGTLE failed
      {
        listInformation = null;
        recordsReturned = 0;
        // See if the call failed because of a too-small receiver variable.
        AS400Message[] messages = pc.getMessageList();
        // GUI0002 means that the receiver variable was too small to hold the list.
        if (!messages[0].getID().equals("GUI0002")) {
          throw new AS400Exception(messages);
        }
      }

      if (recordsReturned < number) // we didn't get as many records as we requested
      {
        if (listInformation != null) {
          // See if we've reached the end of the list.
          int totalRecords =
              BinaryConverter.byteArrayToInt(
                  listInformation, 0); // The total number of records available in the list.
          int firstRecordInReceiverVariable = BinaryConverter.byteArrayToInt(listInformation, 36);

          // Note: The "First record in receiver variable" field is 1-based; that is, the first
          // record is record number '1' (rather than '0').
          if ((firstRecordInReceiverVariable + recordsReturned) > totalRecords) {
            // All the records in the list have been returned, so don't keep requesting more.
            break;
          }
        }

        if (Trace.traceOn_)
          Trace.log(
              Trace.DIAGNOSTIC,
              "Retrieved messages, records returned: " + recordsReturned + ", number:",
              number);
        if (recordsReturned < 0) { // This will never happen, but satisfy the static code analyzer.
          throw new InternalErrorException(
              InternalErrorException.UNKNOWN, "Records returned: " + recordsReturned);
        }
        // Try again, with a larger "receiver variable".
        lengthOfReceiverVariable *= 1 + number / (recordsReturned + 1);
        if (Trace.traceOn_)
          Trace.log(Trace.DIAGNOSTIC, "Updated length: ", lengthOfReceiverVariable);
        parameters[0] = new ProgramParameter(lengthOfReceiverVariable);
        parameters[1] =
            new ProgramParameter(BinaryConverter.intToByteArray(lengthOfReceiverVariable));
      }
    } while (recordsReturned < number);

    // If the caller specified a non-null 'outputListInfo' parameter, copy the "list information"
    // structure into it, to pass it back to the caller.
    if (outputListInfoContainer != null && listInformation != null) {
      outputListInfoContainer[0] = listInformation;
    }

    return parameters[0].getOutputData(); // the contents of the "receiver variable" field
  }
Beispiel #29
0
 public void convertToRawBytes(byte[] rawBytes, int offset, ConvTable ccsidConverter) // @P0C
     throws SQLException {
   BinaryConverter.intToByteArray(value_, rawBytes, offset); // @D0C
 }
Beispiel #30
0
 // @PDA jdbc40
 public Reader getNCharacterStream() throws SQLException {
   truncated_ = 0;
   outOfBounds_ = false; // @PDC
   return new StringReader(BinaryConverter.bytesToHexString(getBytes())); // @PDC
 }