Friday, February 12, 2016

Export Table data or VOIterator Data in Excel in ADF using fileDownloadActionListener

Using fileDownloadActionListener we can export data as follows in adf:

Steps:

1) Create Adf Application
2)Create EO and VO for Employee Table.
3)Create page and Drag and Drop Employee VO DataControl in page.
4)Take one button named as "Export Data"
5)In Component Palette search fileDownloadActionListener and Drag and Drop on Export Data button

6)In properties of fileDownloadActionListener set following values to attributes:

 contentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
filename="Employee.xls"
method="#{Employees.getExcel}"

create method in Employee bean.

and paste following code in method getExcel()

NOTE :  First add library poi-3.7-20101029 .jar

    public void getExcel(FacesContext facesContext, OutputStream outputStream) {

        DCIteratorBinding dcIteratorBindings = null;
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet worksheet = workbook.createSheet("Employee"); //Tab Name

            DCBindingContainer bindings = (DCBindingContainer) BindingContext.getCurrent().getCurrentBindingsEntry();
            dcIteratorBindings = bindings.findIteratorBinding("EmployeesView1Iterator"); // VOIterator
            HSSFRow excelrow = null;

            // Get all the rows of a iterator
            Row[] rows = dcIteratorBindings.getAllRowsInRange();

            int i = 0;
            for (Row row : rows) {
                //print header on first row in excel
                if (i == 0) {
                    excelrow = (HSSFRow) worksheet.createRow((short) i);
                    short j = 0;
                    for (String colName : row.getAttributeNames()) {
                        HSSFCell cellA1 = excelrow.createCell((short) j);
                        cellA1.setCellValue(colName)
                        j++;
                    }
                }
                //print data from second row in excel
                ++i;
                short j = 0;
                excelrow = worksheet.createRow((short) i);
                for (String colName : row.getAttributeNames()) {

                    HSSFCell cell = excelrow.createCell(j);
                    if (row.getAttribute(colName) != null) {
                        cell.setCellValue(row.getAttribute(colName).toString());
                    }
                    j++;
                }
                worksheet.createFreezePane(0, 1, 0, 1);
            }
            workbook.write(outputStream);
            outputStream.flush();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

7)run the project


Hope it will help you

Tuesday, February 9, 2016

How to export ADF table data into excel Sheet in ADF

Sometime we need to export table data in Excel file.So Adf gives you simple solution on this.

Steps to export table data on button click:

create Sample application

create EO and VO of Employee table.


create page and drag and drop Employee data control as table

drag and drop button on page named "Export table data"
From "Component Palette" select Export Collection action Listener and drop on Export table data button.
following window will appears


In Exportid enter value of the table that you want to export
here it is "t1"

For Type “Select excelHTML” from drop down list and you are all set to go.

run the application and get the excel file


Hope this will help you


Tuesday, December 22, 2015

Oracle MAF: Programmatically call REST service ( REST with JSON output)

This example is using RESTServicesAdapter. Using that programmatically you can call a REST service and you can manipulate response as per need.

My REST service details are as follows:

URL: localhost:1111/HrServiceFirst-ViewController-context-root/resources/view/emp

{"lstEmp":[{"address":"ss","empId":22222,"empName":"sss"},{"address":"SKING","empId":100,"empName":"Steven"},{"address":"NKOCHHAR","empId":101,"empName":"Neena"},{"address":"LDEHAAN","empId":102,"empName":"Lex"},{"address":"AHUNOLD","empId":103,"empName":"Alexander"}]}

Step 1: Create new Mobile Application Framework (MAF) Application:



Step 2 :Right click on Connenction create new REST Connection

Give the name of rest Connection and URL End point click ok as follow:

Step 3: Create Employee Class and add following variable and generate accessors

    public Integer empId;
    public String empName;
    public String address;


Step 4: create  CallService class and add follwing code in it

package mobile;

import java.util.ArrayList;
import java.util.List;

import oracle.adfmf.dc.ws.rest.RestServiceAdapter;
import oracle.adfmf.framework.api.Model;
import oracle.adfmf.json.JSONArray;
import oracle.adfmf.json.JSONException;
import oracle.adfmf.json.JSONObject;

public class CallService {
    public CallService() {
        super();
    }
    List<Employee> lstEmp=new ArrayList<Employee>();
    private Employee emp;
    public void setLstEmp(List<Employee> lstEmp) {
        this.lstEmp = lstEmp;
    }

