/**
  * {@collect.stats} {@description.open} Finishes writing compressed data to the output stream
  * without closing the underlying stream. {@description.close} {@property.open} Use this method
  * when applying multiple filters in succession to the same output stream. {@property.close}
  *
  * @exception IOException if an I/O error has occurred
  */
 public void finish() throws IOException {
   if (!def.finished()) {
     def.finish();
     while (!def.finished()) {
       deflate();
     }
   }
 }
 public synchronized void finish() throws IOException {
   if (!_def.finished()) {
     _def.finish();
     while (!_def.finished()) {
       deflate();
     }
   }
 }
 @Override
 public void write(byte[] b, int off, int len) throws IOException {
   if (_def.finished()) throw new IOException("Stream already finished");
   if ((off | len | (off + len) | (b.length - (off + len))) < 0)
     throw new IndexOutOfBoundsException();
   if (len == 0) return;
   if (!_def.finished()) {
     _def.setInput(b, off, len);
     while (!_def.needsInput()) {
       deflate();
     }
   }
 }
示例#4
0
  @Deprecated
  private static synchronized byte[] zipFileName(String fileName) throws IOException {
    Deflater deflater = new Deflater();

    byte[] bytes = fileName.getBytes();
    deflater.setInput(bytes);

    deflater.finish();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
    byte[] buffer = new byte[1024];

    while (!deflater.finished()) {
      int bytesCompressed = deflater.deflate(buffer);
      bos.write(buffer, 0, bytesCompressed);
    }
    bos.close();

    int count = 0;
    for (int i = 0; i < buffer.length; i++) {
      if (buffer[i] != 0) count++;
    }

    byte[] result = new byte[count];
    for (int i = 0; i < result.length; i++) {
      result[i] = buffer[i];
    }

    return result;
  }
 /**
  * deflater 壓縮
  *
  * @param value
  * @return
  */
 public static byte[] deflater(byte[] value) {
   byte[] result = new byte[0];
   Deflater deflater = null;
   ByteArrayOutputStream out = null;
   //
   try {
     deflater = new Deflater();
     deflater.setLevel(Deflater.BEST_SPEED); // fast
     deflater.setInput(value);
     deflater.finish();
     //
     out = new ByteArrayOutputStream();
     byte[] buff = new byte[1024];
     while (!deflater.finished()) {
       int count = deflater.deflate(buff);
       out.write(buff, 0, count);
     }
     //
     result = out.toByteArray();
   } catch (Exception ex) {
     ex.printStackTrace();
   } finally {
     if (deflater != null) {
       deflater.end(); // 需end,不然會有oom(約5000次時)
     }
     IoHelper.close(out);
   }
   return result;
 }
