com.day.cq.commons.feed.StringResponseWrapper Maven / Gradle / Ivy
/*
* Copyright 1997-2008 Day Management AG
* Barfuesserplatz 6, 4001 Basel, Switzerland
* All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Day Management AG, ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Day.
*/
package com.day.cq.commons.feed;
import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper;
import org.apache.sling.api.SlingHttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.io.*;
/**
* The StringResponseWrapper
is a response wrapper
* providing the response body as a String.
*/
public class StringResponseWrapper extends SlingHttpServletResponseWrapper {
private StringWriter sw;
private PrintWriter pw;
private ByteArrayOutputStream bos;
private ServletOutputStream sos;
/**
* Creates a new StringResponseWrapper
using the specified
* response.
*
* @param slingHttpServletResponse The response
*/
public StringResponseWrapper(SlingHttpServletResponse slingHttpServletResponse) {
super(slingHttpServletResponse);
}
/**
* {@inheritDoc}
*/
public ServletOutputStream getOutputStream() throws IOException {
if (sos == null) {
if (pw != null) {
throw new IllegalStateException("Writer already obtained.");
}
bos = new ByteArrayOutputStream();
sos = new AtomFeedOutputStream(bos);
}
return sos;
}
/**
* {@inheritDoc}
*/
public PrintWriter getWriter() throws IOException {
if (pw == null) {
if (sos != null) {
throw new IllegalStateException("Output stream already obtained.");
}
sw = new StringWriter();
pw = new PrintWriter(sw);
}
return pw;
}
/**
* Returns the response body as a String
*
* @return The response body
* @throws java.io.UnsupportedEncodingException
* If the encoding is not supported
*/
public String getString() throws UnsupportedEncodingException {
if (sw != null) {
return sw.toString();
} else if (bos != null) {
return bos.toString(super.getCharacterEncoding());
} else {
return "";
}
}
/**
* The AtomFeedOutputStream
allows for deferring
* the data to another OutputStream
.
*/
public class AtomFeedOutputStream extends ServletOutputStream {
private final OutputStream out;
/**
* Creates a new AtomFeedOutputStream
using the
* specified output stream to write the data to.
*
* @param out The output stream
*/
public AtomFeedOutputStream(OutputStream out) {
this.out = out;
}
/**
* {@inheritDoc}
*/
public void write(int b) throws IOException {
out.write(b);
}
/**
* {@inheritDoc}
*/
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
/**
* {@inheritDoc}
*/
@Override
public void write(byte[] b) throws IOException {
out.write(b);
}
}
}