Friday, August 26, 2016

File Upload to Unix Server (OAF Controller Code)

import com.sun.java.util.collections.ArrayList;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;

import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import oracle.apps.fnd.common.MessageToken;
import oracle.apps.fnd.common.VersionInfo;
import oracle.apps.fnd.framework.OAApplicationModule;
import oracle.apps.fnd.framework.OAException;
import oracle.apps.fnd.framework.webui.OAControllerImpl;
import oracle.apps.fnd.framework.webui.OADialogPage;
import oracle.apps.fnd.framework.webui.OAPageContext;
import oracle.apps.fnd.framework.webui.OAWebBeanConstants;
import oracle.apps.fnd.framework.webui.beans.OAWebBean;
import oracle.apps.fnd.framework.webui.beans.message.OAMessageChoiceBean;
import oracle.apps.fnd.framework.webui.beans.message.OAMessageLovInputBean;
import oracle.apps.fnd.framework.webui.beans.message.OAMessageTextInputBean;
import oracle.apps.xx.server.pathListVOImpl;
import oracle.apps.xx.server.pathListVORowImpl;

import oracle.cabo.ui.data.DataObject;

import oracle.jbo.Row;
import oracle.jbo.domain.BlobDomain;

/**
 * Controller for ...
 */
public class xxFileUploadCO6 extends OAControllerImpl
{
  public static final String RCS_ID="$Header$";
  public static final boolean RCS_ID_RECORDED =
        VersionInfo.recordClassVersion(RCS_ID, "%packagename%");
  String path = "";
  /**
   * Layout and page setup logic for a region.
   * @param pageContext the current OA page context
   * @param webBean the web bean corresponding to the region
   */
 
  public void processRequest(OAPageContext pageContext, OAWebBean oawebbean)
  {
    super.processRequest(pageContext, oawebbean);
    System.out.println(" --  Start PR xxFileUploadCO  -- ");
    OAApplicationModule am =(OAApplicationModule) pageContext.getApplicationModule(oawebbean);
    if (!pageContext.isFormSubmission())
       am.invokeMethod("createRecord");
     
//       // Test
//      
//        OAMessageChoiceBean k = (OAMessageChoiceBean)oawebbean.findIndexedChildRecursive("choiceList");
//        k.setListVOBoundContainerColumn(0, tableBean,"DepColvalue1");
//        k.setListVOBoundContainerColumn(1, tableBean,"DepColvalue2");
//        k.setPickListCacheEnabled(false);                 //  "DepColvalue1","DepColvalue2" are the Item ID in the page Structure and the choice list query execute based on these values for each row in Table Region Dynamically.
//      
//       // end test
  }

