package com.icefaces.support.example; import com.icesoft.faces.context.Resource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.Date; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; public class TableItem { private String fileName; private String mimeType; private Resource resource; public static final String RESOURCE_PATH = "/resources/"; public TableItem(String fileName, String mimeType) { try { this.fileName = fileName; this.mimeType = mimeType; FacesContext fc = FacesContext.getCurrentInstance(); ExternalContext ec = fc.getExternalContext(); this.resource = new MyResource(ec, fileName); } catch (Exception e) { e.printStackTrace(); } } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; } public static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int len = 0; while ((len = input.read(buf)) > -1) { output.write(buf, 0, len); } return output.toByteArray(); } } class MyResource implements Resource, Serializable { private String resourceName; private InputStream inputStream; private final Date lastModified; private ExternalContext extContext; public MyResource(ExternalContext ec, String resourceName) { this.extContext = ec; this.resourceName = resourceName; this.lastModified = new Date(); } /** * This intermediate step of reading in the files from the JAR, into a * byte array, and then serving the Resource from the ByteArrayInputStream, * is not strictly necessary, but serves to illustrate that the Resource * content need not come from an actual file, but can come from any source, * and also be dynamically generated. In most cases, applications need not * provide their own concrete implementations of Resource, but can instead * simply make use of com.icesoft.faces.context.ByteArrayResource, * com.icesoft.faces.context.FileResource, com.icesoft.faces.context.JarResource. */ public InputStream open() throws IOException { if (inputStream == null) { InputStream stream = extContext.getResourceAsStream(TableItem.RESOURCE_PATH + resourceName); byte[] byteArray = TableItem.toByteArray(stream); inputStream = new ByteArrayInputStream(byteArray); } return inputStream; } public String calculateDigest() { return resourceName; } public Date lastModified() { return lastModified; } public void withOptions(Options arg0) throws IOException { } }