View Javadoc
1   package com.srv4pos.server.api.infrastructure;
2   
3   import com.srv4pos.server.api.infrastructure.http.HttpHelper;
4   
5   import java.io.IOException;
6   import java.io.OutputStream;
7   import java.io.OutputStreamWriter;
8   import java.nio.charset.Charset;
9   import java.util.List;
10  
11  /**
12   * Implementation of {@link ConnectionWriter} which write data from {@link String}.
13   * <p>User: Kirill, Date: 23.08.13 14:51</p>
14   */
15  public class StringConnectionWriter implements ConnectionWriter {
16      private String body;
17  
18      public StringConnectionWriter(String body) {
19          this.body = body;
20      }
21  
22      public StringConnectionWriter(List<String> body) {
23          this.body = flatString(body);
24      }
25  
26      private String flatString(List<String> lines) {
27          final String delimiter = "\n";
28          final StringBuilder builder = new StringBuilder();
29          for (String line : lines) {
30              if (builder.length() != 0) {
31                  builder.append(delimiter);
32              }
33              builder.append(line);
34          }
35          return builder.toString();
36      }
37  
38      public void write(OutputStream outputStream) throws IOException {
39          OutputStreamWriter output = new OutputStreamWriter(outputStream, HttpHelper.ENCODING_FOR_BODY);
40          output.write(body);
41          output.close();
42      }
43  
44      public Integer getContentLength() {
45          return body.getBytes(Charset.forName("UTF-8")).length;
46      }
47  }