示例#6
0
  public static byte[] deflateObject(byte[] uncompressedData) throws Exception {
    // Create the compressor with highest level of compression
    Deflater deflater = new Deflater();

    deflater.setLevel(Deflater.BEST_COMPRESSION);

    deflater.setInput(uncompressedData);
    deflater.finish();

    // Create an expandable byte array to hold the compressed data.
    // You cannot use an array that's the same size as the orginal because
    // there is no guarantee that the compressed data will be smaller than
    // the uncompressed data.
    ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);

    // Compress the data
    byte[] buf = new byte[1024];
    try {
      while (!deflater.finished()) {
        int count = deflater.deflate(buf);
        bos.write(buf, 0, count);
      }
    } finally {
      try {
        bos.close();
      } catch (IOException io) {
      }
    }

    // Get the compressed data
    return bos.toByteArray();
  }
 /** Ensures all bytes sent to the deflater are written to the stream. */
 private void flushDeflater() throws IOException {
   if (entry.entry.getMethod() == DEFLATED) {
     def.finish();
     while (!def.finished()) {
       deflate();
     }
   }
 }
  /**
   * Writes all necessary data for this entry.
   *
   * @since 1.1
   */
  public void closeEntry() throws IOException {
    if (entry == null) {
      return;
    }

    long realCrc = crc.getValue();
    crc.reset();

    if (entry.getMethod() == DEFLATED) {
      def.finish();
      while (!def.finished()) {
        deflate();
      }

      entry.setSize(def.getTotalIn());
      entry.setComprSize(def.getTotalOut());
      entry.setCrc(realCrc);

      def.reset();

      written += entry.getCompressedSize();
    } else if (raf == null) {
      if (entry.getCrc() != realCrc) {
        throw new SwcException.BadCRC(Long.toHexString(entry.getCrc()), Long.toHexString(realCrc));
      }

      if (entry.getSize() != written - dataStart) {
        throw new SwcException.BadZipSize(
            entry.getName(), entry.getSize() + "", (written - dataStart) + "");
      }
    } else {
        /* method is STORED and we used RandomAccessFile */
      long size = written - dataStart;

      entry.setSize(size);
      entry.setComprSize(size);
      entry.setCrc(realCrc);
    }

    // If random access output, write the local file header containing
    // the correct CRC and compressed/uncompressed sizes
    if (raf != null) {
      long save = raf.getFilePointer();

      raf.seek(localDataStart);
      writeOut((new ZipLong(entry.getCrc())).getBytes());
      writeOut((new ZipLong(entry.getCompressedSize())).getBytes());
      writeOut((new ZipLong(entry.getSize())).getBytes());
      raf.seek(save);
    }

    writeDataDescriptor(entry);
    entry = null;
  }
 private static void deflate(TemporaryBuffer.Heap tinyPack, final byte[] content)
     throws IOException {
   final Deflater deflater = new Deflater();
   final byte[] buf = new byte[128];
   deflater.setInput(content, 0, content.length);
   deflater.finish();
   do {
     final int n = deflater.deflate(buf, 0, buf.length);
     if (n > 0) tinyPack.write(buf, 0, n);
   } while (!deflater.finished());
 }
 /**
  * {@collect.stats} {@description.open} Writes an array of bytes to the compressed output stream.
  * This method will block until all the bytes are written. {@description.close}
  *
  * @param b the data to be written
  * @param off the start offset of the data
  * @param len the length of the data
  * @exception IOException if an I/O error has occurred
  */
 public void write(byte[] b, int off, int len) throws IOException {
   if (def.finished()) {
     throw new IOException("write beyond end of stream");
   }
   if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
     throw new IndexOutOfBoundsException();
   } else if (len == 0) {
     return;
   }
   if (!def.finished()) {
     // Deflate no more than stride bytes at a time.  This avoids
     // excess copying in deflateBytes (see Deflater.c)
     int stride = buf.length;
     for (int i = 0; i < len; i += stride) {
       def.setInput(b, off + i, Math.min(stride, len - i));
       while (!def.needsInput()) {
         deflate();
       }
     }
   }
 }
示例#11
0
  /**
   * Reads compressed data into a byte array. This method will block until some input can be read
   * and compressed.
   *
   * @param b buffer into which the data is read
   * @param off starting offset of the data within {@code b}
   * @param len maximum number of compressed bytes to read into {@code b}
   * @return the actual number of bytes read, or -1 if the end of the uncompressed input stream is
   *     reached
   * @throws IndexOutOfBoundsException if {@code len} > {@code b.length - off}
   * @throws IOException if an I/O error occurs or if this input stream is already closed
   */
  public int read(byte[] b, int off, int len) throws IOException {
    // Sanity checks
    ensureOpen();
    if (b == null) {
      throw new NullPointerException("Null buffer for read");
    } else if (off < 0 || len < 0 || len > b.length - off) {
      throw new IndexOutOfBoundsException();
    } else if (len == 0) {
      return 0;
    }

    // Read and compress (deflate) input data bytes
    int cnt = 0;
    while (len > 0 && !def.finished()) {
      int n;

      // Read data from the input stream
      if (def.needsInput()) {
        n = in.read(buf, 0, buf.length);
        if (n < 0) {
          // End of the input stream reached
          def.finish();
        } else if (n > 0) {
          def.setInput(buf, 0, n);
        }
      }

      // Compress the input data, filling the read buffer
      n = def.deflate(b, off, len);
      cnt += n;
      off += n;
      len -= n;
    }
    if (cnt == 0 && def.finished()) {
      reachEOF = true;
      cnt = -1;
    }

    return cnt;
  }
