001package org.apache.turbine.util; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, 015 * software distributed under the License is distributed on an 016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 017 * KIND, either express or implied. See the License for the 018 * specific language governing permissions and limitations 019 * under the License. 020 */ 021 022import java.io.ByteArrayInputStream; 023import java.io.ByteArrayOutputStream; 024import java.io.ObjectInputStream; 025import java.io.ObjectOutputStream; 026import java.io.Serializable; 027import java.util.Map; 028 029/** 030 * This is where common Object manipulation routines should go. 031 * 032 * @author <a href="mailto:nissim@nksystems.com">Nissim Karpenstein</a> 033 * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a> 034 * @version $Id$ 035 */ 036public abstract class ObjectUtils 037{ 038 /** 039 * Converts a map to a byte array for storage/serialization. 040 * 041 * @param map The Map to convert. 042 * 043 * @return A byte[] with the converted Map. 044 * 045 * @throws Exception A generic exception. 046 */ 047 public static byte[] serializeMap(Map<String, Object> map) 048 throws Exception 049 { 050 byte[] byteArray = null; 051 052 for (Object value : map.values()) 053 { 054 if (! (value instanceof Serializable)) 055 { 056 throw new Exception("Could not serialize, value is not serializable:" + value); 057 } 058 } 059 060 try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); 061 ObjectOutputStream out = new ObjectOutputStream(baos)) 062 { 063 out.writeObject(map); 064 out.flush(); 065 066 byteArray = baos.toByteArray(); 067 } 068 069 return byteArray; 070 } 071 072 /** 073 * Deserializes a single object from an array of bytes. 074 * 075 * @param <T> type of the object to return 076 * @param objectData The serialized object. 077 * 078 * @return The deserialized object, or <code>null</code> on failure. 079 */ 080 @SuppressWarnings("unchecked") 081 public static <T> T deserialize(byte[] objectData) 082 { 083 T object = null; 084 085 if (objectData != null) 086 { 087 try (ByteArrayInputStream bin = new ByteArrayInputStream(objectData); 088 ObjectInputStream in = new ObjectInputStream(bin)) 089 { 090 // If objectData has not been initialized, an 091 // exception will occur. 092 object = (T)in.readObject(); 093 } 094 catch (Exception e) 095 { 096 // ignore 097 } 098 } 099 100 return object; 101 } 102}