//   C1 PC/IB; C2 PC/OB; C1 AC; EE
  @Test
  public void testB_C1_PC_IB__C2_PC_OB__C1_AC__EE() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;
    InputStream stream1, stream2;
    String text;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);

    stream1 = replay.getContent();
    text = blockRead(stream1, UTF8, 3, 2);
    assertThat(text, is("012"));

    stream2 = replay.getContent();
    text = blockRead(stream2, UTF8, 6, 4);
    assertThat(text, is("012345"));

    try {
      blockRead(stream1, UTF8, 6, 4);
      fail("Expected IOException");
    } catch (IOException e) {
      // Expected.
    }
  }
  public HttpPost createPostMethod(String url, Object postData) {
    try {
      byte[] rawData;

      if (postData instanceof byte[]) {
        rawData = (byte[]) postData;
      } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(postData);
        oos.close();
        rawData = baos.toByteArray();
      }

      InputStream is = new ByteArrayInputStream(rawData);

      HttpPost httpPost = new HttpPost(url);
      BasicHttpEntity entity = new BasicHttpEntity();
      entity.setContentType("application/octet-stream");
      entity.setContentLength(rawData.length);
      entity.setContent(is);
      httpPost.setEntity(entity);

      RequestConfig requestConfig =
          RequestConfig.copy(HAZELCAST_REQUEST_CONFIG)
              .setSocketTimeout(TIMEOUT)
              .setConnectTimeout(TIMEOUT)
              .setConnectionRequestTimeout(TIMEOUT)
              .build();
      httpPost.setConfig(requestConfig);
      return httpPost;
    } catch (IOException e) {
      throw new RuntimeException("Error POST-ing data", e);
    }
  }
  private static HttpEntity entityFromOkHttpResponse(Response response) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = response.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(response.header("Content-Encoding"));

    if (body.contentType() != null) {
      entity.setContentType(body.contentType().type());
    }
    return entity;
  }
Exemplo n.º 4
0
    @Override
    protected String doInBackground(String... params) {
      Context context = getApplicationContext();
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

      String serviceUrlString = prefs.getString("connection.url", null);
      if (serviceUrlString != null) {
        if (!serviceUrlString.endsWith("/")) serviceUrlString += "/";

        Command command = new Command();
        command.actionName = params[0];

        Gson gson = new Gson();
        String commandContent = gson.toJson(command);

        HttpPost executePost = new HttpPost(serviceUrlString + "action/execute");
        BasicHttpEntity httpEntity = new BasicHttpEntity();
        httpEntity.setContentType("application/json");
        try {
          httpEntity.setContent(new ByteArrayInputStream(commandContent.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
          throw new RuntimeException(e);
        }

        executePost.setEntity(httpEntity);
        HttpClient client = new DefaultHttpClient();

        try {
          HttpResponse executeResult = client.execute(executePost);
          if (executeResult.getStatusLine().getStatusCode() == HTTP_STATUS_OK) {
            InputStream content = executeResult.getEntity().getContent();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(content));
            StringBuilder contentBuilder = new StringBuilder();

            String line;
            while ((line = rd.readLine()) != null) {
              contentBuilder.append(line).append("\n");
            }

            Result result = gson.fromJson(contentBuilder.toString(), Result.class);
            return result.message;
          }
        } catch (IOException e) {
          return null;
        }
      }
      return null;
    }
Exemplo n.º 5
0
 /**
  * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
  *
  * @param connection
  * @return an HttpEntity populated with data from <code>connection</code>.
  */
 private static HttpEntity entityFromConnection(HttpURLConnection connection) {
   BasicHttpEntity entity = new BasicHttpEntity();
   InputStream inputStream;
   try {
     inputStream = connection.getInputStream();
   } catch (IOException ioe) {
     inputStream = connection.getErrorStream();
   }
   entity.setContent(inputStream);
   entity.setContentLength(connection.getContentLength());
   entity.setContentEncoding(connection.getContentEncoding());
   entity.setContentType(connection.getContentType());
   return entity;
 }
Exemplo n.º 6
0
 private static HttpEntity a(HttpURLConnection httpurlconnection) {
   BasicHttpEntity basichttpentity = new BasicHttpEntity();
   java.io.InputStream inputstream;
   try {
     inputstream = httpurlconnection.getInputStream();
   } catch (IOException ioexception) {
     ioexception = httpurlconnection.getErrorStream();
   }
   basichttpentity.setContent(inputstream);
   basichttpentity.setContentLength(httpurlconnection.getContentLength());
   basichttpentity.setContentEncoding(httpurlconnection.getContentEncoding());
   basichttpentity.setContentType(httpurlconnection.getContentType());
   return basichttpentity;
 }
  @Test
  public void testS__C1_FC_OB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);

    String output;

    output = byteRead(replay.getContent(), -1);
    assertThat(output, is(data));
  }
  @Test
  public void testWriteTo() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    replay.writeTo(buffer);
    String output = new String(buffer.toByteArray(), UTF8);
    assertThat(output, is(input));
  }
  //   C1 PC/IB.
  @Test
  public void testB_C1_PC_IB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;
    InputStream stream;
    String text;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 20);

    stream = replay.getContent();
    text = blockRead(stream, UTF8, 3, 3);
    assertThat(text, is("012"));
  }
