Java tutorial
/* * Copyright (C) 2011 Dario Scoppelletti, <http://www.scoppelletti.it/>. * * 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 it.scoppelletti.programmerpower.web.view; import java.io.*; import java.util.*; import com.opensymphony.xwork2.conversion.*; import org.apache.commons.codec.binary.*; import org.apache.struts2.util.*; import it.scoppelletti.programmerpower.*; import it.scoppelletti.programmerpower.io.*; import it.scoppelletti.programmerpower.types.*; /** * Convertitore degli oggetti serializzabili. * * @since 1.0.0 */ public final class SerializableConverter extends StrutsTypeConverter { /** * Costruttore. */ public SerializableConverter() { } /** * Converte una stringa in oggetto. * * @param context Contesto. * @param values Vettore di stringhe da convertire. È considerato * il solo primo elemento. * @param toClass Tipo nel quale convertire il vettore di stringhe. * @return Oggetto risultante. */ @Override @SuppressWarnings("rawtypes") public Object convertFromString(Map context, String[] values, Class toClass) { Object obj; String s; byte[] data; InputStream buf = null; ObjectInputStream in = null; if (values == null || values.length == 0) { return null; } s = values[0]; if (Strings.isNullOrEmpty(s)) { return null; } data = Base64.decodeBase64(s); try { buf = new ByteArrayInputStream(data); in = new ObjectInputStream(buf); buf = null; obj = in.readObject(); } catch (Exception ex) { throw new TypeConversionException(ApplicationException.toString(ex), ex); } finally { if (buf != null) { IOUtils.close(buf); buf = null; } if (in != null) { IOUtils.close(in); in = null; } } return obj; } /** * Converte un oggetto in stringa. * * @param context Contesto. * @param obj Oggetto. * @return Stringa risultante. */ @Override @SuppressWarnings("rawtypes") public String convertToString(Map context, Object obj) { ByteArrayOutputStream buf = null; ObjectOutputStream out = null; Base64 encoder; try { buf = new ByteArrayOutputStream(); out = new ObjectOutputStream(buf); out.writeObject(obj); } catch (IOException ex) { throw new TypeConversionException(ApplicationException.toString(ex), ex); } finally { if (out != null) { IOUtils.close(out); out = null; } if (buf != null) { IOUtils.close(buf); } } encoder = new Base64(0); return encoder.encodeToString(buf.toByteArray()); } }