示例#12
0
 public static byte[] compress(byte[] input) throws IOException {
   Deflater compressor = new Deflater();
   compressor.setLevel(Deflater.BEST_SPEED);
   compressor.setInput(input);
   compressor.finish();
   ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length / 10);
   byte[] buf = new byte[input.length / 10];
   while (!compressor.finished()) {
     int count = compressor.deflate(buf);
     bos.write(buf, 0, count);
   }
   bos.close();
   compressor.end();
   return bos.toByteArray();
 }
 /** Writes bytes to ZIP entry. */
 public void write(byte[] b, int offset, int length) throws IOException {
   if (entry.getMethod() == DEFLATED) {
     if (length > 0) {
       if (!def.finished()) {
         def.setInput(b, offset, length);
         while (!def.needsInput()) {
           deflate();
         }
       }
     }
   } else {
     writeOut(b, offset, length);
     written += length;
   }
   crc.update(b, offset, length);
 }
示例#14
0
  private static byte[] deflate(byte[] input) {

    Deflater compressor = new Deflater(Deflater.DEFLATED);
    compressor.setInput(input);
    compressor.finish();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);

    byte[] buf = new byte[CHUNKSIZE];

    while (!compressor.finished()) {
      int count = compressor.deflate(buf);
      bos.write(buf, 0, count);
    }

    return bos.toByteArray();
  }
 /** write implementation for DEFLATED entries. */
 private void writeDeflated(byte[] b, int offset, int length) throws IOException {
   if (length > 0 && !def.finished()) {
     entry.bytesRead += length;
     if (length <= DEFLATER_BLOCK_SIZE) {
       def.setInput(b, offset, length);
       deflateUntilInputIsNeeded();
     } else {
       final int fullblocks = length / DEFLATER_BLOCK_SIZE;
       for (int i = 0; i < fullblocks; i++) {
         def.setInput(b, offset + i * DEFLATER_BLOCK_SIZE, DEFLATER_BLOCK_SIZE);
         deflateUntilInputIsNeeded();
       }
       final int done = fullblocks * DEFLATER_BLOCK_SIZE;
       if (done < length) {
         def.setInput(b, offset + done, length - done);
         deflateUntilInputIsNeeded();
       }
     }
   }
 }
  /* (non-Javadoc)
   * @see org.eclipse.jetty.websocket.AbstractExtension#addFrame(byte, byte, byte[], int, int)
   */
  @Override
  public void addFrame(byte flags, byte opcode, byte[] content, int offset, int length)
      throws IOException {
    if (getConnection().isControl(opcode) || length < _minLength) {
      super.addFrame(clearFlag(flags, 1), opcode, content, offset, length);
      return;
    }

    // prepare the uncompressed input
    _deflater.reset();
    _deflater.setInput(content, offset, length);
    _deflater.finish();

    // prepare the output buffer
    byte[] out = new byte[length];
    int out_offset = 0;

    // write the uncompressed length
    if (length > 0xffff) {
      out[out_offset++] = 0x7f;
      out[out_offset++] = (byte) 0;
      out[out_offset++] = (byte) 0;
      out[out_offset++] = (byte) 0;
      out[out_offset++] = (byte) 0;
      out[out_offset++] = (byte) ((length >> 24) & 0xff);
      out[out_offset++] = (byte) ((length >> 16) & 0xff);
      out[out_offset++] = (byte) ((length >> 8) & 0xff);
      out[out_offset++] = (byte) (length & 0xff);
    } else if (length >= 0x7e) {
      out[out_offset++] = 0x7e;
      out[out_offset++] = (byte) (length >> 8);
      out[out_offset++] = (byte) (length & 0xff);
    } else {
      out[out_offset++] = (byte) (length & 0x7f);
    }

    int l = _deflater.deflate(out, out_offset, length - out_offset);

    if (_deflater.finished()) super.addFrame(setFlag(flags, 1), opcode, out, 0, l + out_offset);
    else super.addFrame(clearFlag(flags, 1), opcode, content, offset, length);
  }
  @Test
  public void testDeflateBasics() throws Exception {
    // Setup deflater basics
    boolean nowrap = true;
    Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION, nowrap);
    compressor.setStrategy(Deflater.DEFAULT_STRATEGY);

    // Text to compress
    String text = "info:";
    byte uncompressed[] = StringUtil.getUtf8Bytes(text);

    // Prime the compressor
    compressor.reset();
    compressor.setInput(uncompressed, 0, uncompressed.length);
    compressor.finish();

    // Perform compression
    ByteBuffer outbuf = ByteBuffer.allocate(64);
    BufferUtil.clearToFill(outbuf);

    while (!compressor.finished()) {
      byte out[] = new byte[64];
      int len = compressor.deflate(out, 0, out.length, Deflater.SYNC_FLUSH);
      if (len > 0) {
        outbuf.put(out, 0, len);
      }
    }
    compressor.end();

    BufferUtil.flipToFlush(outbuf, 0);
    byte b0 = outbuf.get(0);
    if ((b0 & 1) != 0) {
      outbuf.put(0, (b0 ^= 1));
    }
    byte compressed[] = BufferUtil.toArray(outbuf);

    String actual = TypeUtil.toHexString(compressed);
    String expected = "CaCc4bCbB70200"; // what pywebsocket produces

    Assert.assertThat("Compressed data", actual, is(expected));
  }
