Friday, August 26, 2016

Attachment to Workflow Notification

Add multiple Attachments to Workflow Notification:


1. Create Attribute like below:


2. Add Message Attribute like below (to to respective Notification Messages)
                             
                              Internal name : #ATTACHMENTS
                              Display Name: #ATTACHMENTS
                                Value:    Custom Attachment Attribute (which created above)


3. In the Workflow Package Set the Attribute Value Like Below:
               
 
        SELECT count(*) into l_attach_cnt
      FROM  FND_ATTACHED_DOCS_FORM_VL
      WHERE  function_name  =DECODE(0,1,NULL,'GLXJEENT')
      AND function_Type=DECODE(0,1,NULL,'O')
      AND  (    (      entity_name = 'GL_JE_HEADERS'    AND pk1_value = l_je_batch_id )  )    ;
   
           

     if l_attach_cnt >0  then

        wf_engine.SetItemAttrText( itemtype => itemtype,
                                     itemkey  => itemkey,
                                     aname    => 'ATTACH_ATTRIBUTE',
                                     avalue   => 'FND:entity=GL_JE_HEADERS&'||'pk1name=je_batch_id&'||'pk1value='||l_je_batch_id );
     end if ;


4. After that check the notification to find all the attachments, all the attachments count is equal to l_attach_cnt variable. 

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);
    }
  }
}

Thursday, August 25, 2016

Oracle Workflow Topics

1. Oracle Workflow Basics
2. Attributes and Attribute Types
3. Process, Notifications, Functions, Events
4. Messages and Message Attributes, Lookup Types
5. Simple Workflow Creation from WFSTD
6. Intiate workflow
7. Deploying and call workflow in Instance
8. Debugging Workflow Processes
9. WAIT, TIMEOUT, LOOP, NOOP, AND, OR etc. Workflow Standard Functions
10. Database Tables of Workflow
11. FYI and Respond Notifications
12. Workflow Background Process, Workflow Definiation Loader
13. Notification with Attachment
14. Send OAF Page Link from Oracle Workflow
15. Parent and Child Workflow processes
16. Migration of Workflow through WF_LOAD

Friday, August 19, 2016

API to Delete Oracle Alert

Query to Get Alert Details:


Select * from ALR_ALERTS where alert_name like 'TEST_ALERT_NEW';


API to Delete Alert:

Declare
l_Alert_appl_id Number := 20003;                    -- Application Id from ALR_ALERTS
l_Alert_id Number := 11111;                         -- Alert Id from ALR_ALERTS

BEGIN
ALR_ALERTS_PKG.DELETE_ROW(l_Alert_appl_id,l_Alert_id);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Alert Deleted Successfully..'||SQLERRM);
ROLLBACK;
END;

Monday, August 15, 2016

OAF Topics

1. Introduction to OAF (Basics)
2. JDeveloper Setup and Deployment
3. MVC Architecture and Implementation
4. BC4J Objects
5. Hello World Page
6. Data Entry, Search and Update Page and Delete Page
7. Regions, Region Types, and Item Styles
8. Concepts of LOV's and Picklists and Event Capturing
9. PPR , Dependent LOV's, SPEL 
10. Passing Parameters in OAF
11. Table and Advance Table Concepts (single Selection, Multiple selection, totalling etc.)
12. File Upload Page, Download,  Tree Region in OAF
13. Dialogue page and Processing Page in oaf
14. Switcher Region in oaf
15. Tabs , Navigations in oaf
16. Master Child Relationship, Association objects in oaf
17. Images, Hide/Show, Java Script in OAF, Pop-up, Links in oaf
18. Single and Multiple Attachments in OAF
19. Calling PL SQL, SQL Statements from OAF
20. Validations and Debugging in oaf Pages
21. OAF Registration on Applications
22. Personalization, Extension of CO & VO in OAF 
23. Calling Oracle Form and Oracle Workflow from OAF page
24. Migration of OAF pages and OAF Page Personalizations
25. Custom CSS Properties to OAF Pages

Monday, August 1, 2016

ADF Quotes

1. Clear ADF Connection details and need to open JDeveloper fresh in 11g ?

Ans: Goto below path:

             C:\Users\<SystemUserName>\AppData\Roaming\JDeveloper

         and remove or rename file : system11.1.2.4.39.64.36.1 and restart the JDeveloper.