! . . Album Hình . . !

Tìm kiếm Những Gì Bạn Thích !

3 tháng 11, 2013

Upload, Download in Liferay JSF


  • File resource_handler
public class App3ResourceHandler extends ResourceHandlerWrapper {
        public static final String LIBRARY_NAME_BCTHSD = "THSD";
public static final String FileDownload = "Download";
// Logger
private static final Logger logger = LoggerFactory
.getLogger(App3ResourceHandler.class);

// Private Data Members
private ResourceHandler wrappedResourceHandler;

public App3ResourceHandler(ResourceHandler wrappedResourceHandler) {
this.wrappedResourceHandler = wrappedResourceHandler;
}

@Override
public Resource createResource(String resourceName, String libraryName) {

if (libraryName.equals(LIBRARY_NAME_BCD)) {
if (BaoCaoDongExel.RESOURCE_NAME.equals(resourceName)) {
try {
BaoCaoDongBean baocaoSLTSTGBHBean = (BaoCaoDongBean) FacesContext
.getCurrentInstance().getExternalContext()
.getSessionMap().get("baocaodongbean");
Resource re = baocaoSLTSTGBHBean.getExport();
return re;
} catch (Exception e) { //
// TODO: handle exception return
wrappedResourceHandler.createResource(resourceName,
libraryName);
}
} else {
return wrappedResourceHandler.createResource(resourceName,
libraryName);
}
} else if (libraryName.equals(LIBRARY_NAME_BCTHSD)) {
if (BCTHSD_Export_Resource.RESOURCE_NAME.equals(resourceName)) {
try {
BaoCaoTinhHinhSuDungBean baocaoTHSDBean = (BaoCaoTinhHinhSuDungBean) FacesContext
.getCurrentInstance().getExternalContext()
.getSessionMap().get("baoCaoTinhHinhSuDungBean");
Resource re = baocaoTHSDBean.getExport();
return re;
} catch (Exception e) { //
// TODO: handle exception return
wrappedResourceHandler.createResource(resourceName,
libraryName);
}
} else {
return wrappedResourceHandler.createResource(resourceName,
libraryName);
}
}
return wrappedResourceHandler.createResource(resourceName, libraryName);
}
@Override
public void handleResourceRequest(FacesContext facesContext)
throws IOException {

ExternalContext externalContext = facesContext.getExternalContext();
String libraryName = externalContext.getRequestParameterMap().get("ln");
String resourceName = externalContext.getRequestParameterMap().get(
"javax.faces.resource");

String folderName = externalContext.getRequestParameterMap().get("BC1");

Resource resource = createResource(resourceName, libraryName);

ReadableByteChannel readableByteChannel = null;

WritableByteChannel writableByteChannel = null;
InputStream inputStream = null;
int bufferSize = 1024;
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
try {
// Open an input stream in order to read the resource's
// contents/data.
if (libraryName.equalsIgnoreCase(FileDownload)) {
String path = FacesContext.getCurrentInstance()
.getExternalContext().getRealPath("");

if (folderName.equalsIgnoreCase("none")) {
path = path + File.separator + resourceName;
} else {
path = path + File.separator + folderName + File.separator
+ resourceName;
}

try {
File file = new File(path);
inputStream = new FileInputStream(file);
} catch (IOException e) {
// TODO: handle exception
System.out
.println("Rat tiec toi khong tim thay file ban can!");
}

} else {
inputStream = resource.getInputStream();
}

if (inputStream != null) {

// Set the response buffer size.
int responseBufferSize = byteBuffer.capacity();
externalContext.setResponseBufferSize(responseBufferSize);

String responseContentType = resource.getContentType();
externalContext.addResponseHeader("Content-Disposition",
"attachment; filename=" + resourceName);

if (responseContentType != null) {
externalContext.setResponseContentType(responseContentType);
}

// Copy the bytes in the resource's input stream to the
// response's output stream.
int responseContentLength = 0;
readableByteChannel = Channels.newChannel(inputStream);
writableByteChannel = Channels.newChannel(externalContext
.getResponseOutputStream());

int bytesRead = readableByteChannel.read(byteBuffer);
int bytesWritten = 0;

while (bytesRead != -1) {
byteBuffer.rewind();
byteBuffer.limit(bytesRead);

do {
bytesWritten += writableByteChannel.write(byteBuffer);
} while (bytesWritten < responseContentLength);

byteBuffer.clear();
responseContentLength += bytesRead;
bytesRead = readableByteChannel.read(byteBuffer);

if (logger.isTraceEnabled()) {

// Surround with isTraceEnabled check in order to avoid
// unnecessary conversion
// of int to String.
logger.trace("Handling - MORE bytesRead=[{0}]",
Integer.toString(bytesRead));
}
}

// Now that we know how big the file is, set the response
// content length.
externalContext.setResponseContentLength(responseContentLength);
externalContext.setResponseStatus(HttpServletResponse.SC_OK);

logger.debug(
"HANDLED (SC_OK) resourceName=[{0}], libraryName[{1}], responseContentType=[{2}], responseContentLength=[{3}]",
new Object[] { resourceName, libraryName,
responseContentType, responseContentLength });
}
} catch (IOException e) {
externalContext.setResponseStatus(HttpServletResponse.SC_NOT_FOUND);
logger.error(
"NOT HANDLED (SC_NOT_FOUND) resourceName=[{0}], libraryName[{1}], errorMessage=[{2}]",
new Object[] { resourceName, libraryName, e.getMessage() },
e);
} finally {

if (writableByteChannel != null) {
writableByteChannel.close();
}

if (readableByteChannel != null) {
readableByteChannel.close();
}

if (inputStream != null) {
inputStream.close();
}
}
}

@Override
public boolean libraryExists(String libraryName) {

if (LIBRARY_NAME.equals(libraryName)) {
return true;
} else {
return super.libraryExists(libraryName);
}
}

@Override
public ResourceHandler getWrapped() {
return wrappedResourceHandler;
}
}
  • File resource