示例#18
0
文件: NetUtil.java 项目: niczy/hyo
 /**
  * compress a byte array to a new byte array by {@link java.util.zip.Deflater}
  *
  * @param data input data to compress
  * @param len the 0..length in data is for compress
  * @return compressed byte array
  */
 public static byte[] deflateCompress(byte[] data) {
   Deflater compresser = new Deflater();
   ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
   try {
     compresser.reset();
     compresser.setInput(data, 0, data.length);
     compresser.finish();
     byte[] buf = new byte[1024];
     while (!compresser.finished()) {
       int i = compresser.deflate(buf);
       bos.write(buf, 0, i);
     }
     return bos.toByteArray();
   } finally {
     compresser.end();
     try {
       bos.close();
     } catch (IOException e) {
     }
   }
 }
示例#19
0
 // TODO move to separate thread?
 public void compress() {
   if (!compressed) {
     Deflater deflater = new Deflater();
     deflater.setInput(fileData);
     deflater.setLevel(Deflater.BEST_COMPRESSION);
     deflater.finish();
     ByteArrayOutputStream bos = new ByteArrayOutputStream(fileData.length);
     byte[] buffer = new byte[1024];
     while (!deflater.finished()) {
       int bytesCompressed = deflater.deflate(buffer);
       bos.write(buffer, 0, bytesCompressed);
     }
     try {
       bos.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
     fileData = bos.toByteArray();
     compressed = true;
   }
 }
示例#20
0
  public static byte[] compress(byte[] data) throws Exception {
    Deflater def = new Deflater();
    def.setInput(data);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);

    def.finish();

    byte[] buf = new byte[1024];

    while (!def.finished()) {

      int compressed = def.deflate(buf);

      baos.write(buf, 0, compressed);
    }

    baos.close();

    return baos.toByteArray();
  }
示例#21
0
  public static byte[] compress(String data) {
    byte[] encodedData;
    try {
      encodedData = data.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("Compression error: UTF-8 is not supported. " + "Using default encoding.");
      encodedData = data.getBytes();
    }

    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
    deflater.setInput(encodedData);
    deflater.finish();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    while (!deflater.finished()) {
      int byteCount = deflater.deflate(buf);
      baos.write(buf, 0, byteCount);
    }
    deflater.end();

    byte[] compressedData = baos.toByteArray();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
      outputStream.write(ByteBuffer.allocate(4).putInt(encodedData.length).array());
    } catch (IOException e) {
      System.out.println("Compression error: Unable to write compressed data length.");
      e.printStackTrace();
    }
    try {
      outputStream.write(compressedData);
    } catch (IOException e) {
      System.out.println("Compression error: Unable to write compressed data.");
      e.printStackTrace();
    }

    return outputStream.toByteArray();
  }