  /**
   * Procedure to handle form submissions for form elements in
   * a region.
   * @param pageContext the current OA page context
   * @param webBean the web bean corresponding to the region
   */
   ArrayList Msgs= new ArrayList();
  public void processFormRequest(OAPageContext pageContext, OAWebBean webBean)
  {
    super.processFormRequest(pageContext, webBean);
    System.out.println(" --  Start PFR xxFileUploadCO  -- ");
    OAApplicationModule am =(OAApplicationModule) pageContext.getApplicationModule(webBean);
   
    if (pageContext.isLovEvent())
    {
      String lovInputSourceId = pageContext.getLovInputSourceId();
      if("Entity_name".equals(lovInputSourceId))
      {
        OAMessageLovInputBean lovBean=(OAMessageLovInputBean)webBean.findIndexedChildRecursive(lovInputSourceId);
        if(lovBean != null)
        {
          String lovInput  =  (String) lovBean.getValue(pageContext);
          System.out.println("--lovInput --"+lovInput);
        }
      }
      String v_path = pageContext.getParameter("PathToUpload");
      System.out.println("--value v_path --"+v_path);
      Serializable [] param = {v_path};
      path = v_path;
      am.invokeMethod("exeVO",param);
    }
   
   
   
   
     if (pageContext.getParameter("Upload") != null)
    {
      if(path == null || path.equals(""))
      {
        throw new OAException("Please Select Valid Path..", OAException.ERROR);
      }
      validatUploadFileExtn(pageContext, webBean);
      ValiadteFileUploadExists(pageContext, webBean,path);
    }
       if (pageContext.getParameter("WarningYesButton") != null)
       {
         upLoadFile_FromInstance(pageContext, webBean, path);
         //upLoadFile_FromLocalMachine(pageContext, webBean);
       }
       if(pageContext.getParameter("search")!= null)
       {
         ValidatePopulateFileToSearch(pageContext, webBean);
       }
     
       if(pageContext.getParameter(EVENT_PARAM).equals("FileDownloadfromServer"))
       {
         String rowRef = (String)pageContext.getParameter(OAWebBeanConstants.EVENT_SOURCE_ROW_REFERENCE);
         pathListVORowImpl lineRow = (pathListVORowImpl)am.findRowByRef(rowRef);
         if(lineRow != null)
         {
            System.out.println("Path to Download File-->"+lineRow.getpath());
            String file_name_with_path = lineRow.getpath();
            downloadFileFromServer(pageContext, file_name_with_path,webBean) ;
         }
       }
       if (pageContext.getParameter("archievdddde") != null)
       {
         Msgs.clear();
         pathListVOImpl vo = (pathListVOImpl) am.findViewObject("pathListVO1");
         Row Vorow = null;
         Row[] rows = vo.getFilteredRows("SelectFlag", "Y");
         if(rows.length > 0)
         {
           String ConfirmationMsg = "All Files Moved Successfully..";
           for (int i = 0; i < rows.length; i++)
           {
             Vorow = rows[i];
             System.out.println(" --> " + Vorow.getAttribute("path"));
             String CurrentPath = Vorow.getAttribute("path").toString();
             archieveFiles(pageContext,webBean, CurrentPath);
           }

           if(Msgs.size() > 0 )
            OAException.raiseBundledOAException(Msgs);
           else
             throw new OAException(ConfirmationMsg,OAException.CONFIRMATION );
         }
       
         if(rows.length == 0)
         {
           throw new OAException("No files Selcted to Archieve..");
         }
       }
  }
 
  public void archieveFiles(OAPageContext pageContext,OAWebBean webBean, String CurrentPath)
  {
     FileValidations(CurrentPath);
     String archiedPath = "/tmp/guruswamy";
     File afile = new File(CurrentPath);
     String RenamePath = archiedPath + afile.separator + "archive";
     FileValidations(RenamePath);
     String fname = RenamePath + afile.separator + afile.getName();
     if (afile.renameTo(new File(fname)))
     {
       System.out.println("File Moved");
       //Msgs.add(new OAException((String)("File moved successfully to path : " + RenamePath)));
     }
     else
     {
       Msgs.add(new OAException((String)("Unable to Move file : " + fname)));
     }
   }
 
  public void FileValidations(String fileName)
  {
   /* {
      throw new OAException("File path is invalid." + fileName);
      MessageToken[] token = {new MessageToken("USER", getOADBTransaction().getUserName()),new MessageToken("NUM",hMember.getChildNumber())};
      errorMsg.add(new OAException((String)(getOADBTransaction().getMessage("XXCH","XXCH_NO_ACCESS",token))));
      Msgs.add(new OAException((String)("File path is invalid.. "+fileName)));
    }  */
    if (((fileName == null) || ("".equals(fileName))))
    {
      Msgs.add(new OAException((String)("File Path Should not be null : " + fileName)));
    }
    else
    {
      File fileToDownload = new File(fileName);
      if (!fileToDownload.exists())
      {
        Msgs.add(new OAException((String)("File Path does not exist :" + fileName)));
      }
      if (!fileToDownload.canRead() && fileToDownload.exists() )
      {
         Msgs.add(new OAException((String)("Not Able to read the file Path :" + fileName)));
      }
    }
  }
 
