/**
   * Write String into byte array
   *
   * <p>It will remove a trailing null terminator if exists if the option
   * RemoveTrailingTerminatorOnWrite has been set.
   *
   * @return the data as a byte array in format to write to file
   */
  public byte[] writeByteArray() {
    byte[] data;
    // Try and write to buffer using the CharSet defined by getTextEncodingCharSet()
    String charSetName = getTextEncodingCharSet();
    try {

      stripTrailingNull();

      // Special Handling because there is no UTF16 BOM LE charset
      String stringValue = (String) value;
      String actualCharSet = null;
      if (charSetName.equals(TextEncoding.CHARSET_UTF_16)) {
        if (TagOptionSingleton.getInstance().isEncodeUTF16BomAsLittleEndian()) {
          actualCharSet = TextEncoding.CHARSET_UTF_16_LE_ENCODING_FORMAT;
        } else {
          actualCharSet = TextEncoding.CHARSET_UTF_16_BE_ENCODING_FORMAT;
        }
      }

      // Ensure large enough for any encoding
      ByteBuffer outputBuffer = ByteBuffer.allocate((stringValue.length() + 3) * 3);

      // Ensure each string (if multiple values) is written with BOM by writing separately
      List<String> values = splitByNullSeperator(stringValue);
      checkTrailingNull(values, stringValue);

      // For each value
      for (int i = 0; i < values.size(); i++) {
        String next = values.get(i);
        if (actualCharSet != null) {
          if (actualCharSet.equals(TextEncoding.CHARSET_UTF_16_LE_ENCODING_FORMAT)) {
            outputBuffer.put(writeStringUTF16LEBOM(next, i, values.size()));
          } else if (actualCharSet.equals(TextEncoding.CHARSET_UTF_16_BE_ENCODING_FORMAT)) {
            outputBuffer.put(writeStringUTF16BEBOM(next, i, values.size()));
          }
        } else {
          CharsetEncoder charsetEncoder = Charset.forName(charSetName).newEncoder();
          charsetEncoder.onMalformedInput(CodingErrorAction.IGNORE);
          charsetEncoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
          outputBuffer.put(writeString(charsetEncoder, next, i, values.size()));
        }
      }
      outputBuffer.flip();
      data = new byte[outputBuffer.limit()];
      outputBuffer.rewind();
      outputBuffer.get(data, 0, outputBuffer.limit());
      setSize(data.length);
    }
    // https://bitbucket.org/ijabz/jaudiotagger/issue/1/encoding-metadata-to-utf-16-can-fail-if
    catch (CharacterCodingException ce) {
      logger.severe(ce.getMessage() + ":" + charSetName + ":" + value);
      throw new RuntimeException(ce);
    }
    return data;
  }
Example #2
0
  /** @param args */
  public static void main(String[] args) {

    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {
      // Convert a string to UTF-8 bytes in a ByteBuffer
      ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("http://www.google.co.in/"));
      b = bbuf.array();
    } catch (CharacterCodingException e) {
      System.out.println(e.getMessage());
    }

    String data;
    try {
      data = new String(b, "UTF-8");
      // get a byte matrix for the data
      BitMatrix matrix = null;
      ByteMatrix byteMatrix = null;
      int h = 100;
      int w = 100;
      com.google.zxing.Writer writer = new MultiFormatWriter();
      try {
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        matrix = writer.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
      } catch (com.google.zxing.WriterException e) {
        System.out.println(e.getMessage());
      }

      // change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if
      // you are on windows)
      String filePath = "D:\\CreateQR.JPG";
      File file = new File(filePath);
      try {
        MatrixToImageWriter.writeToFile(matrix, "JPG", file);
        System.out.println("printing to " + file.getAbsolutePath());
      } catch (IOException e) {
        System.out.println(e.getMessage());
      }
    } catch (UnsupportedEncodingException e) {
      System.out.println(e.getMessage());
    }
  }
