View Javadoc

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