หน้าเว็บ

วันศุกร์ที่ 18 กรกฎาคม พ.ศ. 2557

HessianSerializer : java


        Hessian เป็น library ที่เอาไว้ serialize ข้อมูลจากรูปแบบหนึ่งไปสู่อีกรูปแบบหนึ่ง  ตัวอย่างเช่น การ serialize ข้อมูลที่เป็น object ไปลง file หรือ deserialize จาก file ไปเป็น object อีกทั้งยังมีความสามารถในการ zip / unzip ข้อมูลที่ถูก serialize/deserialize อีกด้วย  สามารถอ่านเพิ่มเติมได้จาก http://www.caucho.com/resin-3.1/examples/hessian-serialize/index.xtp

ที่มาของการใช้ Hessian
        ช่วงนี้ผมต้องพัฒนา web offline ให้กับลูกค้า  โดยตัว offline หรือ client นั้ันเอาไว้แก้ปัญหาในกรณีที่ user ไม่มี internet ใช้ที่บ้าน หรืออินเตอร์เน็ตช้า คีย์ข้อมูลลำบาก เขาก็จะทำการ download (export) ข้อมูลจากระบบ online หรือตัว server เพื่อนำไป import และ คีย์ข้อมูลในระบบ offline  แทน
        ผมก็เลยใช้ hessian ในการ export ข้อมูลทีเป็น object ไปเป็น file แล้วให้ user นำ file นั้นไป import เข้าตัว client จากนั้นก็จะใช้ hessian ในการแปลงกลับจาก file ไปเป็น object ต่อไปครับ

        จากที่ใช้มาหลายงาน  ก็สะดวกดีน่ะครับ วันนี้ก็เลยเอา libraries เล็กๆ น้อยๆ ที่เขียนไว้มาแชร์ครับ :)
ซึ่งปรับแต่งเพิ่มเติมใหม่นิดหน่อย  เพื่อให้ใช้งานได้สะดวกขึ้น

maven dependencies (pom.xml)
<dependency>
   <groupId>com.caucho</groupId>
   <artifactId>hessian</artifactId>
   <version>4.0.38</version>
   <type>jar</type>
</dependency>

HessianSerializer.java
package com.blogspot.na5cent.library.util;

import com.caucho.hessian.io.Deflation;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author redcrow
 * link : http://na5cent.blogspot.com/2014/07/hessianserializer-java.html
 */
public class HessianSerializer {

    /**
     * @param obj
     * @param file
     * @throws IOException
     */
    public static void serialize2File(Object obj, File file) throws IOException {
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            serialize2OutputStream(obj, outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    /**
     * @param obj
     * @param outputStream
     * @throws IOException
     */
    public static void serialize2OutputStream(Object obj, OutputStream outputStream) throws IOException {
        Deflation envelope = new Deflation();
        Hessian2Output out = null;

        try {
            out = new Hessian2Output(outputStream);
            out = envelope.wrap(out);

            out.startMessage();
            out.writeObject(obj);
            out.completeMessage();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * @param obj
     * @return byte[]
     * @throws IOException
     */
    public static byte[] serialize2toBytes(Object obj) throws IOException {
        byte[] byts = {};
        ByteArrayOutputStream bos = null;

        try {
            bos = new ByteArrayOutputStream();
            serialize2OutputStream(obj, bos);
        } finally {
            if (bos != null) {
                byts = bos.toByteArray();
                bos.close();
            }
        }

        return byts;
    }

    /**
     * @param inputStream
     * @return Object
     * @throws IOException
     */
    public static Object deserializeFromInputStream(InputStream inputStream) throws IOException {
        Deflation envelope = new Deflation();
        Object value = null;
        Hessian2Input in = null;

        try {
            in = new Hessian2Input(inputStream);
            in = envelope.unwrap(in);

            in.startMessage();
            value = in.readObject();
            in.completeMessage();
        } finally {
            if (in != null) {
                in.close();
            }
        }

        return value;
    }

    /**
     * @param inputStream
     * @return Object
     * @throws IOException
     */
    public static Object deserializeFromInputStreamClose(InputStream inputStream) throws IOException {
        Object value = null;
        try {
            value = deserializeFromInputStream(inputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }

        return value;
    }

    /**
     * @param byts
     * @return Object
     * @throws IOException
     */
    public static Object deserializeFromBytes(byte[] byts) throws IOException {
        return deserializeFromInputStreamClose(new ByteArrayInputStream(byts));
    }

    /**
     * @param file
     * @return Object
     * @throws IOException
     */
    public static Object deserializeFromFile(File file) throws IOException {
        return deserializeFromInputStreamClose(new FileInputStream(file));
    }
}

ตัวอย่างการใช้งาน 1 (serialize)
...
...
...
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {IOException.class, FileNotFoundException.class})
public abstract class AbstractExportAuditService implements ExportAuditService {

    protected abstract RecordItemServiceFinder getServiceFinder();

    @Override
    public File export2FileByStaff(WSUserDetails staff) throws Exception {
        List items = getServiceFinder().findRecordItemsByStaff(staff);
        File file = ...
        HessianSerializer.serialize2File(items, file);

        return file;
    }
}
ตัวอย่างการใช้งาน 2 (deserialize)
...
...
...
public abstract class AbstractImportController<T, K> implements Serializable {

    @Autowired
    private StaffService staffService;
    @Autowired
    private AuditorService auditorService;
    @Autowired
    private ConfigService configService;

    protected abstract void handleDataItems(List<T> recordItems, List<K> configItems);

    private void handleFileUpload(UploadedFile file) throws Exception {
        Offline2Out<T, K> out = (Offline2Out<T, K>) HessianSerializer
                .deserializeFromInputStreamClose(file.getInputstream());

        handleOutput(out);
    }

    ....
    ....
    ....
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น