View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.pgp;
8   
9   import java.io.PipedOutputStream;
10  
11  import edu.emory.mathcs.backport.java.util.concurrent.Semaphore;
12  
13  /**
14   * A {@link TransformPolicy} that copies only the requested transformed bytes 
15   * into the {@link PipedOutputStream}.
16   */
17  public class TransformPerRequestPolicy extends AbstractTransformPolicy
18  {
19  
20      private Semaphore writeSemaphore;
21      
22      public TransformPerRequestPolicy()
23      {
24          this.writeSemaphore = new Semaphore(1);
25      }
26  
27      /**
28       * {@inheritDoc}
29       */
30      @Override
31      public void readRequest(long length)
32      {
33          super.readRequest(length);
34          this.writeSemaphore.release();
35      }
36      
37      
38      /**
39       * {@inheritDoc}
40       */
41      @Override
42      public void release()
43      {
44          this.writeSemaphore.release();
45          super.release();
46      }
47  
48      /**
49       * {@inheritDoc}
50       */
51      @Override
52      protected Thread getCopyingThread()
53      {
54          return new PerRequestWork();
55      }
56  
57      private class PerRequestWork extends TransformerWork
58      {
59          @Override
60          protected void execute() throws Exception
61          {
62              getTransformer().initialize(getInputStream().getOut());
63              
64              boolean finishWriting = false;
65              while (!finishWriting && !isClosed)
66              {
67                  writeSemaphore.acquire();
68                  finishWriting = getTransformer().write(getInputStream().getOut(), getBytesRequested());
69              }
70          }
71      }
72  }
73  
74