[LIB-9] Add ability to archive qrcode content
[chesshog.git] / chesshog-qrcode / src / main / java / org / hedgecode / chess / qrcode / zip / ZipContentInflater.java
1 /*
2  * Copyright (c) 2018-2019. Developed by Hedgecode.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.chess.qrcode.zip;
18
19 import java.io.ByteArrayInputStream;
20 import java.io.IOException;
21 import java.util.zip.InflaterInputStream;
22
23 import org.hedgecode.chess.qrcode.ChessQRCodeConstants;
24 import org.hedgecode.chess.qrcode.ChessQRCodeException;
25
26 /**
27  *
28  *
29  * @author Dmitry Samoshin aka gotty
30  */
31 public class ZipContentInflater {
32
33     public static String inflate(String zipContents) throws ChessQRCodeException {
34         byte[] zipBytes = ZipContentUtils.base64Decode(zipContents);
35         int length = ZipContentUtils.getZipLength(zipBytes);
36         if (length > ZipContentUtils.getMaxContentLength()) {
37             throw new ChessQRCodeException(
38                     ChessQRCodeException.Type.PARSE, "zip.max.length.error"
39             );
40         }
41         byte[] resultBytes = new byte[length];
42         InflaterInputStream zin = new InflaterInputStream(
43                 new ByteArrayInputStream(
44                         ZipContentUtils.getZipBytes(zipBytes)
45                 )
46         );
47         try {
48             try {
49                 length = zin.read(resultBytes, 0, length); // todo : check length
50             } finally {
51                 zin.close();
52             }
53         } catch (IOException e) {
54             throw new ChessQRCodeException(
55                     ChessQRCodeException.Type.PARSE, "zip.inflate.read.error", e.getMessage()
56             );
57         }
58         return new String(
59                 resultBytes, 0, length, ChessQRCodeConstants.CHARSET
60         );
61     }
62
63 }