5e2403401b9c6f1f8f87b0f4df288fc775ca823f
[maven-thymeleaf-skin] / src / main / java / de / juplo / thymeproxy / ProxyResourceResolver.java
1 package de.juplo.thymeproxy;
2
3
4 import java.io.IOException;
5 import java.io.InputStream;
6 import org.apache.http.HttpEntity;
7 import org.apache.http.client.methods.CloseableHttpResponse;
8 import org.apache.http.util.EntityUtils;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11 import org.thymeleaf.TemplateProcessingParameters;
12 import org.thymeleaf.resourceresolver.IResourceResolver;
13
14
15
16 /**
17  *
18  * @author kai
19  */
20 public class ProxyResourceResolver implements IResourceResolver
21 {
22   private final static Logger LOG =
23       LoggerFactory.getLogger(ProxyResourceResolver.class);
24
25
26   private final String resource;
27
28   private final CloseableHttpResponse response;
29   private final HttpEntity entity;
30
31
32   public ProxyResourceResolver(
33       String resource,
34       CloseableHttpResponse response,
35       HttpEntity entity
36       )
37   {
38     this.resource = resource;
39     this.response = response;
40     this.entity = entity;
41   }
42
43
44   @Override
45   public String getName()
46   {
47     return resource;
48   }
49
50   @Override
51   public InputStream getResourceAsStream(TemplateProcessingParameters templateProcessingParameters, String resourceName)
52   {
53     InputStream is;
54     try
55     {
56       is = entity.getContent();
57     }
58     catch (IOException e)
59     {
60       LOG.error("unexpected error while retriving the response-body", e);
61       return null;
62     }
63
64     return new InputStream()
65     {
66       @Override
67       public boolean markSupported()
68       {
69         return is.markSupported();
70       }
71
72       @Override
73       public synchronized void reset() throws IOException
74       {
75         is.reset();
76       }
77
78       @Override
79       public synchronized void mark(int readlimit)
80       {
81         is.mark(readlimit);
82       }
83
84       @Override
85       public void close() throws IOException
86       {
87         is.close();
88         EntityUtils.consume(entity);
89         response.close();
90       }
91
92       @Override
93       public int available() throws IOException
94       {
95         return is.available();
96       }
97
98       @Override
99       public long skip(long n) throws IOException
100       {
101         return is.skip(n);
102       }
103
104       @Override
105       public int read() throws IOException
106       {
107         return is.read();
108       }
109
110       @Override
111       public int read(byte[] b, int off, int len) throws IOException
112       {
113         return is.read(b, off, len);
114       }
115
116       @Override
117       public int read(byte[] b) throws IOException
118       {
119         return is.read(b);
120       }
121     };
122   }
123 }