    public List<Employee> getLstEmp() {
        return lstEmp;
    }
    public void getEmployees() {
           RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter(); 
           restServiceAdapter.clearRequestProperties();  
           restServiceAdapter.setConnectionName("restConn");  
           restServiceAdapter.setRequestType(RestServiceAdapter.REQUEST_TYPE_GET);    
           restServiceAdapter.setRetryLimit(0);
           restServiceAdapter.setRequestURI("/emp");
           try {
               String response = restServiceAdapter.send(""); 
               JSONObject res = null;  
               res = new JSONObject(response);     
               JSONArray lstOfEmp=res.getJSONArray("lstEmp");
               
               for(int i=0;i<lstOfEmp.length();i++){
                  JSONObject obj=lstOfEmp.getJSONObject(i);
                  System.out.println("Emp name "+obj.getString("empName"));
                   Employee e=new Employee();
                   e.setEmpName(obj.getString("empName"));
                   lstEmp.add(e);
               }
           } catch (JSONException jsone) {
               // TODO: Add catch code
               jsone.printStackTrace();
           } catch (Exception e) {
               // TODO: Add catch code
               e.printStackTrace();
           }
       }
}

Step 5:create Data Control of CallService Class;


 Step 6: create feature in maf-feature.xml with type MAF Task Flow and create Task Flow.
create ViewActivity call named RestServiceCall and Create .amx Page

Then select getEmployees() method from data control drop in task flow:


           

In PageDef of method View add accessor iterator in executables

Step 6: drag and drop DC in Page with empName view Attribute in List View


Step 7: Deploy project on emulator

Output:


Monday, December 21, 2015

ADF : Exposing BC Component using REST Service

In this blog, we are Exposing BC Component using Rest Service.

For example write service to get 5 Employees name from Employees table.
Use following steps:

Step 1: create ADF Application 
Step 2: Create EO and VO for Employee

Step 3:Create java class name Employee and 3 variable as :
    private Integer empId;
    private String empName;
    private String address;

and generate accessors for this

Step 4: Create java class for EmpWrapper ,In this class create  private List<Emplyee> lstEmp; variable to store Objects of Employee.

write @XmlRootElement above EmpWapper Class

Step 5: create java class EmpService
write  public EmpWapper getEmp() {}
In this method write bc4j  press Ctrl+Enter you will get follwing suggestion

Press Enter, code is generated to access AM instances

        ADFContext oldContext = ADFContext.initADFContext(null, null, null, null);
        try {
            String amDef = "test.TestModule"; 
            String config = "TestModuleLocal";
            ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
            ViewObject vo = am.findViewObject("TestView"); // VO to Access
            // Work with your appmodule and view object here
            Configuration.releaseRootApplicationModule(am, true);
        } finally {
            ADFContext.resetADFContext(oldContext);
        }

Add your logic to get 5 Employes name:

Copy and Paste following method code in Class


public EmpWapper getEmp() {
        EmpWapper objEmp=new EmpWapper();
       
        ADFContext oldContext = ADFContext.initADFContext(null, null, null, null);
        try {
            String amDef = "model.AppModule";
            String config = "AppModuleLocal";
            ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
            ViewObject vo = am.findViewObject("EmployeesView");
            int i=0;
            List<Emplyee> lstEmp=new ArrayList<Emplyee>();
            while(vo.hasNext()){
                
              Row row= vo.next();
               
              Emplyee emp=new Emplyee();
              emp.setAddress(row.getAttribute("Email").toString());
              emp.setEmpId(new Integer(row.getAttribute("EmployeeId").toString()));
              emp.setEmpName(row.getAttribute("FirstName").toString()); 
              lstEmp.add(emp);
              
               
             i++;
             if(i==5)
               break;
            }
            objEmp.setLstEmp(lstEmp);   
            // Work with your appmodule and view object here
            Configuration.releaseRootApplicationModule(am, true);
           
        } finally {
            ADFContext.resetADFContext(oldContext);
        }
        return objEmp;

    }

Step 6: right click on EmpService class and click on Create Restful Service

you will window like as follws:
Click on Produce and select application/xml media Type

Step 7: No win Configure HTTP method set

Type = Get
Produce = application/json
path =emp

and last finish.

then WebService is created . EmpService class looks like as follws:


Step 8:Now Deploye project and Test service

Output:

Note : suppose you will select in Step 7 :
Produce = application/xml

then output will be like this;

Hope this will help you

Thursday, August 20, 2015

ADF : Refresh the parent view when a taskflow displayed in a popup returns


- Refreshing the parent view when an in-line popup taskflow returns.

