/*** Eclipse Class Decompiler plugin, copyright (c) 2012 Chao Chen (cnfree2000@hotmail.com) ***/
package org.primefaces.application;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.faces.application.ResourceHandler;
import javax.faces.application.ResourceHandlerWrapper;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.StreamedContent;
public class PrimeResourceHandler extends ResourceHandlerWrapper {
private static final Logger logger =
Logger.getLogger(PrimeResourceHandler.class.getName());
private ResourceHandler wrapped;
public PrimeResourceHandler(ResourceHandler wrapped) {
this.wrapped = wrapped;
}
public ResourceHandler getWrapped() {
return this.wrapped;
}
public void handleResourceRequest(FacesContext context) throws IOException {
Map params = context.getExternalContext().getRequestParameterMap();
String library = (String) params.get("ln");
String dynamicContentId = (String) params.get("pfdrid");
if ((dynamicContentId != null)
&& (library != null)
&& (library.equals("primefaces"))) {
Map session = context.getExternalContext().getSessionMap();
StreamedContent streamedContent = null;
try {
String dynamicContentEL = (String) session.get(dynamicContentId);
ExternalContext externalContext = context.getExternalContext();
if (dynamicContentEL != null) {
ELContext eLContext = context.getELContext();
ValueExpression ve =
context.getApplication()
.getExpressionFactory()
.createValueExpression(context.getELContext(), dynamicContentEL, StreamedContent.class);
streamedContent = (StreamedContent) ve.getValue(eLContext);
externalContext.setResponseStatus(200);
externalContext.setResponseContentType(streamedContent.getContentType());
if (streamedContent.getContentEncoding() != null) {
externalContext.setResponseHeader("Content-Encoding", streamedContent.getContentEncoding());
}
byte[] buffer = new byte[2048];
InputStream inputStream = streamedContent.getStream();
int length = 0;
while ((length = inputStream.read(buffer)) >= 0) {
externalContext.getResponseOutputStream().write(buffer, 0, length);
}
}
externalContext.responseFlushBuffer();
context.responseComplete();
} catch (Exception e) {
logger.log(Level.SEVERE, "Error in streaming dynamic resource. {0}", new Object[] { e.getMessage() });
e.printStackTrace();
} finally {
session.remove(dynamicContentId);
if (streamedContent != null)
streamedContent.getStream().close();
}
} else {
super.handleResourceRequest(context);
}
}
}