Saturday, January 31, 2015

ADF: Upload/Download File

Recently when I need to upload/download documents using BLOB data type and allow only few document types to upload. I followed below steps to achieve in ADF.

JSF:

    <af:decorativeBox id="db1" styleClass="AFStretchWidth" theme="light"
                      topHeight="150px" inlineStyle="width:1100px"
                      dimensionsFrom="children">
      <f:facet name="top">
        <af:panelBox id="pb2" showDisclosure="false"
                     text="Upload File Here:"
                     rendered="#{pageFlowScope.Mode eq 'Edit'}">
          <af:panelFormLayout id="pfl1">
            <f:facet name="footer">
              <af:panelGroupLayout id="gh1">
                <af:commandButton text="Upload" id="cb3" partialSubmit="true"
                                  disabled="#{pageFlowScope.miscBean.miscInputFile.value eq null ? true : false}"
                                  actionListener="#{pageFlowScope.miscBean.uploadListener}"
                                  partialTriggers="if1"/>
                <af:spacer width="10" height="10" id="s52"/>
                <af:commandButton text="Reset" id="cb5" immediate="true"
                                  partialSubmit="true"
                                  disabled="#{pageFlowScope.miscBean.miscInputFile.value eq null ? true : false}"
                                  actionListener="#{pageFlowScope.miscBean.resetListener}"
                                  partialTriggers="if1"/>
              </af:panelGroupLayout>
            </f:facet>
            <af:spacer width="10" height="10" id="shi2"/>
            <af:inputFile label="Select File to Upload" id="if1"
                          autoSubmit="true"
                          binding="#{pageFlowScope.miscBean.miscInputFile}"
                          valueChangeListener="#{pageFlowScope.miscBean.fileInputChangeListener}"
                          partialTriggers="cb3 cb5"/>
            <af:spacer width="10" height="10" id="s2"/>
          </af:panelFormLayout>
        </af:panelBox>
      </f:facet>
      <f:facet name="center">
        <af:panelGroupLayout layout="vertical" id="pgl1">
          <af:spacer width="10" height="10" id="s3"/>
          <af:outputText value="Existing Files:" id="ot1"
                         inlineStyle="font-weight:bold;"/>
          <af:spacer width="10" height="10" id="s37"/>
          <af:panelCollection id="pc1" styleClass="AFStretchWidth">
            <af:table value="#{bindings.UploadedFilesVO1.collectionModel}"
                      var="row" rows="#{bindings.UploadedFilesVO1.rangeSize}"
                      rowBandingInterval="1" autoHeightRows="15"
                      selectedRowKeys="#{bindings.UploadedFilesVO1.collectionModel.selectedRow}"
                      selectionListener="#{bindings.UploadedFilesVO1.collectionModel.makeCurrent}"
                      rowSelection="single" id="t1" styleClass="AFStretchWidth" partialTriggers=":::cb3 d51">
              <af:column sortProperty="#{bindings.UploadedFilesVO1.hints.FileName.name}"
                         sortable="true" width="340"
                         headerText="#{bindings.UploadedFilesVO1.hints.FileName.label}"
                         id="c2">
                <!--<af:outputText value="#{row.FileName}" id="ot4"/> -->
                <af:commandLink text="#{row.FileName}" id="cl1">
                  <af:fileDownloadActionListener contentType="#{row.MimeType}"
                                                 filename="#{row.FileName}"
                                                 method="#{pageFlowScope.miscBean.downloadFile}"/>
                </af:commandLink>
              </af:column>
            </af:table>
          </af:panelCollection>
        </af:panelGroupLayout>
      </f:facet>
    </af:decorativeBox>