Example #3
0
  public static void decode(
      CharsetDecoder charsetDecoder, ByteBuffer byteBuf, CharBuffer charByte) {
    try {
      CoderResult cr = charsetDecoder.decode(byteBuf, charByte, true);

      if (!cr.isUnderflow()) {
        cr.throwException();
      }

      cr = charsetDecoder.flush(charByte);

      if (!cr.isUnderflow()) {
        cr.throwException();
      }
    } catch (CharacterCodingException x) {
      // Substitution is always enabled,
      // so this shouldn't happen
      throw new JSONException(x.getMessage(), x);
    }
  }
  /**
   * This method will send an close command, which does not return any rowsets, to the ODBC server.
   *
   * @retrun A CloseReply class representing the reply from the ODBC server is returned
   * @exception A SQLException is thrown
   */
  CloseReply Close() throws SQLException {

    try {
      getInputOutput().setTimeout(m_ic.t4props_.getNetworkTimeout());

      LogicalByteArray wbuffer =
          CloseMessage.marshal(m_dialogueId, m_stmtLabel, SQL_CLOSE, this.m_ic);

      LogicalByteArray rbuffer = getReadBuffer(TRANSPORT.SRVR_API_SQLFREESTMT, wbuffer);

      CloseReply cr = new CloseReply(rbuffer, m_ncsAddress.getIPorName(), m_ic);

      return cr;
    } // end try
    catch (SQLException se) {
      throw se;
    } catch (CharacterCodingException e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_,
              m_locale,
              "translation_of_parameter_failed",
              "CloseMessage",
              e.getMessage());
      se.initCause(e);
      throw se;
    } catch (UnsupportedCharsetException e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_, m_locale, "unsupported_encoding", e.getCharsetName());
      se.initCause(e);
      throw se;
    } catch (Exception e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_, m_locale, "close_message_error", e.getMessage());

      se.initCause(e);
      throw se;
    } // end catch
  } // end Close
  public byte[] encode(char[] chars, int off, int len, byte[] bytes) {
    ByteBuffer byteBuf = ByteBuffer.wrap(bytes);

    CharBuffer charBuf = CharBuffer.wrap(chars, off, len);
    try {
      CoderResult cr = encoder.encode(charBuf, byteBuf, true);
      if (!cr.isUnderflow()) {
        cr.throwException();
      }
      cr = encoder.flush(byteBuf);
      if (!cr.isUnderflow()) {
        cr.throwException();
      }
    } catch (CharacterCodingException x) {
      // Substitution is always enabled,
      // so this shouldn't happen
      throw new JSONException(x.getMessage(), x);
    }

    int bytesLength = byteBuf.position();
    byte[] copy = new byte[bytesLength];
    System.arraycopy(bytes, 0, copy, 0, bytesLength);
    return copy;
  }
  /**
   * This method will send a fetch rowset command to the server.
   *
   * @param maxRowCnt the maximum rowset count to return
   * @param maxRowLen the maximum row length to return
   * @param sqlAsyncEnable a flag to enable/disable asynchronies execution
   * @param queryTimeout the number of seconds before the query times out
   * @retrun a FetchPerfReply class representing the reply from the ODBC server is returned
   * @exception A SQLException is thrown
   */
  FetchReply Fetch(
      int sqlAsyncEnable,
      int queryTimeout,
      int stmtHandle,
      int stmtCharset,
      int maxRowCnt,
      String cursorName,
      int cursorCharset,
      String stmtOptions)
      throws SQLException {

    try {
      getInputOutput().setTimeout(m_ic.t4props_.getNetworkTimeout());

      LogicalByteArray wbuffer =
          FetchMessage.marshal(
              m_dialogueId,
              sqlAsyncEnable,
              queryTimeout,
              stmtHandle,
              m_stmtLabel,
              stmtCharset,
              maxRowCnt,
              0 // infinite row size
              ,
              cursorName,
              cursorCharset,
              stmtOptions,
              this.m_ic);

      LogicalByteArray rbuffer = getReadBuffer(TRANSPORT.SRVR_API_SQLFETCH, wbuffer);

      //
      // Process output parameters
      //
      FetchReply frr = new FetchReply(rbuffer, m_ic);

      return frr;
    } // end try
    catch (SQLException se) {
      throw se;
    } catch (CharacterCodingException e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_,
              m_locale,
              "translation_of_parameter_failed",
              "FetchMessage",
              e.getMessage());
      se.initCause(e);
      throw se;
    } catch (UnsupportedCharsetException e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_, m_locale, "unsupported_encoding", e.getCharsetName());
      se.initCause(e);
      throw se;
    } catch (Exception e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_, m_locale, "fetch_perf_message_error", e.getMessage());

      se.initCause(e);
      throw se;
    } // end catch
  } // end FetchPerf