Exemplo n.º 10
0
    @Override
    public void run() {
      super.run();
      try {
        ParcelFileDescriptor[] descriptors = ParcelFileDescriptor.createPipe();
        parcelRead = new ParcelFileDescriptor(descriptors[0]);
        parcelWrite = new ParcelFileDescriptor(descriptors[1]);

        mediaRecorder.setOutputFile(parcelWrite.getFileDescriptor());

        cameraSurface.getHolder().addCallback(CameraActivity.this);

        is = new ParcelFileDescriptor.AutoCloseInputStream(parcelRead);

        // This will skip the MPEG4 header if this step fails we can't stream anything :(

        byte[] mpegHeader = {'m', 'd', 'a', 't'};
        byte[] headerBuffer = new byte[mpegHeader.length];
        try {
          byte mpegHeaderBuffer[] = new byte[4];
          // Skip all atoms preceding mdat atom
          do {
            is.read(headerBuffer);
          } while (!Arrays.equals(mpegHeader, headerBuffer));
        } catch (IOException e) {
          Log.e("ERROR", "Couldn't skip mp4 header :/");
          throw e;
        }

        Log.d("SPRINKLER", "MPEG HEADER SKIPPED");

        HttpPost post =
            new HttpPost("http://" + SERVER_ADDRESS + ":" + SERVER_PORT + "/emit?channel=prueba");
        BasicHttpEntity httpEntity = new BasicHttpEntity();
        httpEntity.setChunked(true);
        httpEntity.setContentLength(-1);
        httpEntity.setContent(is);

        post.setEntity(httpEntity);

        HttpClient client = new DefaultHttpClient();
        client.execute(post);

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  @Test
  public void testGetContentLength() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentLength(), is(-1L));

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    basic.setContentLength(input.length());
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentLength(), is(10L));
  }
  @Test
  public void testIsRepeatable() throws Exception {
    String text = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(text.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic);
    assertThat(replay.isRepeatable(), is(true));

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(text.getBytes(UTF8)));
    BufferedHttpEntity buffered = new BufferedHttpEntity(basic);
    replay = new PartiallyRepeatableHttpEntity(buffered);
    assertThat(replay.isRepeatable(), is(true));
  }
  @Test
  public void testGetContentType() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentType(), nullValue());

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    basic.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentType().getValue(), is("application/json"));
  }
  @Test
  public void testGetContentEncoding() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentEncoding(), nullValue());

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    basic.setContentEncoding("UTF-8");
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentEncoding().getValue(), is("UTF-8"));
  }
  @Test
  public void testIsChunked() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.isChunked(), is(false));

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    basic.setChunked(true);
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.isChunked(), is(true));
  }
  @Test
  public void testConsumeContent() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);

    try {
      replay.consumeContent();
      fail("Expected UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
      // Expected.
    }
  }
Exemplo n.º 17
0
  /**
   * 执行HTTP请求之后获取到的数据流.
   *
   * @param connection
   * @return
   */
  private HttpEntity entityFromURLConnwction(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
      inputStream = connection.getInputStream();
    } catch (IOException e) {
      e.printStackTrace();
      inputStream = connection.getErrorStream();
    }

    // TODO : GZIP
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());

    return entity;
  }
  //   C1 FC/IB; C1 XC; C2 FC.
  @Test
  public void testS_C1_FC_IB__C1_XC__C2_FC() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;
    InputStream stream;
    String text;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 20);
    stream = replay.getContent();
    text = byteRead(stream, -1);
    assertThat(text, is("0123456789"));
    stream.close();

    stream = replay.getContent();
    text = byteRead(stream, -1);
    assertThat(text, is("0123456789"));
  }
  @Test
  public void testB_C1_FC_OB__C2_AC__EE() throws Exception {
    String data = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);

    String output;

    output = blockRead(replay.getContent(), UTF8, -1, 3);
    assertThat(output, is(data));

    try {
      replay.getContent();
      fail("Expected IOException");
    } catch (IOException e) {
      // Expected.
    }
  }
  @Test
  public void testIsStreaming() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    InputStreamEntity streaming;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.isStreaming(), is(true));

    basic = new BasicHttpEntity();
    basic.setContent(null);
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.isStreaming(), is(false));

    streaming =
        new InputStreamEntity(
            new ByteArrayInputStream(input.getBytes(UTF8)), 10, ContentType.TEXT_PLAIN);
    replay = new PartiallyRepeatableHttpEntity(streaming, 5);
    assertThat(replay.isStreaming(), is(true));
  }
