1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
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 | |
|
15 | |
|
16 | |
|
17 | 0 | public class TransformPerRequestInChunksPolicy extends AbstractTransformPolicy |
18 | |
{ |
19 | |
|
20 | |
private Semaphore writeSemaphore; |
21 | |
private long chunkSize; |
22 | |
private long bytesActuallyRequested; |
23 | |
|
24 | |
public TransformPerRequestInChunksPolicy(long chunkSize) |
25 | 0 | { |
26 | 0 | this.writeSemaphore = new Semaphore(1); |
27 | 0 | this.chunkSize = chunkSize; |
28 | 0 | this.bytesActuallyRequested = 0; |
29 | 0 | } |
30 | |
|
31 | |
|
32 | |
|
33 | |
|
34 | |
@Override |
35 | |
public void readRequest(long length) |
36 | |
{ |
37 | 0 | this.bytesActuallyRequested = this.bytesActuallyRequested + length; |
38 | 0 | super.readRequest(length); |
39 | 0 | this.writeSemaphore.release(); |
40 | 0 | } |
41 | |
|
42 | |
|
43 | |
|
44 | |
|
45 | |
@Override |
46 | |
public void release() |
47 | |
{ |
48 | 0 | this.writeSemaphore.release(); |
49 | 0 | super.release(); |
50 | 0 | } |
51 | |
|
52 | |
|
53 | |
|
54 | |
|
55 | |
@Override |
56 | |
protected Thread getCopyingThread() |
57 | |
{ |
58 | 0 | return new PerRequestWork(); |
59 | |
} |
60 | |
|
61 | 0 | private class PerRequestWork extends TransformerWork |
62 | |
{ |
63 | |
@Override |
64 | |
protected void execute() throws Exception |
65 | |
{ |
66 | 0 | getTransformer().initialize(getInputStream().getOut()); |
67 | |
|
68 | 0 | boolean finishWriting = false; |
69 | 0 | while (!finishWriting && !isClosed) |
70 | |
{ |
71 | 0 | writeSemaphore.acquire(); |
72 | |
|
73 | |
|
74 | |
|
75 | |
|
76 | |
|
77 | |
|
78 | 0 | long requested = bytesActuallyRequested; |
79 | 0 | long updatedRequest = (long) (Math.ceil((double)requested / (double)chunkSize) * chunkSize); |
80 | 0 | getBytesRequested().set(updatedRequest); |
81 | |
|
82 | 0 | finishWriting = getTransformer().write(getInputStream().getOut(), getBytesRequested()); |
83 | 0 | } |
84 | 0 | } |
85 | |
} |
86 | |
} |