Bean Method:

    import org.apache.commons.io.IOUtils;
    import org.apache.myfaces.trinidad.model.UploadedFile;

    private String fileName;
    private String contentType;
    private UploadedFile uploadedFile;
    private BlobDomain fileContent;
    private RichInputFile miscInputFile;

    public void fileInputChangeListener(ValueChangeEvent valueChangeEvent) {
        // Add event code here...
        uploadedFile = (UploadedFile)valueChangeEvent.getNewValue();
        // Get the file name
        fileName = uploadedFile.getFilename();
        // get the mime type
        contentType = uploadedFile.getContentType();
        // get blob
        fileContent = getBlob(uploadedFile);
    }

    public BlobDomain getBlob(UploadedFile file) {
        InputStream in = null;
        BlobDomain blobDomain = null;
        OutputStream out = null;
        try {
            in = file.getInputStream();
            blobDomain = new BlobDomain();
            out = blobDomain.getBinaryOutputStream();
            IOUtils.copy(in, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.fillInStackTrace();
        }
        return blobDomain;
    }

    public void showMessage(String message, String severity) {
        FacesMessage fm = new FacesMessage(message);
        if (severity == "INFO") {
            fm.setSeverity(FacesMessage.SEVERITY_INFO);
        } else if (severity == "FATAL") {
            fm.setSeverity(FacesMessage.SEVERITY_FATAL);
        } else if (severity == "ERROR") {
            fm.setSeverity(FacesMessage.SEVERITY_ERROR);
        } else if (severity == "WARN") {
            fm.setSeverity(FacesMessage.SEVERITY_WARN);
        }
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, fm);
    }

    public void uploadListener(ActionEvent actionEvent) {
        // Add event code here...

        if (validateFileExt(fileName)) {

            BindingContext bctx = BindingContext.getCurrent();
            BindingContainer bindings = bctx.getCurrentBindingsEntry();
            OperationBinding operationBinding =
                bindings.getOperationBinding("uploadFile");

            String status = null;

            if (operationBinding != null) {
                operationBinding.getParamsMap().put("pFileName", fileName);
                operationBinding.getParamsMap().put("pFileContent",
                                                    fileContent);
                operationBinding.getParamsMap().put("pContentType",
                                                    contentType);
                status = (String)operationBinding.execute();
            }

            if (!operationBinding.getErrors().isEmpty()) {
                //check errors
                List errors = operationBinding.getErrors();
            }

            showMessage(status, "INFO");

            System.out.println("File " + fileName + " uploaded successfully");

        } else {

            String warning =
                "Please only upload files that end in types: .txt .doc .rtf .pdf .jpeg .jpg .bmp .docx .gif .html .htm .png .xls .ppt .xml .xlsx .pptx .sql .sh .pl .lst .zip .tar .ods .odt .xlsm. Please select a new file to upload and submit again.";
            showMessage(warning, "WARN");
        }

        if (null != miscInputFile) {
            miscInputFile.resetValue();
            miscInputFile.setValid(true);
        }
    }

    public Boolean validateFileExt(String fileName) {
        if (fileName.endsWith(".txt") || fileName.endsWith(".doc") ||
            fileName.endsWith(".rtf") || fileName.endsWith(".pdf") ||
            fileName.endsWith(".jpeg") || fileName.endsWith(".jpg") ||
            fileName.endsWith(".bmp") || fileName.endsWith(".docx") ||
            fileName.endsWith(".gif") || fileName.endsWith(".html") ||
            fileName.endsWith(".htm") || fileName.endsWith(".png") ||
            fileName.endsWith(".xls") || fileName.endsWith(".ppt") ||
            fileName.endsWith(".xml") || fileName.endsWith(".xlsx") ||
            fileName.endsWith(".pptx") || fileName.endsWith(".sql") ||
            fileName.endsWith(".sh") || fileName.endsWith(".pl") ||
            fileName.endsWith(".lst") || fileName.endsWith(".zip") ||
            fileName.endsWith(".tar") || fileName.endsWith(".ods") ||
            fileName.endsWith(".odt") || fileName.endsWith(".xlsm")) {
            return true;
        }
        return false;

    }

    public void downloadFile(FacesContext facesContext,
                             OutputStream outputStream) {
        DCBindingContainer bindings =
            (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        DCIteratorBinding iteratorbinding =
            bindings.findIteratorBinding("UploadedFilesVO1Iterator");
        Row row = iteratorbinding.getCurrentRow();
        System.out.println("Selected: " + row.getAttribute("FileName"));
        BlobDomain blob = (BlobDomain)row.getAttribute("FileContent");
        try {
            IOUtils.copy(blob.getInputStream(), outputStream);
            blob.closeInputStream();
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setMiscInputFile(RichInputFile miscInputFile ) {
        this.miscInputFile = miscInputFile ;
    }

    public RichInputFile getMiscInputFile() {
        return miscInputFile;
    }

    public void resetListener(ActionEvent actionEvent) {
        if (null != miscInputFile) {
            miscInputFile.resetValue();
            miscInputFile.setValid(true);
        }
    }


AM Method:

    public String uploadFile(String pFileName, BlobDomain pFileContent, String pContentType) {

        ViewObjectImpl vo = getUploadedFilesVO1();
        Row row = vo.createRow();

        row.setAttribute("FileContent", pFileContent);
        row.setAttribute("FileName", pFileName);
        row.setAttribute("MimeType", pContentType);

        vo.insertRow(row);
        vo.executeQuery();

        this.getDBTransaction().commit();

        return "File " + pFileName + " Uploaded Successfully";
    }