下面列出了怎么用java.util.zip.InflaterOutputStream的API类实例代码及写法,或者点击链接到github查看源代码。
private void saveContent(IActionContext actionContext, HashMap<?, ?> inputData, InputStream source) throws Exception {
String fileAlias = unwrapFilters(inputData.get("FileAlias"));
boolean compress = BooleanUtils.toBoolean((String)unwrapFilters(inputData.get("Compress")));
boolean append = BooleanUtils.toBoolean((String)unwrapFilters(inputData.get("Append")));
IDataManager dataManager = actionContext.getDataManager();
SailfishURI target = SailfishURI.parse(fileAlias);
if (dataManager.exists(target)) {
try (OutputStream dm = dataManager.getDataOutputStream(target, append); OutputStream os = compress ? new InflaterOutputStream(dm) : dm) {
IOUtils.copy(source, os);
actionContext.getReport().createMessage(StatusType.NA, MessageLevel.INFO, format("Content has been saved by %s", fileAlias));
}
} else {
throw new EPSCommonException(format("Specified %s file alias does not exists", fileAlias));
}
}
public Memory(Document document) {
String zipBytesStr = (String) document.get("zipBytes");
if (zipBytesStr != null) {
byte[] compressedBytes = Base64.getDecoder().decode((String) document.get("zipBytes"));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(baos, decompressor);
inflaterOutputStream.write(compressedBytes);
inflaterOutputStream.close();
setBytes(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} else {
LogManager.LOGGER.severe("Memory was manually deleted");
words = new char[GameServer.INSTANCE.getConfig().getInt("memory_size")];
}
}
public Flux<ByteBuf> completeMessages(Flux<ByteBuf> payloads) {
return payloads.windowUntil(windowPredicate)
.flatMap(Flux::collectList)
.map(list -> {
final ByteBuf buf;
if (list.size() == 1) {
buf = list.get(0);
} else {
CompositeByteBuf composite = allocator.compositeBuffer(list.size());
for (ByteBuf component : list) {
composite.addComponent(true, component);
}
buf = composite;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (InflaterOutputStream inflater = new InflaterOutputStream(out, context)) {
inflater.write(ByteBufUtil.getBytes(buf, buf.readerIndex(), buf.readableBytes(), false));
return allocator.buffer().writeBytes(out.toByteArray()).asReadOnly();
} catch (IOException e) {
throw Exceptions.propagate(e);
}
});
}
public boolean nextPayload() throws IOException {
if (this.offset == this.packetData.length) {
return false;
}
// read compressed packet header
this.compressedPayloadLen = NativeUtils.decodeMysqlThreeByteInteger(this.packetData, this.offset);
this.compressedSequenceId = this.packetData[this.offset + 3];
this.uncompressedPayloadLen = NativeUtils.decodeMysqlThreeByteInteger(this.packetData, this.offset + 4);
this.offset += CompressedPacketSender.COMP_HEADER_LENGTH;
if (this.uncompressedPayloadLen == 0) {
// uncompressed packet
this.payload = java.util.Arrays.copyOfRange(this.packetData, this.offset, this.offset + this.compressedPayloadLen);
} else {
// uncompress payload
InflaterOutputStream inflater = new InflaterOutputStream(this.decompressedStream);
inflater.write(this.packetData, this.offset, this.compressedPayloadLen);
inflater.finish();
inflater.flush();
this.payload = this.decompressedStream.toByteArray();
this.decompressedStream.reset();
}
this.offset += this.compressedPayloadLen;
return true;
}
/**
* java.util.zip.InflaterOutputStream#InflaterOutputStream(java.io.OutputStream)
*/
/* J2ObjC removed: not supported by Junit 4.11 (https://github.com/google/j2objc/issues/1318).
@DisableResourceLeakageDetection(
why = "InflaterOutputStream does not clean up the default Inflater created in the"
+ " constructor if the constructor fails; i.e. constructor calls"
+ " this(..., new Inflater(), ...) and that constructor fails but does not know"
+ " that it needs to call Inflater.end() as the caller has no access to it",
bug = "31798154") */
public void test_ConstructorLjava_io_OutputStream() throws IOException {
new InflaterOutputStream(os).close();
try {
new InflaterOutputStream(null);
fail("Should throw NullPointerException");
} catch (NullPointerException e) {
// expected
}
}
@Override
public byte[] decompress(final byte[] data) {
if (data == null) {
return null;
}
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(data.length);
final InflaterOutputStream inflaterStream = new InflaterOutputStream(buffer, new Inflater());
try {
inflaterStream.write(data);
inflaterStream.close();
buffer.close();
} catch (final IOException e) {
throw new RuntimeException("failed compressing using deflate", e);
}
return buffer.toByteArray();
}
public static byte[] inflate(byte[] bytes) {
try {
ByteArrayOutputStream a = new ByteArrayOutputStream();
try ( InflaterOutputStream out = new InflaterOutputStream(a)) {
out.write(bytes);
out.flush();
}
return a.toByteArray();
} catch (Exception e) {
return null;
}
}
/**
* Inflate the given byte array by {@link #INFLATED_ARRAY_LENGTH}.
*
* @param bytes the bytes
* @return the array as a string with <code>UTF-8</code> encoding
*/
public static String inflate(final byte[] bytes) {
try (ByteArrayInputStream inb = new ByteArrayInputStream(bytes);
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream ios = new InflaterOutputStream(out);) {
IOUtils.copy(inb, ios);
return new String(out.toByteArray(), UTF8_ENCODING);
} catch (final Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static String decompressData(String encdata) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InflaterOutputStream zos = new InflaterOutputStream(bos);
zos.write(getdeBASE64inCodec(encdata));
zos.close();
return new String(bos.toByteArray());
} catch (Exception ex) {
ex.printStackTrace();
return "UNZIP_ERR";
}
}
public static String decompressData(String encdata, String charset) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InflaterOutputStream zos = new InflaterOutputStream(bos);
zos.write(getdeBASE64inCodec(encdata));
zos.close();
return new String(bos.toByteArray(), charset);
} catch (Exception ex) {
ex.printStackTrace();
return "UNZIP_ERR";
}
}
public static byte[] zlib_decompress(byte[] encdata,int offset,int size) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream inf = new InflaterOutputStream(out);
inf.write(encdata,offset, size);
inf.close();
return out.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
//show(emptyStr);
return "ERR".getBytes();
}
}
public static byte[] zlib_decompress(byte[] encdata,int offset) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream inf = new InflaterOutputStream(out);
inf.write(encdata,offset, encdata.length-offset);
inf.close();
return out.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
return "ERR".getBytes();
}
}
@Deprecated
public static byte[] zlib_decompress(byte[] encdata,int offset,int ln) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream inf = new InflaterOutputStream(out);
inf.write(encdata,offset, ln);
inf.close();
return out.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
return "ERR".getBytes();
}
}
public static String decompressData(String encdata) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InflaterOutputStream zos = new InflaterOutputStream(bos);
zos.write(getdeBASE64inCodec(encdata));
zos.close();
return new String(bos.toByteArray());
} catch (Exception ex) {
ex.printStackTrace();
return "UNZIP_ERR";
}
}
public static String decompressData(String encdata, String charset) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InflaterOutputStream zos = new InflaterOutputStream(bos);
zos.write(getdeBASE64inCodec(encdata));
zos.close();
return new String(bos.toByteArray(), charset);
} catch (Exception ex) {
ex.printStackTrace();
return "UNZIP_ERR";
}
}
private JsonNode receiveCompressedMessage() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(bos);
try {
inflaterOutputStream.write(receive());
inflaterOutputStream.close();
return new ObjectMapper().readTree(bos.toByteArray());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private byte[] inflate(byte[] uncompressed) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (InflaterOutputStream deflaterOutputStream = new InflaterOutputStream(byteArrayOutputStream)) {
deflaterOutputStream.write(uncompressed);
} catch (IOException e) {
throw new RuntimeException(e);
}
return byteArrayOutputStream.toByteArray();
}
protected void readCompressedData(byte[] readData) throws IOException {
if (readData.length == originalLength) {
this.tableData = readData;
return;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream compressStream = new InflaterOutputStream(out);
compressStream.write(readData);
compressStream.close();
tableData = out.toByteArray();
}
private String inflate(byte[] decodedBytes) throws IOException {
ByteArrayOutputStream inflatedBytes = new ByteArrayOutputStream();
Inflater inflater = new Inflater(true);
InflaterOutputStream inflaterStream = new InflaterOutputStream(inflatedBytes, inflater);
inflaterStream.write(decodedBytes);
inflaterStream.finish();
return new String(inflatedBytes.toByteArray());
}
private ByteBuf inflateCompressedFrame(final ChannelHandlerContext ctx, final ByteBuf in) throws IOException {
ByteBuf buffer = ctx.alloc().buffer(requiredBytes);
Inflater inflater = new Inflater();
try (
ByteBufOutputStream buffOutput = new ByteBufOutputStream(buffer);
InflaterOutputStream inflaterStream = new InflaterOutputStream(buffOutput, inflater)
) {
in.readBytes(inflaterStream, requiredBytes);
}finally{
inflater.end();
}
return buffer;
}
/**
* Test method for
* {@link kieker.monitoring.writer.compression.DeflateCompressionFilter#chainOutputStream(java.io.OutputStream, java.nio.file.Path)}.
*/
@Test
public void testChainOutputStream() {
final String inputStr = "Hello World";
final byte[] inputData = inputStr.getBytes(Charset.defaultCharset());
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(byteArrayOutputStream);
final Configuration configuration = ConfigurationFactory.createDefaultConfiguration();
final DeflateCompressionFilter unit = new DeflateCompressionFilter(configuration);
final Path path = Paths.get("");
try {
// Passing inflated output stream
final OutputStream value = unit.chainOutputStream(inflaterOutputStream, path);
// Writing byte array to stream
value.write(inputData);
// Closing stream
value.close();
// Checking if input byte array is equal to byteArrayOutputStream
Assert.assertArrayEquals("Inflated result does not match input data", inputData,
byteArrayOutputStream.toByteArray());
} catch (final IOException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test
public void addItem() throws IOException
{
victim.addItem(context.createIndirectReferenceFor(COSInteger.ZERO));
victim.addItem(context.createIndirectReferenceFor(COSInteger.THREE));
victim.prepareForWriting();
assertEquals(COSName.OBJ_STM.getName(), victim.getNameAsString(COSName.TYPE));
assertEquals(2, victim.getInt(COSName.N));
assertEquals(8, victim.getInt(COSName.FIRST));
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(victim.getFilteredStream(), new InflaterOutputStream(out));
byte[] data = new byte[] { 49, 32, 48, 32, 50, 32, 50, 32, 48, 32, 51, 32 };
assertArrayEquals(data, out.toByteArray());
}
private static ByteSequence writeCompressedDefaultType(final ByteSequence contents) throws IOException {
try (org.apache.activemq.util.ByteArrayOutputStream decompressed = new org.apache.activemq.util.ByteArrayOutputStream();
OutputStream os = new InflaterOutputStream(decompressed)) {
os.write(contents.data, contents.offset, contents.getLength());
return decompressed.toByteSequence();
} catch (Exception e) {
throw new IOException(e);
}
}
/**
* java.util.zip.InflaterOutputStream#close()
*/
public void test_close() throws IOException {
InflaterOutputStream ios = new InflaterOutputStream(os);
ios.close();
// multiple close
ios.close();
}
/**
* java.util.zip.InflaterOutputStream#write(int)
*/
public void test_write_I() throws IOException {
int length = compressToBytes(testString);
// uncompress the data stored in the compressedBytes
try (InflaterOutputStream ios = new InflaterOutputStream(os)) {
for (int i = 0; i < length; i++) {
ios.write(compressedBytes[i]);
}
String result = new String(os.toByteArray());
assertEquals(testString, result);
}
}
/**
* java.util.zip.InflaterOutputStream#write(int)
*/
public void test_write_I_Illegal() throws IOException {
// write after close
InflaterOutputStream ios = new InflaterOutputStream(os);
ios.close();
try {
ios.write(-1);
fail("Should throw IOException");
} catch (IOException e) {
// expected
}
}
/**
* java.util.zip.InflaterOutputStream#write(byte[], int, int)
*/
public void test_write_$BII() throws IOException {
int length = compressToBytes(testString);
// uncompress the data stored in the compressedBytes
try (InflaterOutputStream ios = new InflaterOutputStream(os)) {
ios.write(compressedBytes, 0, length);
String result = new String(os.toByteArray());
assertEquals(testString, result);
}
}
@Override
public DecodingOutputStream decode(OutputStream outputStream) {
return new DecodingOutputStream(new InflaterOutputStream(outputStream));
}
public InflaterEndableWriteStream(BufferEndableWriteStream delegate) {
this.delegate = delegate;
this.bufferEndableWriteStreamOutputStream = new BufferEndableWriteStreamOutputStream(delegate);
this.inflaterOutputStream = new InflaterOutputStream(bufferEndableWriteStreamOutputStream);
}
/**
* 读取qq词库文件(qpyd),返回一个包含所以词的list
* @param inputPath : qpyd文件的路径
* @return: 包含词库文件中所有词的一个List<String>
* @throws Exception
*/
public static List<String> readQpydFile(String inputPath) throws Exception
{
List<String> wordList = new ArrayList<String>();
// read qpyd into byte array
ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
FileChannel fChannel = new RandomAccessFile(inputPath, "r").getChannel();
fChannel.transferTo(0, fChannel.size(), Channels.newChannel(dataOut));
fChannel.close();
// qpyd as bytes
ByteBuffer dataRawBytes = ByteBuffer.wrap(dataOut.toByteArray());
dataRawBytes.order(ByteOrder.LITTLE_ENDIAN);
// read info of compressed data
int startZippedDictAddr = dataRawBytes.getInt(0x38);
int zippedDictLength = dataRawBytes.limit() - startZippedDictAddr;
// read zipped qqyd dictionary into byte array
dataOut.reset();
Channels.newChannel(new InflaterOutputStream(dataOut)).write(
ByteBuffer.wrap(dataRawBytes.array(), startZippedDictAddr, zippedDictLength));
// uncompressed qqyd dictionary as bytes
ByteBuffer dataUnzippedBytes = ByteBuffer.wrap(dataOut.toByteArray());
dataUnzippedBytes.order(ByteOrder.LITTLE_ENDIAN);
// for debugging: save unzipped data to *.unzipped file
Channels.newChannel(new FileOutputStream(inputPath + ".unzipped")).write(dataUnzippedBytes);
// stores the start address of actual dictionary data
int unzippedDictStartAddr = -1;
int idx = 0;
byte[] byteArray = dataUnzippedBytes.array();
while (unzippedDictStartAddr == -1 || idx < unzippedDictStartAddr)
{
// read word
int pinyinStartAddr = dataUnzippedBytes.getInt(idx + 0x6);
int pinyinLength = dataUnzippedBytes.get(idx + 0x0) & 0xff;
int wordStartAddr = pinyinStartAddr + pinyinLength;
int wordLength = dataUnzippedBytes.get(idx + 0x1) & 0xff;
if (unzippedDictStartAddr == -1)
{
unzippedDictStartAddr = pinyinStartAddr;
}
String word = new String(Arrays.copyOfRange(byteArray, wordStartAddr, wordStartAddr + wordLength),
"UTF-16LE");
wordList.add(word);
// step up
idx += 0xa;
}
return wordList;
}