use of javax.servlet.ServletOutputStream in project eweb4j-framework by laiweiwei.
the class ActionExecution method handleResult.
private void handleResult() throws Exception {
this.exeActionLog();
if (retn == null)
return;
String baseUrl = (String) this.context.getServletContext().getAttribute(MVCConfigConstant.BASE_URL_KEY);
if (File.class.isAssignableFrom(retn.getClass())) {
File file = (File) retn;
this.handleDownload(file);
return;
} else if (File[].class.isAssignableFrom(retn.getClass())) {
File[] files = (File[]) retn;
String fileName = CommonUtil.getNowTime("yyyyMMddHHmmss") + "_" + "download.zip";
HttpServletResponse resp = this.context.getResponse();
resp.reset();
resp.setContentType("application/zip");
resp.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream outputStream = resp.getOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (File file : files) {
byte[] b = new byte[1024];
int len;
zip.putNextEntry(new ZipEntry(file.getName()));
FileInputStream fis = new FileInputStream(file);
while ((len = fis.read(b)) != -1) {
zip.write(b, 0, len);
}
fis.close();
}
zip.flush();
zip.close();
outputStream.flush();
return;
}
if (!String.class.isAssignableFrom(retn.getClass())) {
String mimeType = null;
boolean hasProduces = JAXWSUtil.hasProduces(method);
if (hasProduces) {
String[] mimeTypes = ProducesUtil.getProducesValue(method);
if (mimeTypes != null && mimeTypes.length > 0)
mimeType = mimeTypes[0];
}
if (mimeType == null || mimeType.trim().length() == 0)
mimeType = this.context.getRequest().getParameter(MVCConfigConstant.HTTP_HEADER_ACCEPT_PARAM);
if (mimeType == null || mimeType.trim().length() == 0) {
String contentType = this.context.getRequest().getContentType();
if (contentType != null) {
this.context.getResponse().setContentType(contentType);
mimeType = contentType.split(";")[0];
}
}
if (this.context.getWriter() == null)
this.context.setWriter(this.context.getResponse().getWriter());
if (MIMEType.JSON.equals(mimeType) || "json".equalsIgnoreCase(mimeType)) {
this.context.getResponse().setContentType(MIMEType.JSON);
this.context.getWriter().print(CommonUtil.toJson(retn));
} else if (MIMEType.XML.equals(mimeType) || "xml".equalsIgnoreCase(mimeType)) {
Class<?> cls = retn.getClass();
if (Collection.class.isAssignableFrom(cls)) {
Class<?> _cls = ClassUtil.getPojoClass(this.method);
if (_cls != null)
cls = _cls;
}
XMLWriter writer = BeanXMLUtil.getBeanXMLWriter(retn);
writer.setCheckStatck(true);
writer.setSubNameAuto(true);
writer.setClass(cls);
writer.setRootElementName(null);
this.context.getResponse().setContentType(MIMEType.XML);
this.context.getWriter().print(writer.toXml());
} else {
//默认都用json
this.context.getResponse().setContentType(MIMEType.JSON);
this.context.getWriter().print(CommonUtil.toJson(retn));
}
return;
}
List<String> produces = this.context.getActionConfigBean().getProduces();
if (produces != null && produces.size() > 0)
for (String produce : produces) {
this.context.getResponse().setContentType(produce);
break;
}
String re = String.valueOf(retn);
//model driven
for (Field f : fields) {
Method getter = ru.getGetter(f.getName());
if (getter == null)
continue;
String name = f.getName();
if (this.context.getModel().containsKey(name))
continue;
this.context.getModel().put(name, getter.invoke(actionObject));
}
this.context.getModel().put(MVCConfigConstant.BASE_URL_KEY, this.context.getServletContext().getAttribute(MVCConfigConstant.BASE_URL_KEY));
this.context.getModel().put(MVCConfigConstant.APPLICATION_SCOPE_KEY, new ServletContextProxy(this.context.getServletContext()).attrs());
this.context.getModel().put(MVCConfigConstant.SESSION_SCOPE_KEY, new HttpSessionProxy(this.context.getSession()).attrs());
this.context.getModel().put(MVCConfigConstant.COOKIE_SCOPE_KEY, new CookieProxy(this.context.getRequest().getCookies()).attrs());
this.context.getModel().put(MVCConfigConstant.REQ_PARAM_SCOPE_KEY, this.context.getQueryParamMap());
// 客户端重定向
if (re.startsWith(RenderType.REDIRECT + ":")) {
String url = re.substring((RenderType.REDIRECT + ":").length());
String location = url;
this.context.getResponse().sendRedirect(CommonUtil.replaceChinese2Utf8(location));
return;
} else if (re.startsWith(RenderType.ACTION + ":")) {
String path = re.substring((RenderType.ACTION + ":").length());
// ACTION 重定向
handleActionRedirect(context, path, baseUrl);
return;
} else if (re.startsWith(RenderType.OUT + ":")) {
String location = re.substring((RenderType.OUT + ":").length());
this.context.getWriter().print(location);
return;
} else if (re.startsWith(RenderType.FORWARD + ":") || re.startsWith(RenderType.JSP + ":") || re.endsWith("." + RenderType.JSP)) {
String[] str = re.split("@");
re = str[0];
String location = re;
if (re.startsWith(RenderType.FORWARD + ":"))
location = re.substring((RenderType.FORWARD + ":").length());
else if (re.startsWith(RenderType.JSP + ":"))
location = re.substring((RenderType.JSP + ":").length());
//渲染JSP
JSPRendererImpl render = new JSPRendererImpl();
render.setContext(context);
if (str.length > 1)
render.layout(str[1]);
render.target(location).render(context.getWriter(), context.getModel());
return;
} else if (re.startsWith(RenderType.FREEMARKER + ":") || re.startsWith(RenderType.FREEMARKER2 + ":") || re.endsWith("." + RenderType.FREEMARKER2)) {
String[] str = re.split("@");
re = str[0];
String location = re;
if (re.startsWith(RenderType.FREEMARKER + ":"))
location = re.substring((RenderType.FREEMARKER + ":").length());
else if (re.startsWith(RenderType.FREEMARKER2 + ":"))
location = re.substring((RenderType.FREEMARKER2 + ":").length());
//渲染Freemarker
Renderer render = RenderFactory.create(RenderType.FREEMARKER).target(location);
if (str.length > 1)
render.layout(str[1]);
render.render(context.getWriter(), context.getModel());
// this.context.getWriter().flush();
return;
} else if (re.startsWith(RenderType.VELOCITY + ":") || re.startsWith(RenderType.VELOCITY2 + ":") || re.endsWith("." + RenderType.VELOCITY2)) {
String[] str = re.split("@");
re = str[0];
String location = re;
if (re.startsWith(RenderType.VELOCITY + ":"))
location = re.substring((RenderType.VELOCITY + ":").length());
else if (re.startsWith(RenderType.VELOCITY2 + ":"))
location = re.substring((RenderType.VELOCITY2 + ":").length());
//渲染Velocity
Renderer render = RenderFactory.create(RenderType.VELOCITY).target(location);
if (str.length > 1)
render.layout(str[1]);
render.render(context.getWriter(), context.getModel());
// this.context.getWriter().flush();
return;
} else {
List<ResultConfigBean> results = this.context.getActionConfigBean().getResult();
if (results == null || results.size() == 0) {
this.context.getWriter().print(retn);
// this.context.getWriter().flush();
return;
}
boolean isOut = true;
for (ResultConfigBean r : results) {
if (!"_props_".equals(r.getName()) && !r.getName().equals(re) && !"".equals(re)) {
continue;
}
isOut = false;
String type = r.getType();
String location = r.getLocation();
if (RenderType.REDIRECT.equalsIgnoreCase(type)) {
this.context.getResponse().sendRedirect(CommonUtil.replaceChinese2Utf8(location));
return;
} else if (RenderType.FORWARD.equalsIgnoreCase(type) || RenderType.JSP.equalsIgnoreCase(type)) {
//渲染JSP
String[] str = location.split("@");
JSPRendererImpl render = new JSPRendererImpl();
render.setContext(context);
if (str.length > 1)
render.layout(str[1]);
render.target(str[0]).render(context.getWriter(), context.getModel());
return;
} else if (RenderType.FREEMARKER.equalsIgnoreCase(type) || RenderType.FREEMARKER2.equalsIgnoreCase(type)) {
//渲染Freemarker
String[] str = location.split("@");
Renderer render = RenderFactory.create(RenderType.FREEMARKER).target(str[0]);
if (str.length > 1)
render.layout(str[1]);
render.render(context.getWriter(), context.getModel());
return;
} else if (RenderType.VELOCITY.equalsIgnoreCase(type) || RenderType.VELOCITY2.equalsIgnoreCase(type)) {
//渲染Velocity
String[] str = location.split("@");
Renderer render = RenderFactory.create(RenderType.VELOCITY).target(str[0]);
if (str.length > 1)
render.layout(str[1]);
render.render(context.getWriter(), context.getModel());
return;
} else if (RenderType.ACTION.equalsIgnoreCase(type)) {
// ACTION 重定向
handleActionRedirect(context, location, baseUrl);
return;
} else if (RenderType.OUT.equalsIgnoreCase(type) || location.trim().length() == 0) {
this.context.getWriter().print(location);
return;
}
}
if (isOut) {
this.context.getWriter().print(retn);
// this.context.getWriter().flush();
}
}
}
use of javax.servlet.ServletOutputStream in project solo by b3log.
the class AdminConsole method exportSQL.
/**
* Exports data as SQL file.
*
* @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response
* @param context the specified HTTP request context
* @throws Exception exception
*/
@RequestProcessing(value = "/console/export/sql", method = HTTPRequestMethod.GET)
public void exportSQL(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
if (!userQueryService.isAdminLoggedIn(request)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
if (!Latkes.runsWithJDBCDatabase() || RuntimeDatabase.MYSQL != Latkes.getRuntimeDatabase()) {
context.renderJSON().renderMsg("Just support MySQL export now");
return;
}
final String dbUser = Latkes.getLocalProperty("jdbc.username");
final String dbPwd = Latkes.getLocalProperty("jdbc.password");
final String dbURL = Latkes.getLocalProperty("jdbc.URL");
String db = StringUtils.substringAfterLast(dbURL, "/");
db = StringUtils.substringBefore(db, "?");
String sql;
try {
if (StringUtils.isNotBlank(dbPwd)) {
sql = Execs.exec("mysqldump -u" + dbUser + " -p" + dbPwd + " --databases " + db);
} else {
sql = Execs.exec("mysqldump -u" + dbUser + " --databases " + db);
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Export failed", e);
context.renderJSON().renderMsg("Export failed, please check log");
return;
}
final String tmpDir = System.getProperty("java.io.tmpdir");
String localFilePath = tmpDir + "/b3_solo_" + UUID.randomUUID().toString() + ".sql";
LOGGER.info(localFilePath);
final File localFile = new File(localFilePath);
try {
final byte[] data = sql.getBytes("UTF-8");
OutputStream output = new FileOutputStream(localFile);
IOUtils.write(data, output);
IOUtils.closeQuietly(output);
final File zipFile = ZipUtil.zip(localFile);
final FileInputStream inputStream = new FileInputStream(zipFile);
final byte[] zipData = IOUtils.toByteArray(inputStream);
IOUtils.closeQuietly(inputStream);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"solo.sql.zip\"");
final ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(zipData);
outputStream.flush();
outputStream.close();
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Export failed", e);
context.renderJSON().renderMsg("Export failed, please check log");
return;
}
}
use of javax.servlet.ServletOutputStream in project h2o-3 by h2oai.
the class CustomHttpFilterTest method testNoLog.
@Test
public void testNoLog() throws Exception {
final Logger _logger = Logger.getLogger("water.default");
_logger.addAppender(new AppenderSkeleton() {
@Override
protected void append(LoggingEvent event) {
if (event.getRenderedMessage().contains("GET"))
throw new RuntimeException("All GETs should be filtered");
}
@Override
public void close() {
_logger.removeAppender(this);
}
@Override
public boolean requiresLayout() {
return false;
}
});
// let's filter out all GETs
RequestServer.setFilters(RequestServer.defaultFilter(), new RequestServer.HttpLogFilter() {
@Override
public boolean filter(RequestUri uri, Properties header, Properties parms) {
String[] path = uri.getPath();
return path[1].equals("GET");
}
});
// mock up a "GET /flow/index.html" call
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getServletPath()).thenReturn("/flow/index.html");
when(request.getRequestURI()).thenReturn("/flow/index.html");
// mock up the headers
// define the headers you want to be returned
HashMap<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36");
headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
headers.put("Cookie", "_yummy");
headers.put("Accept-Encoding", "gzip, deflate, sdch");
headers.put("Host", H2O.getIpPortString());
headers.put("Upgrade-Insecure-Requests", "1");
headers.put("Accept-Language", "en-US,en;q=0.8");
headers.put("Connection", "keep-alive");
// create an Enumeration over the header keys
final Iterator<String> iterator = headers.keySet().iterator();
Enumeration headerNames = new Enumeration<String>() {
@Override
public boolean hasMoreElements() {
return iterator.hasNext();
}
@Override
public String nextElement() {
return iterator.next();
}
};
when(request.getHeaderNames()).thenReturn(headerNames);
when(request.getHeader("User-Agent")).thenReturn(headers.get("User-Agent"));
when(request.getHeader("Accept")).thenReturn(headers.get("Accept"));
when(request.getHeader("Cookie")).thenReturn(headers.get("Cookie"));
when(request.getHeader("Accept-Encoding")).thenReturn(headers.get("Accept-Encoding"));
when(request.getHeader("Host")).thenReturn(headers.get("Host"));
when(request.getHeader("Upgrade-Insecure-Requests")).thenReturn(headers.get("Upgrade-Insecure-Requests"));
when(request.getHeader("Accept-Language")).thenReturn(headers.get("Accept-Language"));
when(request.getHeader("Connection")).thenReturn(headers.get("Connection"));
when(request.getParameterMap()).thenReturn(new HashMap<String, String[]>());
when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
}
});
// start the request lifecycle
H2O.getJetty().getServer().getChildHandlersByClass(JettyHTTPD.GateHandler.class)[0].handle("/", null, request, response);
new RequestServer().doGet(request, response);
}
use of javax.servlet.ServletOutputStream in project gocd by gocd.
the class XmlView method renderMergedOutputModel.
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Document document = (Document) model.get("document");
ServletOutputStream outputStream = response.getOutputStream();
try {
XmlUtils.writeXml(document, outputStream);
} finally {
IOUtils.closeQuietly(outputStream);
}
}
use of javax.servlet.ServletOutputStream in project camel by apache.
the class DefaultHttpBinding method doWriteDirectResponse.
protected void doWriteDirectResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
// if content type is serialized Java object, then serialize and write it to the response
String contentType = message.getHeader(Exchange.CONTENT_TYPE, String.class);
if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
if (allowJavaSerializedObject || isTransferException()) {
try {
Object object = message.getMandatoryBody(Serializable.class);
HttpHelper.writeObjectToServletResponse(response, object);
// object is written so return
return;
} catch (InvalidPayloadException e) {
throw new IOException(e);
}
} else {
throw new RuntimeCamelException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed");
}
}
// prefer streaming
InputStream is = null;
if (checkChunked(message, exchange)) {
is = message.getBody(InputStream.class);
} else {
// try to use input stream first, so we can copy directly
if (!isText(contentType)) {
is = exchange.getContext().getTypeConverter().tryConvertTo(InputStream.class, message.getBody());
}
}
if (is != null) {
ServletOutputStream os = response.getOutputStream();
if (!checkChunked(message, exchange)) {
CachedOutputStream stream = new CachedOutputStream(exchange);
try {
// copy directly from input stream to the cached output stream to get the content length
int len = copyStream(is, stream, response.getBufferSize());
// we need to setup the length if message is not chucked
response.setContentLength(len);
OutputStream current = stream.getCurrentStream();
if (current instanceof ByteArrayOutputStream) {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming (direct) response in non-chunked mode with content-length {}");
}
ByteArrayOutputStream bos = (ByteArrayOutputStream) current;
bos.writeTo(os);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming response in non-chunked mode with content-length {} and buffer size: {}", len, len);
}
copyStream(stream.getInputStream(), os, len);
}
} finally {
IOHelper.close(is, os);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming response in chunked mode with buffer size {}", response.getBufferSize());
}
copyStream(is, os, response.getBufferSize());
}
} else {
// not convertable as a stream so fallback as a String
String data = message.getBody(String.class);
if (data != null) {
// set content length and encoding before we write data
String charset = IOHelper.getCharsetName(exchange, true);
final int dataByteLength = data.getBytes(charset).length;
response.setCharacterEncoding(charset);
response.setContentLength(dataByteLength);
if (LOG.isDebugEnabled()) {
LOG.debug("Writing response in non-chunked mode as plain text with content-length {} and buffer size: {}", dataByteLength, response.getBufferSize());
}
try {
response.getWriter().print(data);
} finally {
response.getWriter().flush();
}
}
}
}
Aggregations