import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.InputStream;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.io.ByteArrayInputStream;
import org.apache.xerces.parsers.DOMParser;


public class EncryptedKeyTokenWithCrossReference extends EncryptedKeyToken
{

   public EncryptedKeyTokenWithCrossReference (
                                         String keyStoreFileName,
                                         String keyStorePassword,
                                         String keyName,
                                         String wsuKeyID,
                                         WSSMessage wssMessage
                                      )
   {
      super ( keyStoreFileName, keyStorePassword, keyName, wsuKeyID, wssMessage );
   }


   public String getType()
   {
      return "EncryptedKeyTokenWithCrossReference";
   }


   public Element encrypt (
                   String wsuEncryptedElementID,
                   String encryptionAlgo,
                   Element elementWantToEncrypt
                 ) {
      Element encryptedDataEl = super.encrypt(
         wsuEncryptedElementID,
         encryptionAlgo,
         elementWantToEncrypt );

      String securityTokenReference =
            "\n\n"+
            "\n\n"+
            "\t\n"+
            "\n"+
            "";

      Document plainText = encryptedDataEl.getOwnerDocument();
      Document sourceDocRef = loadDocument ( securityTokenReference );
      Element keyInfo = (Element)sourceDocRef.
           getElementsByTagName("KeyInfo").item(0).cloneNode(true);
      Node encDataLastElement = encryptedDataEl.getLastChild();
      encryptedDataEl.insertBefore ((Element) plainText.importNode(keyInfo, true),                                     encDataLastElement );
      return encryptedDataEl;
   }//encrypt()


   private Document loadDocument ( String XMLString ) {
      DOMParser dp = new DOMParser();
      InputStream byteData = null;
      byteData = new ByteArrayInputStream (
                              XMLString.getBytes()
                          );
      try
      {
           dp.parse ( new InputSource ( byteData ) );
      }
      catch ( Exception e )
      {
           System.out.println ( "The XMLString is not loaded." );
           e.printStackTrace();
      }
      return dp.getDocument();
   }//loadDocument()


}//EncryptedKeyTokenWithCrossReference