samples/messagedigest/src-new-spi/org/apidesign/impl/security/spi/DigestorProvider.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:52:23 +0200
changeset 44 716af5f2ebd1
permissions -rw-r--r--
Switching to freeform project
     1 /*
     2  * To change this template, choose Tools | Templates
     3  * and open the template in the editor.
     4  */
     5 
     6 package org.apidesign.impl.security.spi;
     7 
     8 import org.apidesign.impl.security.friendapi.DigestImplementation;
     9 import org.apidesign.impl.security.friendapi.DigestProvider;
    10 import java.nio.ByteBuffer;
    11 import java.util.ServiceLoader;
    12 import org.apidesign.spi.security.Digestor;
    13 
    14 /**
    15  *
    16  * @author Jaroslav Tulach
    17  */
    18 public class DigestorProvider implements DigestProvider {
    19 
    20     public DigestImplementation create(String algorithm) {
    21         for (Digestor<?> d : ServiceLoader.load(Digestor.class)) {
    22             Handler<?> h = create(d, algorithm);
    23             if (h != null) {
    24                 return h;
    25             }
    26         }
    27         return null;
    28     }
    29     
    30     private static <Data> Handler<Data> create(Digestor<Data> dig, String algorithm) {
    31         Data d = DigestorAccessor.getDefault().create(dig, algorithm);
    32         if (d == null) {
    33             return null;
    34         } else {
    35             return new Handler<Data>(algorithm, dig, d);
    36         }
    37     }
    38 
    39     private static final class Handler<Data> extends DigestImplementation {
    40         private final Digestor dig;
    41         private final Data data;
    42 
    43         public Handler(String algorithm, Digestor dig, Data data) {
    44             super(algorithm);
    45             this.dig = dig;
    46             this.data = data;
    47         }
    48         
    49         
    50         @Override
    51         public void update(ByteBuffer bb) {
    52             DigestorAccessor.getDefault().update(dig, data, bb);
    53         }
    54 
    55         @Override
    56         public byte[] digest() {
    57             return DigestorAccessor.getDefault().digest(dig, data);
    58         }
    59         
    60     }
    61 }