1 10 package org.mmbase.util.transformers; 11 12 import org.mmbase.util.functions.*; 13 import java.util.zip.Checksum ; 14 import java.io.*; 15 16 import org.mmbase.util.logging.Logger; 17 import org.mmbase.util.logging.Logging; 18 19 27 28 public class ChecksumFactory implements ParameterizedTransformerFactory { 29 private static final Logger log = Logging.getLoggerInstance(ChecksumFactory.class); 30 31 public static final Parameter[] PARAMS = new Parameter[] { 32 new Parameter("implementation", String .class, java.util.zip.Adler32 .class.getName()) 33 }; 34 35 public Parameters createParameters() { 36 return new Parameters(PARAMS); 37 } 38 39 42 public Transformer createTransformer(Parameters parameters) { 43 String impl = (String ) parameters.get("implementation"); 44 try { 45 Class clazz = Class.forName(impl); 46 if (Checksum .class.isAssignableFrom(clazz)) { 47 Checksum checksum = (Checksum ) clazz.newInstance(); 48 return new ChecksumTransformer(checksum); 49 } 50 if (impl.equalsIgnoreCase("md5")) { 51 return new MD5(); 52 } 53 } catch (Exception e) { 54 log.error(e); 55 } 56 return Transformers.getCharTransformer(impl, "", "ChecksumFactory", false); 57 58 59 } 60 61 62 protected class ChecksumTransformer extends ByteArrayToCharTransformer implements ByteToCharTransformer { 63 private static final long serialVersionUID = 1L; 64 private Checksum checksum; 65 ChecksumTransformer(Checksum c) { 66 checksum = c; 67 } 68 public String transform(byte[] bytes) { 69 if (bytes == null) return null; 70 synchronized(checksum) { 71 checksum.reset(); 72 checksum.update(bytes, 0, bytes.length); 73 return "" + checksum.getValue(); 74 } 75 } 76 77 public String toString() { 78 return "checksum(" + checksum + ")"; 79 } 80 81 private void writeObject(ObjectOutputStream out) throws IOException { 83 if (checksum instanceof Serializable) { 84 out.writeObject(checksum); 85 } else { 86 out.writeObject(checksum.getClass()); 87 } 88 } 89 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 91 Object cs = in.readObject(); 92 if (cs instanceof Class ) { 93 try { 94 checksum = (Checksum ) ((Class ) cs).newInstance(); 95 } catch (InstantiationException e) { 96 throw new IOException(e.getMessage()); 97 } catch (IllegalAccessException e) { 98 throw new IOException(e.getMessage()); 99 } 100 } else { 101 checksum = (Checksum ) cs; 102 } 103 } 104 105 } 106 107 } 108 | Popular Tags |