示例#22
0
  public static byte[] compress(byte[] data) throws IOException {

    Deflater deflater = new Deflater();
    deflater.setInput(data);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
    deflater.finish();
    byte[] buffer = new byte[1024];

    while (!deflater.finished()) {
      int count = deflater.deflate(buffer); // returns the generated code... index
      outputStream.write(buffer, 0, count);
    }

    outputStream.close();
    byte[] output = outputStream.toByteArray();

    System.out.println("Original: " + data.length / 1024 + " Kb");

    System.out.println("Compressed: " + output.length / 1024 + " Kb");

    return output;
  }
示例#23
0
  /**
   * Use the Compression object method to deflate the query string
   *
   * @param queryStr An un-compressed CQL query string
   * @param compression The compression object
   * @return A compressed string
   */
  public static ByteBuffer compressQuery(String queryStr, Compression compression) {
    byte[] data = queryStr.getBytes(Charsets.UTF_8);
    Deflater compressor = new Deflater();
    compressor.setInput(data);
    compressor.finish();

    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];

    try {
      while (!compressor.finished()) {
        int size = compressor.deflate(buffer);
        byteArray.write(buffer, 0, size);
      }
    } finally {
      compressor.end(); // clean up after the Deflater
    }

    logger.trace(
        "Compressed query statement {} bytes in length to {} bytes", data.length, byteArray.size());

    return ByteBuffer.wrap(byteArray.toByteArray());
  }
