samples/messagedigest/src-new-spi/org/apidesign/impl/security/spi/DigestorProvider.java
changeset 44 716af5f2ebd1
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/samples/messagedigest/src-new-spi/org/apidesign/impl/security/spi/DigestorProvider.java	Sat Jun 14 09:52:23 2008 +0200
     1.3 @@ -0,0 +1,61 @@
     1.4 +/*
     1.5 + * To change this template, choose Tools | Templates
     1.6 + * and open the template in the editor.
     1.7 + */
     1.8 +
     1.9 +package org.apidesign.impl.security.spi;
    1.10 +
    1.11 +import org.apidesign.impl.security.friendapi.DigestImplementation;
    1.12 +import org.apidesign.impl.security.friendapi.DigestProvider;
    1.13 +import java.nio.ByteBuffer;
    1.14 +import java.util.ServiceLoader;
    1.15 +import org.apidesign.spi.security.Digestor;
    1.16 +
    1.17 +/**
    1.18 + *
    1.19 + * @author Jaroslav Tulach
    1.20 + */
    1.21 +public class DigestorProvider implements DigestProvider {
    1.22 +
    1.23 +    public DigestImplementation create(String algorithm) {
    1.24 +        for (Digestor<?> d : ServiceLoader.load(Digestor.class)) {
    1.25 +            Handler<?> h = create(d, algorithm);
    1.26 +            if (h != null) {
    1.27 +                return h;
    1.28 +            }
    1.29 +        }
    1.30 +        return null;
    1.31 +    }
    1.32 +    
    1.33 +    private static <Data> Handler<Data> create(Digestor<Data> dig, String algorithm) {
    1.34 +        Data d = DigestorAccessor.getDefault().create(dig, algorithm);
    1.35 +        if (d == null) {
    1.36 +            return null;
    1.37 +        } else {
    1.38 +            return new Handler<Data>(algorithm, dig, d);
    1.39 +        }
    1.40 +    }
    1.41 +
    1.42 +    private static final class Handler<Data> extends DigestImplementation {
    1.43 +        private final Digestor dig;
    1.44 +        private final Data data;
    1.45 +
    1.46 +        public Handler(String algorithm, Digestor dig, Data data) {
    1.47 +            super(algorithm);
    1.48 +            this.dig = dig;
    1.49 +            this.data = data;
    1.50 +        }
    1.51 +        
    1.52 +        
    1.53 +        @Override
    1.54 +        public void update(ByteBuffer bb) {
    1.55 +            DigestorAccessor.getDefault().update(dig, data, bb);
    1.56 +        }
    1.57 +
    1.58 +        @Override
    1.59 +        public byte[] digest() {
    1.60 +            return DigestorAccessor.getDefault().digest(dig, data);
    1.61 +        }
    1.62 +        
    1.63 +    }
    1.64 +}