Exemplo n.º 21
0
 public HttpResponse put(
     String cType,
     String accountSid,
     String authToken,
     String timestamp,
     String url,
     DefaultHttpClient httpclient,
     EncryptUtil encryptUtil,
     String body)
     throws Exception {
   HttpPut httpPut = new HttpPut(url);
   httpPut.setHeader("Accept", cType);
   httpPut.setHeader("Content-Type", cType + ";charset=utf-8");
   String src = accountSid + ":" + timestamp;
   String auth = encryptUtil.base64Encoder(src);
   httpPut.setHeader("Authorization", auth);
   logger.info(body);
   BasicHttpEntity requestBody = new BasicHttpEntity();
   requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
   requestBody.setContentLength(body.getBytes("UTF-8").length);
   httpPut.setEntity(requestBody);
   HttpResponse response = httpclient.execute(httpPut);
   return response;
 }
  //   C1 PC/OB; C1 XC; C2 AC; EE
  @Test
  public void testS_C1_PC_OB__C1_XC__C2_AC__EE() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;
    InputStream stream;
    String text;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);

    stream = replay.getContent();
    text = byteRead(stream, 7);
    assertThat(text, is("0123456"));
    stream.close();

    try {
      replay.getContent();
      fail("Expected IOException");
    } catch (IOException e) {
      // Expected.
    }
  }
Exemplo n.º 23
0
 /**
  * Write the stream to a temporary storage and calculate the content length
  *
  * @param entity HTTPEntity
  * @param messageFormatter message formatter
  * @param msgContext current message context
  * @param format message format
  * @throws IOException if an exception occurred while writing data
  */
 private void setStreamAsTempData(
     BasicHttpEntity entity,
     MessageFormatter messageFormatter,
     MessageContext msgContext,
     OMOutputFormat format)
     throws IOException {
   TemporaryData serialized = new TemporaryData(256, 4096, "http-nio_", ".dat");
   OutputStream out = serialized.getOutputStream();
   try {
     messageFormatter.writeTo(msgContext, format, out, true);
   } finally {
     out.close();
   }
   msgContext.setProperty(NhttpConstants.SERIALIZED_BYTES, serialized);
   entity.setContentLength(serialized.getLength());
 }
Exemplo n.º 24
0
  // FIXME: rather than isError, we might was to pass in the status code to give more flexibility
  private void writeResponse(
      HttpResponse resp,
      final String responseText,
      final int statusCode,
      String responseType,
      String reasonPhrase) {
    try {
      resp.setStatusCode(statusCode);
      resp.setReasonPhrase(reasonPhrase);

      BasicHttpEntity body = new BasicHttpEntity();
      if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
        // JSON response
        body.setContentType(jsonContentType);
        if (responseText == null) {
          body.setContent(
              new ByteArrayInputStream(
                  "{ \"error\" : { \"description\" : \"Internal Server Error\" } }"
                      .getBytes("UTF-8")));
        }
      } else {
        body.setContentType("text/xml");
        if (responseText == null) {
          body.setContent(
              new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes("UTF-8")));
        }
      }

      if (responseText != null) {
        body.setContent(new ByteArrayInputStream(responseText.getBytes("UTF-8")));
      }
      resp.setEntity(body);
    } catch (Exception ex) {
      s_logger.error("error!", ex);
    }
  }
Exemplo n.º 25
0
  /**
   * Send the passed in response message, asynchronously
   *
   * @param msgContext the message context to be sent
   * @throws AxisFault on error
   */
  private void sendAsyncResponse(MessageContext msgContext) throws AxisFault {

    int contentLength = extractContentLength(msgContext);

    // remove unwanted HTTP headers (if any from the current message)
    removeUnwantedHeaders(msgContext);
    Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    ServerWorker worker = (ServerWorker) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO);
    HttpResponse response = worker.getResponse();

    OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext);
    MessageFormatter messageFormatter =
        MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext);
    Boolean noEntityBody = (Boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY);
    if (noEntityBody == null || Boolean.FALSE == noEntityBody) {
      response.setHeader(
          HTTP.CONTENT_TYPE,
          messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
    } else if (Boolean.TRUE == noEntityBody) {
      ((BasicHttpEntity) response.getEntity()).setChunked(false);
      ((BasicHttpEntity) response.getEntity()).setContentLength(0);

      // Since HTTP HEAD request doesn't contain message body content length of the is set to be 0.
      // To handle
      // content length 0 while serving head method, content length of the backend response is set
      // as the content
      // as synapse cannot calculate content length without providing message body.
      if (transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD) != null
          && NhttpConstants.HTTP_HEAD.equals(
              transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD))
          && transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN) != null) {

        ((BasicHttpEntity) response.getEntity())
            .setContentLength(
                Long.parseLong(
                    String.valueOf(transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN))));
        transportHeaders.remove(NhttpConstants.ORIGINAL_CONTENT_LEN);
        transportHeaders.remove(NhttpConstants.HTTP_REQUEST_METHOD);
      }
    }
    response.setStatusCode(determineHttpStatusCode(msgContext, response));

    // Override the Standard Reason Phrase
    if (msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE) != null
        && !msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).equals("")) {
      response.setReasonPhrase(
          msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).toString());
    }

    // set any transport headers
    if (transportHeaders != null && !transportHeaders.values().isEmpty()) {
      Iterator iter = transportHeaders.keySet().iterator();
      while (iter.hasNext()) {
        Object header = iter.next();
        Object value = transportHeaders.get(header);
        if (value != null && header instanceof String && value instanceof String) {
          response.addHeader((String) header, (String) value);

          String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

          Map map = (Map) msgContext.getProperty(excessProp);
          if (map != null && map.get(header) != null) {
            log.debug(
                "Number of excess values for "
                    + header
                    + " header is : "
                    + ((Collection) (map.get(header))).size());

            for (Iterator iterator = map.keySet().iterator(); iterator.hasNext(); ) {
              String key = (String) iterator.next();

              for (String excessVal : (Collection<String>) map.get(key)) {
                if (header.equals(key)) {
                  response.addHeader((String) header, (String) excessVal);
                }
              }
            }
          }
        }
      }
    }

    boolean forceContentLength =
        msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
    boolean forceContentLengthCopy =
        msgContext.isPropertyTrue(NhttpConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);

    BasicHttpEntity entity = (BasicHttpEntity) response.getEntity();

    MetricsCollector lstMetrics = worker.getServiceHandler().getMetrics();
    try {
      if (forceContentLength) {
        entity.setChunked(false);
        if (forceContentLengthCopy && contentLength > 0) {
          entity.setContentLength(contentLength);
        } else {
          setStreamAsTempData(entity, messageFormatter, msgContext, format);
        }
      }

      worker.getServiceHandler().commitResponse(worker.getConn(), response);
      lstMetrics.reportResponseCode(response.getStatusLine().getStatusCode());
      OutputStream out = worker.getOutputStream();

      /*
       * if this is a dummy message to handle http 202 case with non-blocking IO
       * write an empty byte array as body
       */
      if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED) || Boolean.TRUE == noEntityBody) {
        out.write(new byte[0]);
      } else {
        if (forceContentLength) {
          if (forceContentLengthCopy && contentLength > 0) {
            messageFormatter.writeTo(msgContext, format, out, false);
          } else {
            writeMessageFromTempData(out, msgContext);
          }
        } else {
          messageFormatter.writeTo(msgContext, format, out, false);
        }
      }
      out.close();
      if (lstMetrics != null) {
        lstMetrics.incrementMessagesSent();
      }

    } catch (ProtocolException e) {
      log.error(e + " (Synapse may be trying to send an exact response more than once )");
    } catch (HttpException e) {
      if (lstMetrics != null) {
        lstMetrics.incrementFaultsSending();
      }
      handleException(
          "Unexpected HTTP protocol error sending response to : " + worker.getRemoteAddress(), e);
    } catch (ConnectionClosedException e) {
      if (lstMetrics != null) {
        lstMetrics.incrementFaultsSending();
      }
      log.warn("Connection closed by client : " + worker.getRemoteAddress());
    } catch (IllegalStateException e) {
      if (lstMetrics != null) {
        lstMetrics.incrementFaultsSending();
      }
      log.warn("Connection closed by client : " + worker.getRemoteAddress());
    } catch (IOException e) {
      if (lstMetrics != null) {
        lstMetrics.incrementFaultsSending();
      }
      handleException("IO Error sending response message to : " + worker.getRemoteAddress(), e);
    } catch (Exception e) {
      if (lstMetrics != null) {
        lstMetrics.incrementFaultsSending();
      }
      handleException(
          "General Error sending response message to : " + worker.getRemoteAddress(), e);
    }

    InputStream is = worker.getIs();
    if (is != null) {
      try {
        is.close();
      } catch (IOException ignore) {
      }
    }
  }