下面列出了javax.servlet.ServletOutputStream#print ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void performUpdate(final String query, final SailRepositoryConnection conn, final ServletOutputStream os, final String infer, final String vis) throws RepositoryException, MalformedQueryException, IOException {
final Update update = conn.prepareUpdate(QueryLanguage.SPARQL, query);
if (infer != null && infer.length() > 0) {
update.setBinding(RdfCloudTripleStoreConfiguration.CONF_INFER, VALUE_FACTORY.createLiteral(Boolean.parseBoolean(infer)));
}
if (conn.getSailConnection() instanceof RdfCloudTripleStoreConnection && vis != null) {
final RdfCloudTripleStoreConnection<?> sailConnection = (RdfCloudTripleStoreConnection<?>) conn.getSailConnection();
sailConnection.getConf().set(RdfCloudTripleStoreConfiguration.CONF_CV, vis);
}
final long startTime = System.currentTimeMillis();
try {
update.execute();
} catch (final UpdateExecutionException e) {
final String message = "Update could not be successfully completed for query: ";
os.print(String.format(message + "%s\n\n", StringEscapeUtils.escapeHtml4(query)));
log.error(message + LogUtils.clean(query), e);
}
log.info(String.format("Update Time = %.3f\n", (System.currentTimeMillis() - startTime) / 1000.));
}
/**
* service() - accept request and produce response
*
* @param request The HTTP request
* @param response The HTTP response
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setCharacterEncoding("UTF-8");
ServletOutputStream out = response.getOutputStream();
if (request.getParameterMap().isEmpty()) {
_log.warn("ignoring request without parameters");
return;
}
_log.debug(Utils.getLogRequestParameters(request.getParameterMap()));
if (request.getParameter("action") == null) {
response.setContentType("text/xml; charset=UTF-8");
out.print(handleRSRequest(request));
}
else {
response.setContentType("text/plain; charset=UTF-8");
out.print(handleCUIRequest(request));
}
}
catch (Exception e) {
_log.error("cannot handle request", e);
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log(request);
ServletOutputStream w = response.getOutputStream();
log("Got output stream " + w);
w.println("Previous value of attribute: " + request.getSession().getAttribute("A"));
request.getSession(true).removeAttribute("A");
w.println("New value of attribute: " + request.getSession().getAttribute("A"));
w.println("Encoded url: " + response.encodeURL("/"));
w.print("Served at: ");
w.print(request.getContextPath());
w.print(" ");
// PrintWriter w = response.getWriter();
// log("Got writer w");
// w.println("Previous value of attribute: " + request.getSession().getAttribute("A"));
// request.getSession(true).removeAttribute("A");
// w.println("New value of attribute: " + request.getSession().getAttribute("A"));
// w.append("Served at: ").append(request.getContextPath()).append(" ");
// w.flush();
}
/**
* Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an
* exception).
*
* @param resourceInfo
* The ResourceInfo object
* @param ostream
* The output stream to write to
* @param ranges
* Enumeration of the ranges the client wanted to retrieve
* @param contentType
* Content type of the resource
* @exception IOException
* if an input/output error occurs
*/
private void copy(ResourceInfo resourceInfo, ServletOutputStream ostream, Enumeration ranges, String contentType) throws IOException {
IOException exception = null;
while ((exception == null) && (ranges.hasMoreElements())) {
InputStream resourceInputStream = resourceInfo.getStream();
InputStream istream = // FIXME:ms: internationalization???????
new BufferedInputStream(resourceInputStream, input);
Range currentRange = (Range) ranges.nextElement();
// Writing MIME header.
ostream.println("--" + mimeSeparation);
if (contentType != null)
ostream.println("Content-Type: " + contentType);
ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/" + currentRange.length);
ostream.println();
// Printing content
exception = copyRange(istream, ostream, currentRange.start, currentRange.end);
try {
istream.close();
} catch (Throwable t) {
}
}
ostream.print("--" + mimeSeparation + "--");
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Writes the error to the HTTP response.
*
* @param response
* @param status
* @param t
* @throws ServletException
* @throws IOException
*/
private void handleError(HttpServletResponse response, Response.Status status, Throwable t) throws ServletException, IOException {
String message = status.getReasonPhrase();
try {
response.sendError(status.getStatusCode(), message);
response.setContentType(MediaType.APPLICATION_JSON);
StringWriter writer = new StringWriter();
Boolean compact = false;
JsonWriter jWriter = new JsonWriter(writer, compact);
try {
jWriter.startObject();
ErrorHelper.writeProperty(jWriter, ATTR_CODE, status.getStatusCode());
ErrorHelper.writeProperty(jWriter, ATTR_TEXT, message);
if ( t != null ) {
ErrorHelper.writeException(jWriter, t);
}
}
finally {
jWriter.endObject();
}
StringBuffer buffer = writer.getBuffer();
ServletOutputStream os = response.getOutputStream();
os.print(buffer.toString());
os.flush();
}
catch (IOException e) {
DAS_LOGGER.warn(e, "Error creating response."); //$NLW-DasServlet.Errorcreatingresponse-1$
}
}
protected void processConvertError(HttpServletResponse response, Exception ex) {
if (!response.isCommitted()) {
try {
ServletOutputStream os = response.getOutputStream();
os.print("raptor service error: ");
os.print(ex.getMessage());
os.flush();
os.close();
} catch (IOException e) {
log.error("processConvertError error.", e);
}
}
}
/**
* Called by the server (via the <code>service</code> method)
* to allow a servlet to handle a TRACE request.
*
* A TRACE returns the headers sent with the TRACE
* request to the client, so that they can be used in
* debugging. There's no need to override this method.
*
* @param req the {@link HttpServletRequest} object that
* contains the request the client made of
* the servlet
*
* @param resp the {@link HttpServletResponse} object that
* contains the response the servlet returns
* to the client
*
* @exception IOException if an input or output error occurs
* while the servlet is handling the
* TRACE request
*
* @exception ServletException if the request for the
* TRACE cannot be handled
*/
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
int responseLength;
String CRLF = "\r\n";
StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI())
.append(" ").append(req.getProtocol());
Enumeration<String> reqHeaderEnum = req.getHeaderNames();
while( reqHeaderEnum.hasMoreElements() ) {
String headerName = reqHeaderEnum.nextElement();
buffer.append(CRLF).append(headerName).append(": ")
.append(req.getHeader(headerName));
}
buffer.append(CRLF);
responseLength = buffer.length();
resp.setContentType("message/http");
resp.setContentLength(responseLength);
ServletOutputStream out = resp.getOutputStream();
out.print(buffer.toString());
out.close();
return;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String name = req.getParameter("name");
ServletOutputStream out = res.getOutputStream();
ProducerTemplate producer = camelContext.createProducerTemplate();
String result = producer.requestBody("direct:start", name, String.class);
out.print(result);
}
private void formular(ServletOutputStream out, HttpServletRequest requ,
HttpServletResponse resp, int sub) throws IOException {
out.print("<form method='post' action='");
out.print(requ.getRequestURI());
out.print("?action=");
out.print(ACT_INIT);
out.print("&sub=");
out.print(ACT_REPORT_1);
out.println("'>");
out.print("<input type='checkbox' name='preview' value='Y'");
if (requ.getParameter("preview") != null)
out.print(" checked ");
out.println(">preview<br>");
out.println("<input type=submit value='Report 1'>");
out.println("</form>");
if (sub != ACT_INIT) {
if (requ.getParameter("preview") != null) {
out.println("<script language='JavaScript'>");
out.print("w = window.open(\"");
out.print(requ.getRequestURI());
out.print("?action=");
out.print(sub);
out
.print("&preview=Y\", \"Printing\", \"width=800,height=450,scrollbars,menubar=yes,resizable=yes\");");
out.println("</script>");
} else {
out.print("<iframe src='");
out.print(requ.getRequestURI());
out.print("?action=");
out.print(sub);
out.println("' width='10' height='10' name='pdf_box'>");
}
}
out.println("</body>");
out.println("</html>");
}
/**
* Send a warning message to user about failed ICS file generation
* @param fileName
* @param warningMsg
*/
protected void sendDownloadWarning(String fileName, String warningMsg) {
FacesContext fc = FacesContext.getCurrentInstance();
ServletOutputStream out = null;
try {
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset();
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control","public, must-revalidate, post-check=0, pre-check=0, max-age=0");
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
out = response.getOutputStream();
warningMsg= warningMsg!=null? warningMsg:"Missing Scheduler tool on site";
out.print(warningMsg);
out.flush();
} catch (IOException ex) {
log.warn("Error generating file for download:" + ex.getMessage());
} finally {
try{
if(out != null) {
out.close();
}
}catch (Exception e){
//do nothing;
}
}
fc.responseComplete();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String name = req.getParameter("name");
if (name == null || name.isEmpty()) {
// Default to Hello world output
name = "world";
}
ServletOutputStream out = res.getOutputStream();
ProducerTemplate producer = camelctx.createProducerTemplate();
String result = producer.requestBody("direct:start", name, String.class);
out.print(result);
}
/**
* Called by the server (via the <code>service</code> method)
* to allow a servlet to handle a TRACE request.
*
* A TRACE returns the headers sent with the TRACE
* request to the client, so that they can be used in
* debugging. There's no need to override this method.
*
* @param req the {@link HttpServletRequest} object that
* contains the request the client made of
* the servlet
*
* @param resp the {@link HttpServletResponse} object that
* contains the response the servlet returns
* to the client
*
* @exception IOException if an input or output error occurs
* while the servlet is handling the
* TRACE request
*
* @exception ServletException if the request for the
* TRACE cannot be handled
*/
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
int responseLength;
String CRLF = "\r\n";
StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI())
.append(" ").append(req.getProtocol());
Enumeration<String> reqHeaderEnum = req.getHeaderNames();
while( reqHeaderEnum.hasMoreElements() ) {
String headerName = reqHeaderEnum.nextElement();
buffer.append(CRLF).append(headerName).append(": ")
.append(req.getHeader(headerName));
}
buffer.append(CRLF);
responseLength = buffer.length();
resp.setContentType("message/http");
resp.setContentLength(responseLength);
ServletOutputStream out = resp.getOutputStream();
out.print(buffer.toString());
out.close();
return;
}
/**
* Rendering to the local disk. <br>
* See {@link OperationalReport}
* @param req Request
* @param resp Response
* @param content Plain text content to be exported
* @param fileName Name of export file
* @param format Format of the file, as defined in this class
* @throws IOException If an input or output exception occurred
*/
public void getTextFileDownloadRendering(HttpServletRequest req, HttpServletResponse resp,
String content, String fileName, String format, String destinationURL) throws IOException {
resp.setContentType( getMIMEType(format) );
resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + getFileExtension(format) + "\"");
// if(destinationURL != null){
// resp.setHeader("Refresh", "1;URL=" + destinationURL);
// }
ServletOutputStream out = resp.getOutputStream();
out.print(content);
out.flush();
}
/**
* Send a warning message to user about failed ICS file generation
* @param fileName
* @param warningMsg
*/
protected void sendDownloadWarning(String fileName, String warningMsg) {
FacesContext fc = FacesContext.getCurrentInstance();
ServletOutputStream out = null;
try {
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset();
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control","public, must-revalidate, post-check=0, pre-check=0, max-age=0");
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
out = response.getOutputStream();
warningMsg= warningMsg!=null? warningMsg:"Missing Scheduler tool on site";
out.print(warningMsg);
out.flush();
} catch (IOException ex) {
log.warn("Error generating file for download:" + ex.getMessage());
} finally {
try{
if(out != null) {
out.close();
}
}catch (Exception e){
//do nothing;
}
}
fc.responseComplete();
}
/**
* Called by the server (via the <code>service</code> method)
* to allow a servlet to handle a TRACE request.
*
* A TRACE returns the headers sent with the TRACE
* request to the client, so that they can be used in
* debugging. There's no need to override this method.
*
*
*
* @param req the {@link HttpServletRequest} object that
* contains the request the client made of
* the servlet
*
*
* @param resp the {@link HttpServletResponse} object that
* contains the response the servlet returns
* to the client
*
*
* @exception IOException if an input or output error occurs
* while the servlet is handling the
* TRACE request
*
* @exception ServletException if the request for the
* TRACE cannot be handled
*
*/
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
int responseLength;
String CRLF = "\r\n";
String responseString = "TRACE "+ req.getRequestURI()+
" " + req.getProtocol();
Enumeration reqHeaderEnum = req.getHeaderNames();
while( reqHeaderEnum.hasMoreElements() ) {
String headerName = (String)reqHeaderEnum.nextElement();
responseString += CRLF + headerName + ": " +
req.getHeader(headerName);
}
responseString += CRLF;
responseLength = responseString.length();
resp.setContentType("message/http");
resp.setContentLength(responseLength);
ServletOutputStream out = resp.getOutputStream();
out.print(responseString);
out.close();
return;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
String name = req.getParameter("name");
ServletOutputStream out = res.getOutputStream();
if (name == null) {
out.print("There is no name query parameter, try adding ?name=donald");
} else {
// call the Camel route
String result = producer.requestBody("direct:hello", name, String.class);
out.print(result);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String name = req.getParameter("name");
ServletOutputStream out = res.getOutputStream();
ProducerTemplate producer = camelContext.createProducerTemplate();
String result = producer.requestBody("direct:start", name, String.class);
out.print(result);
}
public static void executeUpdate(String sql, ServletContext application, HttpServletRequest request, HttpServletResponse response) throws IOException{
response.setHeader("Content-Type", "text/html;charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
String connectionType = null;
Connection con = null;
PreparedStatement stmt = null;
TagUtil.printPageHead(out);
TagUtil.printPageNavbar(out);
TagUtil.printContentDiv(out);
try {
//Checking if connectionType is not, defaulting it to c3p0 if not set.
if(request.getParameter("connectionType") == null) {
connectionType = "c3p0";
} else {
connectionType = request.getParameter("connectionType");
}
con = ConnectionUtil.getConnection(application, connectionType);
out.println("<div class=\"panel-body\">");
out.println("<h1>SQL Query:</h1>");
out.println("<pre>");
out.println(sql);
out.println("</pre>");
logger.info(sql);
stmt = con.prepareStatement(sql);
logger.info("Created PreparedStatement: " + sql);
int result = stmt.executeUpdate();
logger.info("Executed: " + sql);
out.println("<h1>Altered Rows:</h1>");
out.print("<pre>" + result + "</pre>");
} catch(SQLException e) {
if(e.getMessage().equals("Attempted to execute a query with one or more bad parameters.")) {
int error = Integer.parseInt((String) application.getAttribute("defaultError"));
response.setStatus(error);
} else {
response.setStatus(500);
}
out.println("<div class=\"alert alert-danger\" role=\"alert\">");
out.println("<strong>SQLException:</strong> " + e.getMessage() + "<BR>");
if(logger.isDebugEnabled()) {
logger.debug(e.getMessage(), e);
} else {
logger.error(e);
}
while((e = e.getNextException()) != null) {
out.println(e.getMessage() + "<BR>");
}
} finally {
try {
if(stmt != null) {
logger.info("Closing PreparedStatement " + stmt);
stmt.close();
logger.info("Closed PreparedStatement " + stmt);
}
} catch (SQLException stmtCloseException) {
if(logger.isDebugEnabled()) {
logger.debug(stmtCloseException.getMessage(), stmtCloseException);
} else {
logger.error(stmtCloseException);
}
}
try {
if(con != null) {
logger.info("Closing Connection " + con);
con.close();
logger.info("Closed Connection " + con);
}
} catch (SQLException conCloseException) {
if(logger.isDebugEnabled()) {
logger.debug(conCloseException.getMessage(), conCloseException);
} else {
logger.error(conCloseException);
}
}
out.println("</DIV>");
TagUtil.printPageFooter(out);
out.close();
}
}
private void parseHtml(final String uri,
final ServletContext context,
final ServletOutputStream os,
final Stack<String> usedFiles)
throws IOException
{
if (usedFiles.contains(uri)) {
os.print("<b><font color=\"red\">SSI Error: Recursive include: " + uri
+ "</font></b>");
return;
}
usedFiles.push(uri);
InputStream raw;
try {
raw = context.getResourceAsStream(uri);
} catch (final Exception e) {
raw = null;
}
if (raw == null) {
os.print("<b><font color=\"red\">SSI Error: Error reading file: " + uri
+ "</font></b>");
return;
}
final InputStream is = new BufferedInputStream(raw);
byte c;
boolean tagBegin = false;
final StringBuffer buf = new StringBuffer(20);
while ((c = (byte) is.read()) != -1) {
if (c == '<') {
buf.setLength(0);
tagBegin = true;
} else if (tagBegin && c == '>') {
String restOfTag = buf.toString();
final String ssi_pattern = "!--#";
if (restOfTag.length() > ssi_pattern.length()
&& restOfTag.startsWith(ssi_pattern)) { // is this an
// ssi tag?
restOfTag = restOfTag.substring(ssi_pattern.length());
final String include_pattern = "include";
if (restOfTag.length() > include_pattern.length()
&& restOfTag.startsWith(include_pattern)) { // is
// this
// an
// include
// directive?
restOfTag = restOfTag.substring(include_pattern.length());
final String file_pattern = "file=\"";
final int index = restOfTag.indexOf(file_pattern);
if (index > 0 && Character.isWhitespace(restOfTag.charAt(0))) {
restOfTag = restOfTag.substring(index + file_pattern.length());
final String file = restOfTag.substring(0, restOfTag.indexOf('\"'));
parseHtml(uri.substring(0, uri.lastIndexOf("/") + 1) + file,
context, os, usedFiles);
} else {
os.print("<b><font color=\"red\">SSI Error: Unsupported directive</font></b>");
}
} else {
os.print("<b><font color=\"red\">SSI Error: Unsupported directive</font></b>");
}
} else {
os.print('<');
os.print(restOfTag);
os.print('>');
}
tagBegin = false;
} else if (tagBegin) {
buf.append((char) c);
} else {
os.write(c);
}
}
is.close();
usedFiles.pop();
}
/**
* Sends an HTML form to the browser to get the PDF
* @param stream the outputstream of the servlet
* @throws IOException
*/
private void isFinished(ServletOutputStream stream) throws IOException {
stream.print("<html>\n\t<head>\n\t\t<title>Finished!</title>\n\t</head>\n\t<body>");
stream.print("The document is finished:<form method=\"POST\"><input type=\"Submit\" value=\"Get PDF\"></form>\n\t</body>\n</html>");
}