示例#24
0
  /**
   * Compresses the data in a byte array.
   *
   * @param input The byte array to be compressed.
   * @return The byte array in its compressed form.
   */
  public static byte[] compress(byte[] input) {
    try {
      final Deflater deflater = new Deflater();
      deflater.setLevel(Deflater.BEST_COMPRESSION);
      deflater.setInput(input);

      final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(input.length);
      deflater.finish();

      final byte[] buffer = new byte[1024];

      while (!deflater.finished()) {
        final int count = deflater.deflate(buffer);
        byteOutput.write(buffer, 0, count);
      }

      byteOutput.close();
      return byteOutput.toByteArray();
    } catch (final IOException e) {
      RadixCore.getInstance().quitWithException("Error compressing byte array.", e);
      return null;
    }
  }
  private static ActiveMQMessage toAMQMessage(
      MessageReference reference,
      ServerMessage coreMessage,
      WireFormat marshaller,
      ActiveMQDestination actualDestination)
      throws IOException {
    ActiveMQMessage amqMsg = null;
    byte coreType = coreMessage.getType();
    switch (coreType) {
      case org.apache.activemq.artemis.api.core.Message.BYTES_TYPE:
        amqMsg = new ActiveMQBytesMessage();
        break;
      case org.apache.activemq.artemis.api.core.Message.MAP_TYPE:
        amqMsg = new ActiveMQMapMessage();
        break;
      case org.apache.activemq.artemis.api.core.Message.OBJECT_TYPE:
        amqMsg = new ActiveMQObjectMessage();
        break;
      case org.apache.activemq.artemis.api.core.Message.STREAM_TYPE:
        amqMsg = new ActiveMQStreamMessage();
        break;
      case org.apache.activemq.artemis.api.core.Message.TEXT_TYPE:
        amqMsg = new ActiveMQTextMessage();
        break;
      case org.apache.activemq.artemis.api.core.Message.DEFAULT_TYPE:
        amqMsg = new ActiveMQMessage();
        break;
      default:
        throw new IllegalStateException("Unknown message type: " + coreMessage.getType());
    }

    String type = coreMessage.getStringProperty(new SimpleString("JMSType"));
    if (type != null) {
      amqMsg.setJMSType(type);
    }
    amqMsg.setPersistent(coreMessage.isDurable());
    amqMsg.setExpiration(coreMessage.getExpiration());
    amqMsg.setPriority(coreMessage.getPriority());
    amqMsg.setTimestamp(coreMessage.getTimestamp());

    Long brokerInTime = (Long) coreMessage.getObjectProperty(AMQ_MSG_BROKER_IN_TIME);
    if (brokerInTime == null) {
      brokerInTime = 0L;
    }
    amqMsg.setBrokerInTime(brokerInTime);

    ActiveMQBuffer buffer = coreMessage.getBodyBufferDuplicate();
    Boolean compressProp = (Boolean) coreMessage.getObjectProperty(AMQ_MSG_COMPRESSED);
    boolean isCompressed = compressProp == null ? false : compressProp.booleanValue();
    amqMsg.setCompressed(isCompressed);

    if (buffer != null) {
      buffer.resetReaderIndex();
      byte[] bytes = null;
      synchronized (buffer) {
        if (coreType == org.apache.activemq.artemis.api.core.Message.TEXT_TYPE) {
          SimpleString text = buffer.readNullableSimpleString();
          if (text != null) {
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(text.length() + 4);
            OutputStream out = bytesOut;
            if (isCompressed) {
              out = new DeflaterOutputStream(out);
            }
            try (DataOutputStream dataOut = new DataOutputStream(out)) {
              MarshallingSupport.writeUTF8(dataOut, text.toString());
              bytes = bytesOut.toByteArray();
            }
          }
        } else if (coreType == org.apache.activemq.artemis.api.core.Message.MAP_TYPE) {
          TypedProperties mapData = new TypedProperties();
          // it could be a null map
          if (buffer.readableBytes() > 0) {
            mapData.decode(buffer);
            Map<String, Object> map = mapData.getMap();
            ByteArrayOutputStream out = new ByteArrayOutputStream(mapData.getEncodeSize());
            OutputStream os = out;
            if (isCompressed) {
              os = new DeflaterOutputStream(os);
            }
            try (DataOutputStream dataOut = new DataOutputStream(os)) {
              MarshallingSupport.marshalPrimitiveMap(map, dataOut);
            }
            bytes = out.toByteArray();
          }

        } else if (coreType == org.apache.activemq.artemis.api.core.Message.OBJECT_TYPE) {
          int len = buffer.readInt();
          bytes = new byte[len];
          buffer.readBytes(bytes);
          if (isCompressed) {
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            try (DeflaterOutputStream out = new DeflaterOutputStream(bytesOut)) {
              out.write(bytes);
            }
            bytes = bytesOut.toByteArray();
          }
        } else if (coreType == org.apache.activemq.artemis.api.core.Message.STREAM_TYPE) {
          org.apache.activemq.util.ByteArrayOutputStream bytesOut =
              new org.apache.activemq.util.ByteArrayOutputStream();
          OutputStream out = bytesOut;
          if (isCompressed) {
            out = new DeflaterOutputStream(bytesOut);
          }
          try (DataOutputStream dataOut = new DataOutputStream(out)) {

            boolean stop = false;
            while (!stop && buffer.readable()) {
              byte primitiveType = buffer.readByte();
              switch (primitiveType) {
                case DataConstants.BOOLEAN:
                  MarshallingSupport.marshalBoolean(dataOut, buffer.readBoolean());
                  break;
                case DataConstants.BYTE:
                  MarshallingSupport.marshalByte(dataOut, buffer.readByte());
                  break;
                case DataConstants.BYTES:
                  int len = buffer.readInt();
                  byte[] bytesData = new byte[len];
                  buffer.readBytes(bytesData);
                  MarshallingSupport.marshalByteArray(dataOut, bytesData);
                  break;
                case DataConstants.CHAR:
                  char ch = (char) buffer.readShort();
                  MarshallingSupport.marshalChar(dataOut, ch);
                  break;
                case DataConstants.DOUBLE:
                  double doubleVal = Double.longBitsToDouble(buffer.readLong());
                  MarshallingSupport.marshalDouble(dataOut, doubleVal);
                  break;
                case DataConstants.FLOAT:
                  Float floatVal = Float.intBitsToFloat(buffer.readInt());
                  MarshallingSupport.marshalFloat(dataOut, floatVal);
                  break;
                case DataConstants.INT:
                  MarshallingSupport.marshalInt(dataOut, buffer.readInt());
                  break;
                case DataConstants.LONG:
                  MarshallingSupport.marshalLong(dataOut, buffer.readLong());
                  break;
                case DataConstants.SHORT:
                  MarshallingSupport.marshalShort(dataOut, buffer.readShort());
                  break;
                case DataConstants.STRING:
                  String string = buffer.readNullableString();
                  if (string == null) {
                    MarshallingSupport.marshalNull(dataOut);
                  } else {
                    MarshallingSupport.marshalString(dataOut, string);
                  }
                  break;
                default:
                  // now we stop
                  stop = true;
                  break;
              }
            }
          }
          bytes = bytesOut.toByteArray();
        } else if (coreType == org.apache.activemq.artemis.api.core.Message.BYTES_TYPE) {
          int n = buffer.readableBytes();
          bytes = new byte[n];
          buffer.readBytes(bytes);
          if (isCompressed) {
            int length = bytes.length;
            Deflater deflater = new Deflater();
            try (org.apache.activemq.util.ByteArrayOutputStream compressed =
                new org.apache.activemq.util.ByteArrayOutputStream()) {
              compressed.write(new byte[4]);
              deflater.setInput(bytes);
              deflater.finish();
              byte[] bytesBuf = new byte[1024];
              while (!deflater.finished()) {
                int count = deflater.deflate(bytesBuf);
                compressed.write(bytesBuf, 0, count);
              }
              ByteSequence byteSeq = compressed.toByteSequence();
              ByteSequenceData.writeIntBig(byteSeq, length);
              bytes = Arrays.copyOfRange(byteSeq.data, 0, byteSeq.length);
            } finally {
              deflater.end();
            }
          }
        } else {
          int n = buffer.readableBytes();
          bytes = new byte[n];
          buffer.readBytes(bytes);
          if (isCompressed) {
            try (ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
                DeflaterOutputStream out = new DeflaterOutputStream(bytesOut)) {
              out.write(bytes);
              bytes = bytesOut.toByteArray();
            }
          }
        }

        buffer.resetReaderIndex(); // this is important for topics as the buffer
        // may be read multiple times
      }

      if (bytes != null) {
        ByteSequence content = new ByteSequence(bytes);
        amqMsg.setContent(content);
      }
    }

    // we need check null because messages may come from other clients
    // and those amq specific attribute may not be set.
    Long arrival = (Long) coreMessage.getObjectProperty(AMQ_MSG_ARRIVAL);
    if (arrival == null) {
      // messages from other sources (like core client) may not set this prop
      arrival = 0L;
    }
    amqMsg.setArrival(arrival);

    String brokerPath = (String) coreMessage.getObjectProperty(AMQ_MSG_BROKER_PATH);
    if (brokerPath != null && brokerPath.isEmpty()) {
      String[] brokers = brokerPath.split(",");
      BrokerId[] bids = new BrokerId[brokers.length];
      for (int i = 0; i < bids.length; i++) {
        bids[i] = new BrokerId(brokers[i]);
      }
      amqMsg.setBrokerPath(bids);
    }

    String clusterPath = (String) coreMessage.getObjectProperty(AMQ_MSG_CLUSTER);
    if (clusterPath != null && clusterPath.isEmpty()) {
      String[] cluster = clusterPath.split(",");
      BrokerId[] bids = new BrokerId[cluster.length];
      for (int i = 0; i < bids.length; i++) {
        bids[i] = new BrokerId(cluster[i]);
      }
      amqMsg.setCluster(bids);
    }

    Integer commandId = (Integer) coreMessage.getObjectProperty(AMQ_MSG_COMMAND_ID);
    if (commandId == null) {
      commandId = -1;
    }
    amqMsg.setCommandId(commandId);

    SimpleString corrId = (SimpleString) coreMessage.getObjectProperty("JMSCorrelationID");
    if (corrId != null) {
      amqMsg.setCorrelationId(corrId.toString());
    }

    byte[] dsBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_DATASTRUCTURE);
    if (dsBytes != null) {
      ByteSequence seq = new ByteSequence(dsBytes);
      DataStructure ds = (DataStructure) marshaller.unmarshal(seq);
      amqMsg.setDataStructure(ds);
    }

    amqMsg.setDestination(OpenWireUtil.toAMQAddress(coreMessage, actualDestination));

    Object value = coreMessage.getObjectProperty(AMQ_MSG_GROUP_ID);
    if (value != null) {
      String groupId = value.toString();
      amqMsg.setGroupID(groupId);
    }

    Integer groupSequence = (Integer) coreMessage.getObjectProperty(AMQ_MSG_GROUP_SEQUENCE);
    if (groupSequence == null) {
      groupSequence = -1;
    }
    amqMsg.setGroupSequence(groupSequence);

    MessageId mid = null;
    byte[] midBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_MESSAGE_ID);
    if (midBytes != null) {
      ByteSequence midSeq = new ByteSequence(midBytes);
      mid = (MessageId) marshaller.unmarshal(midSeq);
    } else {
      mid = new MessageId(UUIDGenerator.getInstance().generateStringUUID() + ":-1");
    }

    amqMsg.setMessageId(mid);

    byte[] origDestBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_ORIG_DESTINATION);
    if (origDestBytes != null) {
      ActiveMQDestination origDest =
          (ActiveMQDestination) marshaller.unmarshal(new ByteSequence(origDestBytes));
      amqMsg.setOriginalDestination(origDest);
    }

    byte[] origTxIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_ORIG_TXID);
    if (origTxIdBytes != null) {
      TransactionId origTxId =
          (TransactionId) marshaller.unmarshal(new ByteSequence(origTxIdBytes));
      amqMsg.setOriginalTransactionId(origTxId);
    }

    byte[] producerIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_PRODUCER_ID);
    if (producerIdBytes != null) {
      ProducerId producerId = (ProducerId) marshaller.unmarshal(new ByteSequence(producerIdBytes));
      amqMsg.setProducerId(producerId);
    }

    byte[] marshalledBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_MARSHALL_PROP);
    if (marshalledBytes != null) {
      amqMsg.setMarshalledProperties(new ByteSequence(marshalledBytes));
    }

    amqMsg.setRedeliveryCounter(reference.getDeliveryCount() - 1);

    byte[] replyToBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_REPLY_TO);
    if (replyToBytes != null) {
      ActiveMQDestination replyTo =
          (ActiveMQDestination) marshaller.unmarshal(new ByteSequence(replyToBytes));
      amqMsg.setReplyTo(replyTo);
    }

    String userId = (String) coreMessage.getObjectProperty(AMQ_MSG_USER_ID);
    if (userId != null) {
      amqMsg.setUserID(userId);
    }

    Boolean isDroppable = (Boolean) coreMessage.getObjectProperty(AMQ_MSG_DROPPABLE);
    if (isDroppable != null) {
      amqMsg.setDroppable(isDroppable);
    }

    SimpleString dlqCause =
        (SimpleString) coreMessage.getObjectProperty(AMQ_MSG_DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY);
    if (dlqCause != null) {
      try {
        amqMsg.setStringProperty(
            ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY, dlqCause.toString());
      } catch (JMSException e) {
        throw new IOException("failure to set dlq property " + dlqCause, e);
      }
    }

    Set<SimpleString> props = coreMessage.getPropertyNames();
    if (props != null) {
      for (SimpleString s : props) {
        String keyStr = s.toString();
        if (keyStr.startsWith("_AMQ") || keyStr.startsWith("__HDR_")) {
          continue;
        }
        Object prop = coreMessage.getObjectProperty(s);
        try {
          if (prop instanceof SimpleString) {
            amqMsg.setObjectProperty(s.toString(), prop.toString());
          } else {
            amqMsg.setObjectProperty(s.toString(), prop);
          }
        } catch (JMSException e) {
          throw new IOException("exception setting property " + s + " : " + prop, e);
        }
      }
    }
    try {
      amqMsg.onSend();
      amqMsg.setCompressed(isCompressed);
    } catch (JMSException e) {
      throw new IOException("Failed to covert to Openwire message", e);
    }
    return amqMsg;
  }