  public void downloadFileFromServer(OAPageContext pageContext, String file_name_with_path,OAWebBean webBean)
  {
    HttpServletResponse response = (HttpServletResponse) pageContext.getRenderingContext().getServletResponse();
    if (((file_name_with_path == null) || ("".equals(file_name_with_path))))
    {
      throw new OAException("File path is invalid.");
    }
    File fileToDownload = null;
    try
    {
      fileToDownload = new File(file_name_with_path);
    }
    catch (Exception e)
    {
      throw new OAException("Invalid File Path or file does not exist.");
    }
    if (!fileToDownload.exists())
    {
      throw new OAException("File does not exist.");
    }

    if (!fileToDownload.canRead())
    {
      throw new OAException("Not Able to read the file.");
    }
   
    System.out.println(" file_name_with_path -->"+file_name_with_path);
    String file_name_with_ext_toSave = fileToDownload.getName();
   
    System.out.println(" File to save download File -->"+file_name_with_ext_toSave);
   
    String fileType = "application/pdf"; //getMimeType(file_name_with_ext_toSave);
    response.setContentType(fileType);
    response.setContentLength((int) fileToDownload.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file_name_with_ext_toSave + "\"");

    InputStream in = null;
    ServletOutputStream outs = null;

    try
    {
      outs = response.getOutputStream();
      in = new BufferedInputStream(new FileInputStream(fileToDownload));
      int ch;
      while ((ch = in.read()) != -1)
      {
        outs.write(ch);
      }
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    finally
    {
      try
      {
        outs.flush();
        outs.close();
        if (in != null)
        {
          in.close();
        }
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }
  }
 
  public void validatUploadFileExtn(OAPageContext pageContext, OAWebBean webBean)
  {
    String uFileName = null;
    try
    {
      DataObject fileUploadData = pageContext.getNamedDataObject("MsgFileUpload");
      uFileName = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");
    }
    catch (Exception ex)
    {
      throw new OAException(ex.getMessage(), OAException.ERROR);
    }
    if(uFileName != null )
    {
      String FileExtn = null;
      if(uFileName.lastIndexOf(".") != -1 && uFileName.lastIndexOf(".") != 0)
       FileExtn  = uFileName.substring(uFileName.lastIndexOf(".")+1);
      System.out.println("File Extention --> "+FileExtn);
      System.out.println("profile value for FileEXtnetion  : "+pageContext.getProfile("XX_FILE_UPLOAD_TYPE_PF"));
     
      if(pageContext.getProfile("XX_FILE_UPLOAD_TYPE_PF") == null
                  || pageContext.getProfile("XX_FILE_UPLOAD_TYPE_PF").equals(""))
      {
        throw new OAException("Please Select Profile Value for File Extention ", OAException.ERROR);
      }
     
      String fe = pageContext.getProfile("XX_FILE_UPLOAD_TYPE_PF");
      String[] okFileExtensions = fe.split(",");
      int cnt = 0;
      for(int i= 0 ; i< okFileExtensions.length; i++)
      {
        if(okFileExtensions[i].replace("\"","").toLowerCase().equals(FileExtn.toLowerCase()))
        {
          cnt = cnt + 1;
        }
      }
      if(cnt == 0)
      {
        throw new OAException("Please select File Type as : { "+ fe + " }", OAException.ERROR);
      }
    }
   
  }
 
  public void ValidatePopulateFileToSearch(OAPageContext pageContext, OAWebBean webBean)
  {
    OAApplicationModule am =(OAApplicationModule) pageContext.getApplicationModule(webBean);
    OAMessageTextInputBean m = (OAMessageTextInputBean )webBean.findChildRecursive("FileToSearch");
    Object FileToSearch_k = m.getValue(pageContext);
 
    if( FileToSearch_k  == null || FileToSearch_k.equals(""))
    {
      throw new OAException("Enter Valid value for \"Exact File Path to Find \" ",OAException.ERROR);
    }
    String FileToSearch = FileToSearch_k.toString();
    System.out.println(" File to Search value -->"+FileToSearch);
    am.invokeMethod("deleteRows");
   
    if(FileToSearch == null || FileToSearch.equals(""))
    {
      throw new OAException ("Path Should not be null",OAException.ERROR);
    }
   
    File paramFile = new File(FileToSearch);
   
    if(!paramFile.exists())
    {
      MessageToken[] arrayOfMessageToken = { new MessageToken("PATH", FileToSearch, false) };
      throw new OAException(pageContext.getMessage("FND", "PERZ_INVALID_DOC_PATH", arrayOfMessageToken), OAException.ERROR);
    }
   
    try
     {
       ArrayList paramArrayList = new ArrayList();
       ArrayList lastModifyDateArrayList = new ArrayList();
       populateFilesToArrayList(paramArrayList, paramFile,lastModifyDateArrayList);
       for (int i = 0; i<paramArrayList.size();i++ )
       {
         Serializable parameters[]  = {paramArrayList.get(i).toString(),lastModifyDateArrayList.get(i).toString()};
         Class paramTypes[] = {String.class, String.class};
         am.invokeMethod("setPath",parameters,paramTypes);
       }
     }
     catch (OAException localOAException)
     {
        System.out.println("inside localOAException "+localOAException);
     }
  }
 
 
  public void ValiadteFileUploadExists(OAPageContext pageContext, OAWebBean webBean,String path)
  {
      String uFileName = "";
      if(path == null || path.equals(""))
      {
        throw new OAException("Please Select value for \"Unix Path\" to Upload ..", OAException.ERROR);
      }
      DataObject fileUploadData = pageContext.getNamedDataObject("MsgFileUpload");
      if (fileUploadData != null)
      {
        uFileName = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");
      }
      File UploadingFileFullPath = new File(path + File.separator + uFileName);
      if(UploadingFileFullPath.exists())
      {
        dialoguePage(pageContext, webBean);
      }
      else
      {
        //upLoadFile_FromLocalMachine(pageContext, webBean);
        upLoadFile_FromInstance(pageContext, webBean, path);
      }
     
  }
 
 
  public void dialoguePage(OAPageContext oapageContext, OAWebBean oawebBean)
    {
      OADialogPage dialoguepage = null;
      //OAException mainmsg = new OAException("CF","XX_TEST");
      OAException mainmsg =
        new OAException("The Files Already Exist in path.. Do You want to Overwrite it..");
      dialoguepage = new OADialogPage(OAException.WARNING, mainmsg, null, "", "");
      dialoguepage.setOkButtonItemName("WarningYesButton");
      dialoguepage.setOkButtonToPost(true);
      dialoguepage.setNoButtonToPost(true);
      dialoguepage.setPostToCallingPage(true);
      dialoguepage.setOkButtonLabel("Yes");
      dialoguepage.setNoButtonLabel("No");
      dialoguepage.setPageTitle("File Alreay Exists Warning..");
      oapageContext.redirectToDialogPage(dialoguepage);
    }
   
   
  private static void populateFilesToArrayList(ArrayList paramArrayList, File paramFile,ArrayList lastModifyDateArrayList)
  {
    String[] arrayOfString = paramFile.list();
    if (arrayOfString == null)
    {
      File localFile = new File(paramFile.getAbsolutePath());
      if(localFile.isFile())
      {
        paramArrayList.add(localFile);
        Date k = new Date(localFile.lastModified());
        lastModifyDateArrayList.add(k);
      }
    }
    if(arrayOfString != null)
    {
      for (int i = 0; i < arrayOfString.length; i++)
      {
        File localFile = new File(paramFile.getAbsolutePath() + File.separator + arrayOfString[i]);
        if (localFile.isDirectory())
        {
          populateFilesToArrayList(paramArrayList, localFile,lastModifyDateArrayList);
        }
        if(localFile.isFile())
        {
          paramArrayList.add(localFile);
          Date k = new Date(localFile.lastModified());
          lastModifyDateArrayList.add(k);
        }
      }
    }
  }
 

  // CODE #1 -- If Page has not deployed at instance, testing at Local Machine, use following Code


  public void upLoadFile_FromLocalMachine(OAPageContext pageContext, OAWebBean webBean)
  {
    String filePath = "D:\\PRajkumar";
    String status = "N";
    File file = null;
    String fileUrl = null;
    try
    {
      DataObject fileUploadData = pageContext.getNamedDataObject("MsgFileUpload");
      //FileUploading is my MessageFileUpload Bean Id
      if (fileUploadData != null)
      {
        String uFileName = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");
        String contentType = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");
        FileOutputStream output = null;
        InputStream input = null;

        BlobDomain uploadedByteStream = (BlobDomain) fileUploadData.selectValue(null, uFileName);
        file = new File("D:\\PRajkumar", uFileName);
        output = new FileOutputStream(file);
        input = uploadedByteStream.getInputStream();
        byte abyte0[] = new byte[0x19000];
        int i;
        while ((i = input.read(abyte0)) > 0)
          output.write(abyte0, 0, i);
        output.close();
        input.close();
        status = "Y";
      }
    }
    catch (Exception ex)
    {
      throw new OAException(ex.getMessage(), OAException.ERROR);
    }
    if( status.equals("Y"))
    {
      throw new OAException("File Uploaded Successfully to Path : "+file, OAException.CONFIRMATION);
    }
  }


  // CODE #2 -- If Page has been Deployed at Instance, Use Following Code


  public void methodChangeFilePermissions(File fileUrl)
  {
    try
    {
      String[] command = { "/bin/chmod", "777", fileUrl.getAbsolutePath(), };
      Runtime rt = Runtime.getRuntime();

      Process proc = rt.exec(command);
      InputStream stdin = proc.getInputStream();
      InputStreamReader isr = new InputStreamReader(stdin);
      BufferedReader br = new BufferedReader(isr);
      String line = null;
      System.out.println("<OUTPUT>");
      while ((line = br.readLine()) != null)
        System.out.println(line);
      System.out.println("</OUTPUT>");
      int exitVal = proc.waitFor();
      System.out.println("Process exitValue: " + exitVal);
     
      if(proc.exitValue()!=0)
      {
        throw new OAException("The permission change failed with exit value" + proc.exitValue()+ " -->"+exitVal, OAException.ERROR);
      }
    }
    catch (Throwable t)
    {
      throw new OAException("Exception in  methodChangeFilePermissions :"+fileUrl.getAbsolutePath()+"-->"+t, OAException.ERROR);
    }
  }

  public void upLoadFile_FromInstance(OAPageContext pageContext, OAWebBean webBean,String path)
  {
    String filePath = path;
    String status = "N";
    File file = null;
    String fileUrl = null;
 
    try
    {
      DataObject fileUploadData = pageContext.getNamedDataObject("MsgFileUpload");
      //FileUploading is my MessageFileUpload Bean Id
      if (fileUploadData != null)
      {
        String uFileName = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");
        String contentType = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");
        FileOutputStream output = null;
        InputStream input = null;
        BlobDomain uploadedByteStream = (BlobDomain) fileUploadData.selectValue(null, uFileName);
        file = new File(filePath, uFileName);
        fileUrl = filePath + file.separator +"\""+ uFileName+"\"";
        output = new FileOutputStream(file);
        input = uploadedByteStream.getInputStream();
        byte abyte0[] = new byte[0x19000];
        int i;
        while ((i = input.read(abyte0)) > 0)
          output.write(abyte0, 0, i);

        output.close();
        input.close();
        status = "Y";
      }
    }
    catch (Exception ex)
    {
      throw new OAException(ex.getMessage(), OAException.ERROR);
    }
    methodChangeFilePermissions(file);
    if( status.equals("Y"))
    {
      throw new OAException("File Uploaded Successfully to Path : "+file, OAException.CONFIRMATION);
    }
  }
}

No comments:

Post a Comment