Java tutorial
/* * Copyright 2016 Mobicage NV * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobicage.rogerthat.mfr.dal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import com.mobicage.rogerthat.mfr.ApiServlet; public class Streamable { static final Logger log = Logger.getLogger(ApiServlet.class.getName()); protected static Object fromBase64(String base64String) { try { ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(base64String)); try { ZipInputStream zip = new ZipInputStream(bis); try { zip.getNextEntry(); ObjectInput in = new ObjectInputStream(zip); try { return in.readObject(); } finally { in.close(); } } finally { zip.close(); } } finally { bis.close(); } } catch (ClassNotFoundException e) { log.log((Level.SEVERE), "ClassNotFoundException while deserializing member", e); return null; } catch (IOException e) { log.log((Level.SEVERE), "IOException while deserializing member", e); return null; } } public String toBase64() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ZipOutputStream zip = new ZipOutputStream(bos); try { zip.setLevel(9); zip.putNextEntry(new ZipEntry("entry")); try { ObjectOutput out = new ObjectOutputStream(zip); try { out.writeObject(this); } finally { out.flush(); } } finally { zip.closeEntry(); } zip.flush(); return Base64.encodeBase64URLSafeString(bos.toByteArray()); } finally { zip.close(); } } finally { bos.close(); } } catch (IOException e) { log.log((Level.SEVERE), "IO Error while serializing member", e); return null; } } public Streamable() { super(); } }