This scenario usually arises when the second task flow updates tables used by the first one from a different transaction context. 

There are two taskflows, both work with separate transaction contexts(Transaction attribute is set as new-transaction). Second taskflow is invoked from the first one as a dialog. The requirement here is to refresh the 'executables' of calling page(from first taskflow) when the second taskflow returns. 



createWO view from first task flow.

truckCompTF is the second taskflow.


- Define a returnListener for secondary window on the command button (which invokes second taskflow as dialog)

- Create method as dialogReturnListener in returnListner and copy below code

    public void dialogReturnListener(ReturnEvent returnEvent) {
        BindingContext bc = BindingContext.getCurrent();
          DCBindingContainer dcb =
            (DCBindingContainer)bc.getCurrentBindingsEntry();
          DCIteratorBinding iter =
            dcb.findIteratorBinding("TransportUnitVOIterator");   //your VOIterator 
          iter.executeQuery();         // It refresh the underlying IteratorBindings used by the parent page. 
       RequestContext.getCurrentInstance().addPartialTarget(returnEvent.getComponent().getParent().getParent());

    }


Tuesday, August 4, 2015

ADF - How-to show a glasspane and splash screen for long running queries


A Glass Pane is a pop-up that prevents user-input while a large database job or query is running in the background. It uses a splash screen with an animated image giving the impression of activity while the job completes.

The Glass Pane will consist of a pop-up that is activated by a javascript function included in the page-template.

Add Javascript File and Popup to Page Template:

Add the Popup in the Template as follows:

 <af:popup id="Busypopup"  contentDelivery="immediate">
                <af:dialog id="d2" type="none" closeIconVisible="false" title="File uploading...">
                    <af:panelGroupLayout id="pgl5" layout="vertical">
                        <af:image source="/resources/images/1processing.gif" id="i1"/> 
                    </af:panelGroupLayout>
                </af:dialog>
            </af:popup>

Include below Javascript code in the Template by using a Resource component.



function enforcePreventUserInput(evt) {
              var popup = AdfPage.PAGE.findComponentByAbsoluteId('pt1:Busypopup');
              if (popup != null) {
                  AdfPage.PAGE.addBusyStateListener(popup, handleBusyState);
                  evt.preventUserInput();
              }
          }
              function handleBusyState(evt) {
                  var popup = AdfPage.PAGE.findComponentByAbsoluteId('pt1:Busypopup');
                  if (popup != null) {
                      if (evt.isBusy()) {
                          popup.show();
                      }
                      else if (popup.isPopupVisible()) {
                          popup.hide();
                          AdfPage.PAGE.removeBusyStateListener(popup, handleBusyState);
                      }
                  }

              }

In above Code , pt1 is the page template id and Busypopup is the popup id.
pt1:Busypopup by this we get the address of popup.



Client Listener

On the button that calls the query or database job add a clientListener.
Ensure the PartialSubmit of the button is set to true (the default)


Add enforcePreventUserInput as the method (the javascript function we created earlier)


For  <af:inputFile> component use Type -> click in Client Listener
For  <af:button>     component use Type -> action in Client Listener


Output:



Monday, August 3, 2015

ADF- Checkbox selection will be calculated using Groovy, based on additional helper attribute.

In this blog we will see how to select or deselect checkbox value:

Steps:

Create your EO and VO of Table.
In this Example , i have TransportUnitVO. Here,I want to set a check box value (true or false) to attribute Discard.


create one new transient attribute of type Boolean named as CheckedDis and write groovy as follow in expression field of that attribute.

 Now in a page create one column, drag and drop this attribute in it.
On value changed write below Code in managed bean:

public void discardCheck(ValueChangeEvent valueChangeEvent) {
       Row  row = ADFUtils.getSelectedCurrentRow("TransportUnitVOIterator");
        if(valueChangeEvent.getNewValue().toString().equalsIgnoreCase("true")){
            row.setAttribute("Discard", "true");
        }else{
            row.setAttribute("Discard", "false"); 
        }
    }

After drag and drop, in a page source should be:

<af:selectBooleanCheckbox value="#{row.bindings.CheckedDis.inputValue}"
                                               label="#{row.bindings.CheckedDis.label}"
                                       shortDesc="#{bindings.TransportUnitVO.hints.CheckedDis.tooltip}"
                                     autoSubmit="true" immediate="true" id="sbc1" 
                      valueChangeListener="#{workOrderBean.discardCheck}"/>



Save all changes and run Page:

Output:
After saving details of TransportUnitVO value inserted of attribute Discard is true or false: