Search in sources :

Example 6 with IRestorer

use of org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruption.IRestorer in project scout.rt by eclipse.

the class JsonRequestHelper method writeResponse.

/**
 * Writes the given {@link JSONObject} into the given {@link ServletResponse}.
 */
public void writeResponse(final ServletResponse servletResponse, final JSONObject jsonResponse) throws IOException {
    String jsonText = jsonResponse.toString();
    final byte[] data = jsonText.getBytes(StandardCharsets.UTF_8);
    servletResponse.setContentLength(data.length);
    if (servletResponse.getContentType() == null) {
        servletResponse.setContentType("application/json");
    }
    servletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
    // Clear the current thread's interruption status before writing the response to the output stream.
    // Otherwise, the stream gets silently corrupted, which makes the client to loose the connection.
    IRestorer interruption = ThreadInterruption.clear();
    try {
        servletResponse.getOutputStream().write(data);
    } catch (final EOFException e) {
        // NOSONAR
        final StringBuilder sb = new StringBuilder("EOF - Client disconnected, cannot write response");
        if (LOG.isDebugEnabled()) {
            sb.append(": ").append(jsonText);
        } else {
            sb.append(" (").append(data.length).append(" bytes)");
        }
        LOG.warn(sb.toString());
        return;
    } finally {
        interruption.restore();
    }
    LOG.debug("Returned: {}", formatJsonForLogging(jsonText));
}
Also used : IRestorer(org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruption.IRestorer) EOFException(java.io.EOFException)

Aggregations

IRestorer (org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruption.IRestorer)6 IRunnable (org.eclipse.scout.rt.platform.util.concurrent.IRunnable)3 Test (org.junit.Test)3 EOFException (java.io.EOFException)1 JMSException (javax.jms.JMSException)1