56
// in java/org/apache/struts2/config/StrutsXmlConfigurationProvider.java
Override
protected Iterator<URL> getConfigurationUrls(String fileName) throws IOException {
URL url = null;
if (baseDir != null) {
url = findInFileSystem(fileName);
if (url == null) {
return super.getConfigurationUrls(fileName);
}
}
if (url != null) {
List<URL> list = new ArrayList<URL>();
list.add(url);
return list.iterator();
} else {
return super.getConfigurationUrls(fileName);
}
}
// in java/org/apache/struts2/config/StrutsXmlConfigurationProvider.java
protected URL findInFileSystem(String fileName) throws IOException {
URL url = null;
File file = new File(fileName);
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to load file " + file);
}
// Trying relative path to original file
if (!file.exists()) {
file = new File(baseDir, fileName);
}
if (file.exists()) {
try {
url = file.toURI().toURL();
} catch (MalformedURLException e) {
throw new IOException("Unable to convert "+file+" to a URL");
}
}
return url;
}
// in java/org/apache/struts2/components/template/FreemarkerTemplateEngine.java
public void renderTemplate(TemplateRenderingContext templateContext) throws Exception {
// get the various items required from the stack
ValueStack stack = templateContext.getStack();
Map context = stack.getContext();
ServletContext servletContext = (ServletContext) context.get(ServletActionContext.SERVLET_CONTEXT);
HttpServletRequest req = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse res = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
// prepare freemarker
Configuration config = freemarkerManager.getConfiguration(servletContext);
// get the list of templates we can use
List<Template> templates = templateContext.getTemplate().getPossibleTemplates(this);
// find the right template
freemarker.template.Template template = null;
String templateName = null;
Exception exception = null;
for (Template t : templates) {
templateName = getFinalTemplateName(t);
try {
// try to load, and if it works, stop at the first one
template = config.getTemplate(templateName);
break;
} catch (ParseException e) {
// template was found but was invalid - always report this.
exception = e;
break;
} catch (IOException e) {
// FileNotFoundException is anticipated - report the first IOException if no template found
if (exception == null) {
exception = e;
}
}
}
if (template == null) {
if (LOG.isErrorEnabled()) {
LOG.error("Could not load the FreeMarker template named '" + templateContext.getTemplate().getName() +"':");
for (Template t : templates) {
LOG.error("Attempted: " + getFinalTemplateName(t));
}
LOG.error("The TemplateLoader provided by the FreeMarker Configuration was a: "+config.getTemplateLoader().getClass().getName());
}
if (exception != null) {
throw exception;
} else {
return;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Rendering template " + templateName);
}
ActionInvocation ai = ActionContext.getContext().getActionInvocation();
Object action = (ai == null) ? null : ai.getAction();
SimpleHash model = freemarkerManager.buildTemplateModel(stack, action, servletContext, req, res, config.getObjectWrapper());
model.put("tag", templateContext.getTag());
model.put("themeProperties", getThemeProps(templateContext.getTemplate()));
// the BodyContent JSP writer doesn't like it when FM flushes automatically --
// so let's just not do it (it will be flushed eventually anyway)
Writer writer = templateContext.getWriter();
final Writer wrapped = writer;
writer = new Writer() {
public void write(char cbuf[], int off, int len) throws IOException {
wrapped.write(cbuf, off, len);
}
public void flush() throws IOException {
// nothing!
}
public void close() throws IOException {
wrapped.close();
}
};
try {
stack.push(templateContext.getTag());
template.process(model, writer);
} finally {
stack.pop();
}
}
// in java/org/apache/struts2/components/template/FreemarkerTemplateEngine.java
public void write(char cbuf[], int off, int len) throws IOException {
wrapped.write(cbuf, off, len);
}
// in java/org/apache/struts2/components/template/FreemarkerTemplateEngine.java
public void flush() throws IOException {
// nothing!
}
// in java/org/apache/struts2/components/template/FreemarkerTemplateEngine.java
public void close() throws IOException {
wrapped.close();
}
// in java/org/apache/struts2/components/Include.java
public static void include( String relativePath, Writer writer, ServletRequest request,
HttpServletResponse response ) throws ServletException, IOException {
include(relativePath, writer, request, response, null);
}
// in java/org/apache/struts2/components/Include.java
public static void include( String relativePath, Writer writer, ServletRequest request,
HttpServletResponse response, String encoding ) throws ServletException, IOException {
String resourcePath = getContextRelativePath(request, relativePath);
RequestDispatcher rd = request.getRequestDispatcher(resourcePath);
if (rd == null) {
throw new ServletException("Not a valid resource path:" + resourcePath);
}
PageResponse pageResponse = new PageResponse(response);
// Include the resource
rd.include(request, pageResponse);
if (encoding != null) {
// Use given encoding
pageResponse.getContent().writeTo(writer, encoding);
} else {
//use the platform specific encoding
pageResponse.getContent().writeTo(writer, systemEncoding);
}
}
// in java/org/apache/struts2/components/Include.java
public FastByteArrayOutputStream getBuffer() throws IOException {
flush();
return buffer;
}
// in java/org/apache/struts2/components/Include.java
public void close() throws IOException {
buffer.close();
}
// in java/org/apache/struts2/components/Include.java
public void flush() throws IOException {
buffer.flush();
}
// in java/org/apache/struts2/components/Include.java
public void write(byte[] b, int o, int l) throws IOException {
buffer.write(b, o, l);
}
// in java/org/apache/struts2/components/Include.java
public void write(int i) throws IOException {
buffer.write(i);
}
// in java/org/apache/struts2/components/Include.java
public void write(byte[] b) throws IOException {
buffer.write(b);
}
// in java/org/apache/struts2/components/Include.java
public FastByteArrayOutputStream getContent() throws IOException {
//if we are using a writer, we need to flush the
//data to the underlying outputstream.
//most containers do this - but it seems Jetty 4.0.5 doesn't
if (pagePrintWriter != null) {
pagePrintWriter.flush();
}
return ((PageOutputStream) getOutputStream()).getBuffer();
}
// in java/org/apache/struts2/components/Include.java
public ServletOutputStream getOutputStream() throws IOException {
if (pageOutputStream == null) {
pageOutputStream = new PageOutputStream();
}
return pageOutputStream;
}
// in java/org/apache/struts2/components/Include.java
public PrintWriter getWriter() throws IOException {
if (pagePrintWriter == null) {
pagePrintWriter = new PrintWriter(new OutputStreamWriter(getOutputStream(), getCharacterEncoding()));
}
return pagePrintWriter;
}
// in java/org/apache/struts2/views/freemarker/tags/CallbackWriter.java
public void close() throws IOException {
if (bean.usesBody()) {
body.close();
}
}
// in java/org/apache/struts2/views/freemarker/tags/CallbackWriter.java
public void flush() throws IOException {
writer.flush();
if (bean.usesBody()) {
body.flush();
}
}
// in java/org/apache/struts2/views/freemarker/tags/CallbackWriter.java
public void write(char cbuf[], int off, int len) throws IOException {
if (bean.usesBody() && !afterBody) {
body.write(cbuf, off, len);
} else {
writer.write(cbuf, off, len);
}
}
// in java/org/apache/struts2/views/freemarker/tags/CallbackWriter.java
public int onStart() throws TemplateModelException, IOException {
boolean result = bean.start(this);
if (result) {
return EVALUATE_BODY;
} else {
return SKIP_BODY;
}
}
// in java/org/apache/struts2/views/freemarker/tags/CallbackWriter.java
public int afterBody() throws TemplateModelException, IOException {
afterBody = true;
boolean result = bean.end(this, bean.usesBody() ? body.toString() : "");
if (result) {
return REPEAT_EVALUATION;
} else {
return END_EVALUATION;
}
}
// in java/org/apache/struts2/views/freemarker/tags/TagModel.java
public Writer getWriter(Writer writer, Map params)
throws TemplateModelException, IOException {
Component bean = getBean();
Container container = (Container) stack.getContext().get(ActionContext.CONTAINER);
container.inject(bean);
Map unwrappedParameters = unwrapParameters(params);
bean.copyParams(unwrappedParameters);
return new CallbackWriter(bean, writer);
}
// in java/org/apache/struts2/views/freemarker/FreemarkerResult.java
public void doExecute(String locationArg, ActionInvocation invocation) throws IOException, TemplateException {
this.location = locationArg;
this.invocation = invocation;
this.configuration = getConfiguration();
this.wrapper = getObjectWrapper();
ActionContext ctx = invocation.getInvocationContext();
HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
if (!locationArg.startsWith("/")) {
String base = ResourceUtil.getResourceBase(req);
locationArg = base + "/" + locationArg;
}
Template template = configuration.getTemplate(locationArg, deduceLocale());
TemplateModel model = createModel();
// Give subclasses a chance to hook into preprocessing
if (preTemplateProcess(template, model)) {
try {
// Process the template
Writer writer = getWriter();
if (isWriteIfCompleted() || configuration.getTemplateExceptionHandler() == TemplateExceptionHandler.RETHROW_HANDLER) {
CharArrayWriter parentCharArrayWriter = (CharArrayWriter) req.getAttribute(PARENT_TEMPLATE_WRITER);
boolean isTopTemplate = false;
if (isTopTemplate = (parentCharArrayWriter == null)) {
//this is the top template
parentCharArrayWriter = new CharArrayWriter();
//set it in the request because when the "action" tag is used a new VS and ActionContext is created
req.setAttribute(PARENT_TEMPLATE_WRITER, parentCharArrayWriter);
}
try {
template.process(model, parentCharArrayWriter);
if (isTopTemplate) {
parentCharArrayWriter.flush();
parentCharArrayWriter.writeTo(writer);
}
} finally {
if (isTopTemplate && parentCharArrayWriter != null) {
req.removeAttribute(PARENT_TEMPLATE_WRITER);
parentCharArrayWriter.close();
}
}
} else {
template.process(model, writer);
}
} finally {
// Give subclasses a chance to hook into postprocessing
postTemplateProcess(template, model);
}
}
}
// in java/org/apache/struts2/views/freemarker/FreemarkerResult.java
protected Writer getWriter() throws IOException {
if(writer != null) {
return writer;
}
return ServletActionContext.getResponse().getWriter();
}
// in java/org/apache/struts2/views/freemarker/FreemarkerResult.java
protected void postTemplateProcess(Template template, TemplateModel data) throws IOException {
}
// in java/org/apache/struts2/views/freemarker/FreemarkerResult.java
protected boolean preTemplateProcess(Template template, TemplateModel model) throws IOException {
Object attrContentType = template.getCustomAttribute("content_type");
HttpServletResponse response = ServletActionContext.getResponse();
if (response.getContentType() == null) {
if (attrContentType != null) {
response.setContentType(attrContentType.toString());
} else {
String contentType = getContentType();
if (contentType == null) {
contentType = "text/html";
}
String encoding = template.getEncoding();
if (encoding != null) {
contentType = contentType + "; charset=" + encoding;
}
response.setContentType(contentType);
}
} else if(isInsideActionTag()){
//trigger com.opensymphony.module.sitemesh.filter.PageResponseWrapper.deactivateSiteMesh()
response.setContentType(response.getContentType());
}
return true;
}
// in java/org/apache/struts2/views/xslt/XSLTResult.java
protected Templates getTemplates(String path) throws TransformerException, IOException {
String pathFromRequest = ServletActionContext.getRequest().getParameter("xslt.location");
if (pathFromRequest != null)
path = pathFromRequest;
if (path == null)
throw new TransformerException("Stylesheet path is null");
Templates templates = templatesCache.get(path);
if (noCache || (templates == null)) {
synchronized (templatesCache) {
URL resource = ServletActionContext.getServletContext().getResource(path);
if (resource == null) {
throw new TransformerException("Stylesheet " + path + " not found in resources.");
}
if (LOG.isDebugEnabled()) {
LOG.debug("Preparing XSLT stylesheet templates: " + path);
}
TransformerFactory factory = TransformerFactory.newInstance();
factory.setURIResolver(getURIResolver());
templates = factory.newTemplates(new StreamSource(resource.openStream()));
templatesCache.put(path, templates);
}
}
return templates;
}
// in java/org/apache/struts2/views/velocity/components/AbstractDirective.java
public boolean render(InternalContextAdapter ctx, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
// get the bean
ValueStack stack = (ValueStack) ctx.get("stack");
HttpServletRequest req = (HttpServletRequest) stack.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse res = (HttpServletResponse) stack.getContext().get(ServletActionContext.HTTP_RESPONSE);
Component bean = getBean(stack, req, res);
Container container = (Container) stack.getContext().get(ActionContext.CONTAINER);
container.inject(bean);
// get the parameters
Map params = createPropertyMap(ctx, node);
bean.copyParams(params);
//bean.addAllParameters(params);
bean.start(writer);
if (getType() == BLOCK) {
Node body = node.jjtGetChild(node.jjtGetNumChildren() - 1);
body.render(ctx, writer);
}
bean.end(writer, "");
return true;
}
// in java/org/apache/struts2/dispatcher/multipart/JakartaMultiPartRequest.java
private RequestContext createRequestContext(final HttpServletRequest req) {
return new RequestContext() {
public String getCharacterEncoding() {
return req.getCharacterEncoding();
}
public String getContentType() {
return req.getContentType();
}
public int getContentLength() {
return req.getContentLength();
}
public InputStream getInputStream() throws IOException {
InputStream in = req.getInputStream();
if (in == null) {
throw new IOException("Missing content in the request");
}
return req.getInputStream();
}
};
}
// in java/org/apache/struts2/dispatcher/multipart/JakartaMultiPartRequest.java
public InputStream getInputStream() throws IOException {
InputStream in = req.getInputStream();
if (in == null) {
throw new IOException("Missing content in the request");
}
return req.getInputStream();
}
// in java/org/apache/struts2/dispatcher/ActionContextCleanUp.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String timerKey = "ActionContextCleanUp_doFilter: ";
try {
UtilTimerStack.push(timerKey);
try {
Integer count = (Integer)request.getAttribute(COUNTER);
if (count == null) {
count = Integer.valueOf(1);
}
else {
count = Integer.valueOf(count.intValue()+1);
}
request.setAttribute(COUNTER, count);
//LOG.debug("filtering counter="+count);
chain.doFilter(request, response);
} finally {
int counterVal = ((Integer)request.getAttribute(COUNTER)).intValue();
counterVal -= 1;
request.setAttribute(COUNTER, Integer.valueOf(counterVal));
cleanUp(request);
}
}
finally {
UtilTimerStack.pop(timerKey);
}
}
// in java/org/apache/struts2/dispatcher/Dispatcher.java
public HttpServletRequest wrapRequest(HttpServletRequest request, ServletContext servletContext) throws IOException {
// don't wrap more than once
if (request instanceof StrutsRequestWrapper) {
return request;
}
String content_type = request.getContentType();
if (content_type != null && content_type.contains("multipart/form-data")) {
MultiPartRequest mpr = null;
//check for alternate implementations of MultiPartRequest
Set<String> multiNames = getContainer().getInstanceNames(MultiPartRequest.class);
if (multiNames != null) {
for (String multiName : multiNames) {
if (multiName.equals(multipartHandlerName)) {
mpr = getContainer().getInstance(MultiPartRequest.class, multiName);
}
}
}
if (mpr == null ) {
mpr = getContainer().getInstance(MultiPartRequest.class);
}
request = new MultiPartRequestWrapper(mpr, request, getSaveDir(servletContext));
} else {
request = new StrutsRequestWrapper(request);
}
return request;
}
// in java/org/apache/struts2/dispatcher/Dispatcher.java
public void cleanUpRequest(HttpServletRequest request) throws IOException {
if (!(request instanceof MultiPartRequestWrapper)) {
return;
}
MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
String inputValue = (String) fileParameterNames.nextElement();
File[] files = multiWrapper.getFiles(inputValue);
for (File currentFile : files) {
if (LOG.isInfoEnabled()) {
String msg = LocalizedTextUtil.findText(this.getClass(), "struts.messages.removing.file", Locale.ENGLISH, "no.message.found", new Object[]{inputValue, currentFile});
LOG.info(msg);
}
if ((currentFile != null) && currentFile.isFile()) {
if (!currentFile.delete()) {
if (LOG.isWarnEnabled()) {
LOG.warn("Resource Leaking: Could not remove uploaded file '" + currentFile.getCanonicalPath() + "'.");
}
}
}
}
}
}
// in java/org/apache/struts2/dispatcher/DefaultStaticContentLoader.java
public void findStaticResource(String path, HttpServletRequest request, HttpServletResponse response)
throws IOException {
String name = cleanupPath(path);
for (String pathPrefix : pathPrefixes) {
URL resourceUrl = findResource(buildPath(name, pathPrefix));
if (resourceUrl != null) {
InputStream is = null;
try {
//check that the resource path is under the pathPrefix path
String pathEnding = buildPath(name, pathPrefix);
if (resourceUrl.getFile().endsWith(pathEnding))
is = resourceUrl.openStream();
} catch (IOException ex) {
// just ignore it
continue;
}
//not inside the try block, as this could throw IOExceptions also
if (is != null) {
process(is, path, request, response);
return;
}
}
}
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
// in java/org/apache/struts2/dispatcher/DefaultStaticContentLoader.java
protected void process(InputStream is, String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
if (is != null) {
Calendar cal = Calendar.getInstance();
// check for if-modified-since, prior to any other headers
long ifModifiedSince = 0;
try {
ifModifiedSince = request.getDateHeader("If-Modified-Since");
} catch (Exception e) {
log.warn("Invalid If-Modified-Since header value: '"
+ request.getHeader("If-Modified-Since") + "', ignoring");
}
long lastModifiedMillis = lastModifiedCal.getTimeInMillis();
long now = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_MONTH, 1);
long expires = cal.getTimeInMillis();
if (ifModifiedSince > 0 && ifModifiedSince <= lastModifiedMillis) {
// not modified, content is not sent - only basic
// headers and status SC_NOT_MODIFIED
response.setDateHeader("Expires", expires);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
is.close();
return;
}
// set the content-type header
String contentType = getContentType(path);
if (contentType != null) {
response.setContentType(contentType);
}
if (serveStaticBrowserCache) {
// set heading information for caching static content
response.setDateHeader("Date", now);
response.setDateHeader("Expires", expires);
response.setDateHeader("Retry-After", expires);
response.setHeader("Cache-Control", "public");
response.setDateHeader("Last-Modified", lastModifiedMillis);
} else {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
}
try {
copy(is, response.getOutputStream());
} finally {
is.close();
}
return;
}
}
// in java/org/apache/struts2/dispatcher/DefaultStaticContentLoader.java
protected URL findResource(String path) throws IOException {
return ClassLoaderUtil.getResource(path, getClass());
}
// in java/org/apache/struts2/dispatcher/DefaultStaticContentLoader.java
protected void copy(InputStream input, OutputStream output) throws IOException {
final byte[] buffer = new byte[4096];
int n;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
output.flush();
}
// in java/org/apache/struts2/dispatcher/ng/filter/StrutsExecuteFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (excludeUrl(request)) {
chain.doFilter(request, response);
return;
}
// This is necessary since we need the dispatcher instance, which was created by the prepare filter
if (execute == null) {
lazyInit();
}
ActionMapping mapping = prepare.findActionMapping(request, response);
//if recusrion counter is > 1, it means we are in a "forward", in that case a mapping will still be
//in the request, if we handle it, it will lead to an infinte loop, see WW-3077
Integer recursionCounter = (Integer) request.getAttribute(PrepareOperations.CLEANUP_RECURSION_COUNTER);
if (mapping == null || recursionCounter > 1) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
execute.executeAction(request, response, mapping);
}
}
// in java/org/apache/struts2/dispatcher/ng/filter/StrutsPrepareAndExecuteFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
prepare.setEncodingAndLocale(request, response);
prepare.createActionContext(request, response);
prepare.assignDispatcherToThread();
if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
chain.doFilter(request, response);
} else {
request = prepare.wrapRequest(request);
ActionMapping mapping = prepare.findActionMapping(request, response, true);
if (mapping == null) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
execute.executeAction(request, response, mapping);
}
}
} finally {
prepare.cleanupRequest(request);
}
}
// in java/org/apache/struts2/dispatcher/ng/filter/StrutsPrepareFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
prepare.setEncodingAndLocale(request, response);
prepare.createActionContext(request, response);
prepare.assignDispatcherToThread();
if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
request.setAttribute(REQUEST_EXCLUDED_FROM_ACTION_MAPPING, new Object());
} else {
request = prepare.wrapRequest(request);
prepare.findActionMapping(request, response);
}
chain.doFilter(request, response);
} finally {
prepare.cleanupRequest(request);
}
}
// in java/org/apache/struts2/dispatcher/ng/servlet/StrutsServlet.java
Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
try {
prepare.createActionContext(request, response);
prepare.assignDispatcherToThread();
prepare.setEncodingAndLocale(request, response);
request = prepare.wrapRequest(request);
ActionMapping mapping = prepare.findActionMapping(request, response);
if (mapping == null) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled)
throw new ServletException("Resource loading not supported, use the StrutsPrepareAndExecuteFilter instead.");
} else {
execute.executeAction(request, response, mapping);
}
} finally {
prepare.cleanupRequest(request);
}
}
// in java/org/apache/struts2/dispatcher/ng/ExecuteOperations.java
public boolean executeStaticResourceRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// there is no action in this request, should we look for a static resource?
String resourcePath = RequestUtils.getServletPath(request);
if ("".equals(resourcePath) && null != request.getPathInfo()) {
resourcePath = request.getPathInfo();
}
StaticContentLoader staticResourceLoader = dispatcher.getContainer().getInstance(StaticContentLoader.class);
if (staticResourceLoader.canHandle(resourcePath)) {
staticResourceLoader.findStaticResource(resourcePath, request, response);
// The framework did its job here
return true;
} else {
// this is a normal request, let it pass through
return false;
}
}
// in java/org/apache/struts2/dispatcher/PlainTextResult.java
protected void sendStream(PrintWriter writer, InputStreamReader reader) throws IOException {
char[] buffer = new char[BUFFER_SIZE];
int charRead;
while((charRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, charRead);
}
}
// in java/org/apache/struts2/dispatcher/ServletRedirectResult.java
protected void sendRedirect(HttpServletResponse response, String finalLocation) throws IOException {
if (SC_FOUND == statusCode) {
response.sendRedirect(finalLocation);
} else {
response.setStatus(statusCode);
response.setHeader("Location", finalLocation);
response.getWriter().write(finalLocation);
response.getWriter().close();
}
}
// in java/org/apache/struts2/dispatcher/FilterDispatcher.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
ServletContext servletContext = getServletContext();
String timerKey = "FilterDispatcher_doFilter: ";
try {
// FIXME: this should be refactored better to not duplicate work with the action invocation
ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
ActionContext ctx = new ActionContext(stack.getContext());
ActionContext.setContext(ctx);
UtilTimerStack.push(timerKey);
request = prepareDispatcherAndWrapRequest(request, response);
ActionMapping mapping;
try {
mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());
} catch (Exception ex) {
log.error("error getting ActionMapping", ex);
dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
return;
}
if (mapping == null) {
// there is no action in this request, should we look for a static resource?
String resourcePath = RequestUtils.getServletPath(request);
if ("".equals(resourcePath) && null != request.getPathInfo()) {
resourcePath = request.getPathInfo();
}
if (staticResourceLoader.canHandle(resourcePath)) {
staticResourceLoader.findStaticResource(resourcePath, request, response);
} else {
// this is a normal request, let it pass through
chain.doFilter(request, response);
}
// The framework did its job here
return;
}
dispatcher.serviceAction(request, response, servletContext, mapping);
} finally {
dispatcher.cleanUpRequest(request);
try {
ActionContextCleanUp.cleanUp(req);
} finally {
UtilTimerStack.pop(timerKey);
}
devModeOverride.remove();
}
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
public void writeTo(OutputStream out) throws IOException {
if (buffers != null) {
for (byte[] bytes : buffers) {
out.write(bytes, 0, blockSize);
}
}
out.write(buffer, 0, index);
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
public void writeTo(RandomAccessFile out) throws IOException {
if (buffers != null) {
for (byte[] bytes : buffers) {
out.write(bytes, 0, blockSize);
}
}
out.write(buffer, 0, index);
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
public void writeTo(Writer out, String encoding) throws IOException {
if (encoding != null) {
CharsetDecoder decoder = getDecoder(encoding);
// Create buffer for characters decoding
CharBuffer charBuffer = CharBuffer.allocate(buffer.length);
// Create buffer for bytes
float bytesPerChar = decoder.charset().newEncoder().maxBytesPerChar();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) (buffer.length + bytesPerChar));
if (buffers != null) {
for (byte[] bytes : buffers) {
decodeAndWriteOut(out, bytes, bytes.length, byteBuffer, charBuffer, decoder, false);
}
}
decodeAndWriteOut(out, buffer, index, byteBuffer, charBuffer, decoder, true);
} else {
if (buffers != null) {
for (byte[] bytes : buffers) {
writeOut(out, bytes, bytes.length);
}
}
writeOut(out, buffer, index);
}
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
public void writeTo(JspWriter out, String encoding) throws IOException {
try {
writeTo((Writer) out, encoding);
} catch (IOException e) {
writeToFile();
throw e;
} catch (Throwable e) {
writeToFile();
throw new RuntimeException(e);
}
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
private void writeOut(Writer out, byte[] bytes, int length) throws IOException {
out.write(new String(bytes, 0, length));
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
private static void decodeAndWriteOut(Writer writer, byte[] bytes, int length, ByteBuffer in, CharBuffer out, CharsetDecoder decoder, boolean endOfInput) throws IOException {
// Append bytes to current buffer
// Previous data maybe partially decoded, this part will appended to previous
in.put(bytes, 0, length);
// To begin of data
in.flip();
decodeAndWriteBuffered(writer, in, out, decoder, endOfInput);
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
private static void decodeAndWriteBuffered(Writer writer, ByteBuffer in, CharBuffer out, CharsetDecoder decoder, boolean endOfInput) throws IOException {
// Decode
CoderResult result;
do {
result = decodeAndWrite(writer, in, out, decoder, endOfInput);
// Check that all data are decoded
if (in.hasRemaining()) {
// Move remaining to top of buffer
in.compact();
if (result.isOverflow() && !result.isError() && !result.isMalformed()) {
// Not all buffer chars decoded, spin it again
// Set to begin
in.flip();
}
} else {
// Clean up buffer
in.clear();
}
} while (in.hasRemaining() && result.isOverflow() && !result.isError() && !result.isMalformed());
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
private static CoderResult decodeAndWrite(Writer writer, ByteBuffer in, CharBuffer out, CharsetDecoder decoder, boolean endOfInput) throws IOException {
CoderResult result = decoder.decode(in, out, endOfInput);
// To begin of decoded data
out.flip();
// Output
writer.write(out.toString());
return result;
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
public void write(int datum) throws IOException {
if (closed) {
throw new IOException("Stream closed");
}
if (index == blockSize) {
addBuffer();
}
buffer[index++] = (byte) datum;
}
// in java/org/apache/struts2/util/FastByteArrayOutputStream.java
public void write(byte data[], int offset, int length) throws IOException {
if (data == null) {
throw new NullPointerException();
}
if (offset < 0 || offset + length > data.length || length < 0) {
throw new IndexOutOfBoundsException();
}
if (closed) {
throw new IOException("Stream closed");
}
if (index + length > blockSize) {
do {
if (index == blockSize) {
addBuffer();
}
int copyLength = blockSize - index;
if (length < copyLength) {
copyLength = length;
}
System.arraycopy(data, offset, buffer, index, copyLength);
offset += copyLength;
index += copyLength;
length -= copyLength;
} while (length > 0);
} else {
System.arraycopy(data, offset, buffer, index, length);
index += length;
}
}
// in java/org/apache/struts2/util/VelocityStrutsUtil.java
public String evaluate(String expression) throws IOException, ResourceNotFoundException, MethodInvocationException, ParseErrorException {
CharArrayWriter writer = new CharArrayWriter();
velocityEngine.evaluate(ctx, writer, "Error parsing " + expression, expression);
return writer.toString();
}
// in java/org/apache/struts2/util/StrutsUtil.java
public PrintWriter getWriter() throws IOException {
return writer;
}