public class BaoCaoDongExel extends Resource {
public static final String CONTENT_TYPE = "application/vnd.ms-excel";
public static final String RESOURCE_NAME = "BaoCao.xls";
 private String requestPath;
public BaoCaoDongExel() {
setLibraryName(App3ResourceHandler.LIBRARY_NAME_BCD);
setResourceName(RESOURCE_NAME);
setContentType(CONTENT_TYPE);
if (!Validator.isNull(listData)) {
this.listData.clear();
}
}
@Override
public InputStream getInputStream() throws IOException {
byte[] excel = new byte[] {};
try {
// code tạo file xuất ra ở đây

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
wb.write(byteArrayOutputStream);
excel = byteArrayOutputStream.toByteArray();

} catch (Exception e2) {
System.out.println("co loi trong " + getClass().getName() + "\n"
+ e2);
}

return new ByteArrayInputStream(excel);
}


@Override
public String getRequestPath() {
if (requestPath == null) {
StringBuilder buf = new StringBuilder();
buf.append(ResourceHandler.RESOURCE_IDENTIFIER);
buf.append("/");
buf.append(getResourceName());
buf.append("?ln=");
buf.append(getLibraryName());
buf.append("&");
buf.append("BC1");// chua hieu
buf.append("=");
buf.append(Math.random());
requestPath = buf.toString();
}

return requestPath;
}

@Override
public Map getResponseHeaders() {
// TODO Auto-generated method stub
return null;
}

@Override
public URL getURL() {
// TODO Auto-generated method stub
return null;
}

@Override
public boolean userAgentNeedsUpdate(FacesContext arg0) {
// TODO Auto-generated method stub
return false;
}

}
  • File bean
Lưu ý là sessionscope
private BaoCaoDongExel export;

public BaoCaoDongExel getExport() {
export = new BaoCaoDongExel(các tham số truyền qua tương ứng);
return export;
}

public void setExport(BaoCaoDongExel export) {
this.export = export;
}
-  Download Bean
@ManagedBean (name="downloadBean")
public class DownloadBean {
public String getLink(String folder, String fileName) {
String link1 = null;
if (link1 == null) {
StringBuilder buf = new StringBuilder();
buf.append(ResourceHandler.RESOURCE_IDENTIFIER);
buf.append("/");
buf.append(fileName);
buf.append("?ln=");
buf.append(App3ResourceHandler.FileDownload);
buf.append("&");
buf.append("BC1");
buf.append("=");
buf.append(folder);
link1 = buf.toString();
}

return link1;
}
}
  • File view
- Nếu file đã có sẳn thì down theo đường dẫn nó.
style="display:#{tailieu.existFile=='TRUE'?'block':'none'}"
value="#{downloadBean.getLink(customUtils.GetFolderUpload(),tailieu.tenFileLuu)}">

Không có nhận xét nào:

Hướng dẫn đăng nhận xét của bạn

  • Nếu muốn đăng nhận xét của mình các bạn click vào "Xem và nhận xét ở đây" dưới mỗi bài đăng, sau đó hộp thoại xuất hiện bạn gõ vào những nhận xét của mình. thế là xong! cảm ơn các bạn đã ghé thăm blog của mình !