Loading...


af:richTextEditor
is used to format text in rich text using HTML formatting and it is used to get formatted text. Previously I have posted about it
Cool Component - Using af:richTextEditor as text editor, HTML editor with custom toolbox in Oracle ADF



But I have seen developers asking about getting plain text value from richTextEditor,
It means on UI editor shows HTML formatted text but when getting value in managed bean it should ignore HTML tags and formatting
This component is designed for rich text editing so there is no direct way to get plain text
So for this requirement we need to parse HTML into plain text , Here I am using jsoup java library to parse HTML

When we get this value in bean using component binding it returns


Now to get plain text without formatting just parse this HTML using jsoup library, Add library to viewController project


and use this simple code

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

Document doc = Jsoup.parse(ritValue);
System.out.println(doc.text());

and it returns

Cheers :) Happy Learning
Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Facebook is most popular social networking sites now a days and influencing our life in all aspect. Facebook gives us option to use it's Graph API to access it's features programmatically, The Graph API is primary way to read and write to facebook social graph using Access Tokens

In this post I am talking about how to access Facebook profile detail using restfb graph API . So First we need to know about Acsess Tokens

What docs says- 
When someone connects with an app using Facebook Login, the app will be able to obtain an access token which provides temporary, secure access to Facebook APIs.

An access token is an opaque string that identifies a user, app, or Page and can be used by the app to make graph API calls
The token includes information about when the token will expire and which app generated the token. Because of privacy checks, the majority of API calls on Facebook need to include an access token.

restfb Graph API-
RestFB is a simple and flexible Facebook Graph API client written in Java.It is open source software and simplifies code for you , It provides default implementation for all components . We need to access it's methods and customized it

Let's start with getting access token for our application
Open Graph API Explorer , You'll see a input text there to enter token



As we don't have any token so we need to generate one , click on Get token - Get User Access Token, It'll open a dialog asking permissions
See here I have requested for following permissions to get user profile


Click on Get Access Token button and allow facebook to give these permissions and continue


It'll generate a temporary Access Token, that'll be used to connect facebook


Now created a fusion web application , added two input text to enter AccessToken and Id and a button to submit data


Download restfb jar file and add it to view controller project


Created component binding for both input text and output text (to show response) in managed bean, See managed bean code

Packages Used-
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;

import javax.faces.event.ActionEvent;

import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.output.RichOutputFormatted;

Component Binding to get and set page data-
    //Component Binding for ID field
private RichInputText idBind;
//Component binding for AccessToken field
private RichInputText fbTokenBind;
//Component Binding for response output text
private RichOutputFormatted reponseBind;


public void setIdBind(RichInputText idBind) {
this.idBind = idBind;
}

public RichInputText getIdBind() {
return idBind;
}

public void setFbTokenBind(RichInputText fbTokenBind) {
this.fbTokenBind = fbTokenBind;
}

public RichInputText getFbTokenBind() {
return fbTokenBind;
}

public void setReponseBind(RichOutputFormatted reponseBind) {
this.reponseBind = reponseBind;
}

public RichOutputFormatted getReponseBind() {
return reponseBind;
}

Method to connect Facebook and access profile detail-
    /**Method to connect facebook and access profile details
* @param actionEvent
*/
public void fetchInfo(ActionEvent actionEvent) {
//Get Access Token
String accessToken = fbTokenBind.getValue().toString();
//Get Id
String id = idBind.getValue().toString();
//Initiate facebook client for accessToken
fbClient = new DefaultFacebookClient(accessToken);
//Get User
User user = fbClient.fetchObject("me", User.class);
//Get Profile details (We can get only permissible object) using User Object
reponseBind.setValue("Name- " + user.getName() + "<br>Gender- " + user.getGender() + "<br>DOB- " +
user.getBirthday() + " <br>Bio- " + user.getBio() + "<br>Status- " +
user.getRelationshipStatus() + "<br>Religion- " + user.getReligion() + "<br>Websites- " +
user.getWebsite() + "<br> Hometown- " + user.getHometownName());

}


Now run application and enter UserId and AccessToken that we generated earlier, Click on Fetch button and profile details is on page :)

Get Facebook Profile using restfb Graph API in Java & Oracle ADF - YouTube


Sample ADF Application (Jdeveloper 12.1.3)- Download
Cheers :) Happy Learning
Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hello All

I have posted about using external XML file as List resource bundle earlier , the aim of resource file is to read application static text from some source so that we can change that without compiling and redeploying application

Next requirement is to change application language , sometimes we need support multiple langauge in ADF application and it requires change in all static text so for this I am going to use separate XML resource file for different language and in this post I'll show that how to update resource file in a live running application



Here I am using same sample application and after adding resource for English language , added a list on page to select language


created a value change listener in managed bean for this list

<af:selectOneChoice label="Select Language" id="soc1" autoSubmit="true"
valueChangeListener="#{ResourceManagerBean.changeLanguageVCE}"
contentStyle="width:100px;">
<af:selectItem label="English" value="English" id="si1"/>
<af:selectItem label="French" value="French" id="si2"/>
<af:selectItem label="Dutch" value="Dutch" id="si3"/>
</af:selectOneChoice>

Here ResourceManagerBean is a session scope bean , Initialized a session scope variable that holds the path of resource file and on value change listener of choice list I'll change path of resource file on basis of selected language

In this demo I am using 3 XML resource files for 3 different languages (English, French and Dutch)
User will select any language from the list and resource values will be read from respective resource file after a page refresh and clearing resource cache

Managed Bean Code-

import java.io.Serializable;

import java.util.ResourceBundle;

import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

import javax.servlet.http.HttpSession;

public class ResourceManagerBean implements Serializable {

//String variable to hold locale
private String appLocale;

public void setAppLocale(String appLocale) {
this.appLocale = appLocale;
}

public String getAppLocale() {
return appLocale;
}
public ResourceManagerBean() {
//Take a session variable to put resource file path
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(true);
session.setAttribute("resName", "D://Resource_En.xml");
}

/**Method to forcefully refresh page
*/
protected void refreshPage() {

FacesContext fctx = FacesContext.getCurrentInstance();
String page = fctx.getViewRoot().getViewId();
ViewHandler ViewH = fctx.getApplication().getViewHandler();
UIViewRoot UIV = ViewH.createView(fctx, page);
UIV.setViewId(page);
fctx.setViewRoot(UIV);

}

/**Method to change app language by changing locale and XML resource file of application
* @param vce
*/
public void changeLanguageVCE(ValueChangeEvent vce) {
if (vce.getNewValue() != null) {
if ("English".equalsIgnoreCase(vce.getNewValue().toString())) {
//Change application locale to English
setAppLocale("en");
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(true);
session.setAttribute("resName", "D://Resource_En.xml");

} else if ("French".equalsIgnoreCase(vce.getNewValue().toString())) {
//Change application locale to French
setAppLocale("fr");
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(true);
session.setAttribute("resName", "D://Resource_fr.xml");

} else if ("Dutch".equalsIgnoreCase(vce.getNewValue().toString())) {
//Change application locale to Dutch (Netherland)
setAppLocale("nl");
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(true);
session.setAttribute("resName", "D://Resource_nl.xml");

}
//Clear Resource Bundle cache to load Resource.java file again
ResourceBundle bundle = ResourceBundle.getBundle("listresourcebundle.view.bundle.Resource");
bundle.clearCache();

//Refresh Page after changing resource file
refreshPage();
}
}
}

Small change in Resource.java file , Now it reads Resource file path from session scope variable that is initialized in managed bean

Resource.java file-

import java.io.File;

import java.util.ListResourceBundle;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Resource extends ListResourceBundle {

//Path to XML Resource File
private String Res_path =
    resolvEl("#{sessionScope.resName}");

//Initialize an Object Array to hold label and key values
public Resource() {
for (int i = 0; i < 5000; i++) {
contents[i][0] = "";
contents[i][1] = "";
}
}

private static final Object[][] contents = new Object[5000][2];

/**Method to process XML file and get key and value of resource and put that in array
* @return
*/
public Object[][] getContents() {
try {
System.out.println("Resource path is- " + Res_path);
File file = new File(Res_path);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("label");

for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;
contents[temp][0] = getTagValue("key", eElement);
contents[temp][1] = getTagValue("value", eElement);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return contents;
}

private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = nlList.item(0);
return nValue.getNodeValue();
}

public String resolvEl(String data) {
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp = elFactory.createValueExpression(elContext, data, Object.class);
Object expVal = valueExp.getValue(elContext);
String Message = "D:\\Resource_En.xml";
if (expVal != null) {
Message = expVal.toString();
}

return Message;
}
}

Next step is to refer page locale from managed bean , Open page and in structure window select f:view tag (container tag for all components used on page)


 Refer locale property to bean variable


All Done :) Run and Check Application

Supporting multiple language in ADF application using XML Resource files - YouTube


Sample ADF Application (Jdeveloper 12.1.3)- Download
Cheers :) Happy Learning
Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Hello All
Hope you all are doing well :)

This post is about exporting view object data in a pdf file directly from af:table , export to excel is built in feature of ADF but exporting data in PDF requires little bit of extra effort
So here for this requirement I am using Apache PDFBox library , previously I have posted about using this API to create PDF file from text data
I know many of you will not visit that link ;) So a quick overview



What is Apache PDFBox
The Apache PDFBox library is an open source Java tool for working with PDF documents. This project allows creation of new PDF documents, manipulation of existing documents and the ability to extract content from documents. Apache PDFBox also includes several command line utilities.

Let's implement this

  • Create a Fusion Web Application and prepare model using Departments table of HR Schema


  • Add PDFBox jar to view controller project


  • Drop Departments view object as table on page and add two buttons to Export All Rows and Export Selected Row


  • Now see the managed bean code that exports viewObject data to PDF file , Idea is to add viewObject data in a multi dimensional array and then iterate over array to draw a table in pdf Go through the comments to understand code part
Packages and Helper method-
import java.io.IOException;

import javax.faces.event.ActionEvent;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCIteratorBinding;

import oracle.binding.BindingContainer;

import oracle.jbo.Row;
import oracle.jbo.RowSetIterator;
import oracle.jbo.ViewObject;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

 /**
* Generic Method to call operation binding**/
public BindingContainer getBindingsCont() {
return BindingContext.getCurrent().getCurrentBindingsEntry();
}

Method to Export All Rows of ViewObject to PDF-
    /**Method to export all rows of viewObject to PDF
* @param actionEvent
* @throws IOException
*/
public void exportAllRowsToPdfAction(ActionEvent actionEvent) throws IOException {
//Create new PDF Document
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);

//Get the iterator of af:table on page
DCIteratorBinding iter = (DCIteratorBinding) getBindingsCont().get("DepartmentsVO1Iterator");
//No of total rows+ 1 for array sizing
int totRows = ((int) iter.getEstimatedRowCount()) + 1;
//Here 4 is the number of columns
String[][] content = new String[totRows][4];

int column = 4;
//Set header text in first row of table in PDF
content[0][0] = "Department Id";
content[0][1] = "Department Name";
content[0][2] = "Manager Id";
content[0][3] = "Location Id";

//Get viewObject from iterator and Iterate over it to add all data in array
ViewObject vo = iter.getViewObject();
RowSetIterator rsi = vo.createRowSetIterator(null);
int i = 1;
while (rsi.hasNext()) {
Row nextRow = rsi.next();

for (int j = 0; j < column; j++) {
System.out.println(i + "" + j);
if (j == 0 && nextRow.getAttribute("DepartmentId") != null) {
content[i][j] = nextRow.getAttribute("DepartmentId").toString();
}
if (j == 1 && nextRow.getAttribute("DepartmentName") != null) {
content[i][j] = nextRow.getAttribute("DepartmentName").toString();
}
if (j == 2 && nextRow.getAttribute("ManagerId") != null) {
content[i][j] = nextRow.getAttribute("ManagerId").toString();
}
if (j == 3 && nextRow.getAttribute("LocationId") != null) {
content[i][j] = nextRow.getAttribute("LocationId").toString();
}
}
i++;
}
rsi.closeRowSetIterator();
//Write data to PDF
writeToPdf(contentStream, content);

contentStream.close();
try {
//Save generated pdf document in a drive
document.save("D:\\Departments.pdf");
} catch (COSVisitorException e) {
}
}

Method to Export Selected Row of ViewObject to PDF-
    /**Method to export selected row to PDF
* @param actionEvent
* @throws IOException
*/
public void exportCurRowToPdfAction(ActionEvent actionEvent) throws IOException {
//Create new PDF Document
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);

//Get the iterator of af:table on page
DCIteratorBinding iter = (DCIteratorBinding) getBindingsCont().get("DepartmentsVO1Iterator");
//Define the array for two rows only
String[][] data = new String[2][4];

//Set header text in first row of table in PDF
data[0][0] = "Department Id";
data[0][1] = "Department Name";
data[0][2] = "Manager Id";
data[0][3] = "Location Id";

//Get current row of Iterator and insert data in array
Row row = iter.getCurrentRow();

if (row.getAttribute("DepartmentId") != null) {
data[1][0] = row.getAttribute("DepartmentId").toString();
}
if (row.getAttribute("DepartmentName") != null) {
data[1][1] = row.getAttribute("DepartmentName").toString();
}
if (row.getAttribute("ManagerId") != null) {
data[1][2] = row.getAttribute("ManagerId").toString();
}
if (row.getAttribute("LocationId") != null) {
data[1][3] = row.getAttribute("LocationId").toString();
}
//Write data to PDF
writeToPdf(contentStream, data);

contentStream.close();
try {
//Save generated pdf document in a drive
document.save("D:\\Departments.pdf");
} catch (COSVisitorException e) {
}
}

Method to draw table in PDF -
    /**Method to draw table on pdf using array of data
* @param page
* @param contentStream
* @param y
* @param margin
* @param content
* @throws IOException
*/
public static void writeToPdf(PDPageContentStream contentStream, String[][] data) throws IOException {
final int rows = data.length;
final int cols = data[0].length;

//Height for each row
final float rowHeight = 20f;
//Width of table drawn
final float tableWidth = 550;

//Total table height
final float tableHeight = rowHeight * rows;
//Width of each column
final float colWidth = tableWidth / (float) cols;
final float cellMargin = 5f;
//Margin from left
float margin = 20;
//Margin from top (Increase value to decrease margin)
float y = 750;
//draw the rows
float anoy = y;

for (int i = 0; i <= rows; i++) {
contentStream.drawLine(margin, anoy, margin + tableWidth, anoy);
anoy -= rowHeight;
}

//Draw the columns
float anox = margin;
for (int i = 0; i <= cols; i++) {
contentStream.drawLine(anox, y, anox, y - tableHeight);
anox += colWidth;
}

//Setting for font and size
contentStream.setFont(PDType1Font.COURIER_BOLD, 10);

float textx = margin + cellMargin;
float texty = y - 15;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (data[i][j] != null) {
String text = data[i][j];

contentStream.beginText();
contentStream.moveTextPositionByAmount(textx, texty);
contentStream.drawString(text);
contentStream.endText();
textx += colWidth;
}
}
texty -= rowHeight;
textx = margin + cellMargin;
}
}

All Done :) Now run and check application

Export ViewObject data to PDF file using Apache PDFBox in Oracle ADF - YouTube


Sample ADF Application (Jdeveloper 12.1.3)- Download
Cheers :) Happy Learning
Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hello All

Previously I have posted about uploading and saving files in database blob column now this post is about showing saved file content on page using ADF Faces inline frame component

In this post I am extending same previous application, Now see how we can implement this
There are few more steps to go , See the additional steps to show file content on page-




  • Create a servlet to parse file into output stream , this output stream will be used to show file content further.
    To create servlet right click on viewController project select New--->From Gallery-->Web Tier-->Servlet




  • See servlet source code to read BLOB file from database and then parse file into outputStream

  • import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.io.OutputStream;

    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;

    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class PreviewFileServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    }

    /**
    * @param request
    * @param response
    * @throws ServletException
    * @throws IOException
    */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Get fileName from parameter
    String fileName = (request.getParameter("fname"));

    OutputStream os = response.getOutputStream();
    Connection conn = null;
    try {
    System.out.println("FileName is- " + fileName);
    //Get database connection object
    conn = getDBConnection();
    //Prepare statement using SQL query to get blob file using file name
    PreparedStatement statement =
    conn.prepareStatement("SELECT IMAGE_FILE FROM FILE_UPD_DWN WHERE FILE_NAME = ?");

    //Pass file name as parameter
    statement.setString(1, fileName);

    //Execute Statement, It'll return a result set
    ResultSet rs = statement.executeQuery();

    //Get BLOB file and read binaryStream and write to outputStream
    if (rs.next()) {
    Blob blob = rs.getBlob("IMAGE_FILE");
    BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream());
    int b;
    byte[] buffer = new byte[10240];
    while ((b = in.read(buffer, 0, 10240)) != -1) {
    os.write(buffer, 0, b);
    }
    os.close();
    }
    } catch (Exception e) {
    System.out.println(e);
    } finally {
    if (conn != null) {
    try {
    conn.close();
    } catch (SQLException e) {
    }
    }

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

    /**Method to get oracle DB conncection object
    * @return
    * @throws Exception
    */
    public static Connection getDBConnection() throws Exception {
    //Type4 Oracle JDBC driver
    String driver = "oracle.jdbc.driver.OracleDriver";
    //Connection url string (hostname,portname, service name)
    String url = "jdbc:oracle:thin:@localhost:1521:XE";
    //DB UserName
    String username = "HR";
    //DB user password
    String password = "hr";

    Class.forName(driver); // load Oracle driver
    //Get connecion object using above detail
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
    }
    }

  • Now open page in editor and drop an af:inlineFrame from component palette . inlineFrame is used to create a frame to show any external page or document just like as HTML iframe , it is loaded from source attribute So here i am using servlet as source attribute for this inlineFrame

  • <af:inlineFrame id="if2" inlineStyle="height:350px;width:800px;" sizing="preferred"
    source="/previewfileservlet?fname=#{bindings.FileName.inputValue == null ? 'No' : bindings.FileName.inputValue}"/>

    Here fileName of document is added to pageDef bindings that is passed to servelt as parameter

  • Now run this application and check it

    View Image File


  • View Text File


Sample ADF Application-Download
Thanks :) Happy Learning
Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Hello all

This post is about a very simple requirement -file handling (uploading and downloading various types of file) in ADF and it is needed very often to store file in absolute server path (actual path) and download from there and I have posted about that previously

Uploading and downloading files from absolute server path

Now this post is about uploading and saving file in database BLOB column and downloading from there
See step by step implementation -



  • Created a simple table in HR schema to store uploaded file name ,path ,content type and file in BLOB column
  • See sql script for this table-

    CREATE TABLE FILE_UPD_DWN  
    (
    FILE_NAME VARCHAR2(50 BYTE),
    PATH VARCHAR2(100 BYTE),
    CONTENT_TYPE VARCHAR2(500 BYTE),
    IMAGE_FILE BLOB
    )


  • Then prepare model using this table and drop on page as af:table, and an af:inputFile component to select and upload file 

  • Then create a ValueChangeListener on inputFile component to create new row in table and upload file to database

  • Packages Used

    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    import java.sql.SQLException;

    import java.util.List;

    import javax.faces.context.FacesContext;
    import javax.faces.event.ValueChangeEvent;

    import oracle.adf.model.BindingContext;
    import oracle.adf.model.binding.DCIteratorBinding;
    import oracle.adf.view.rich.util.ResetUtils;

    import oracle.binding.BindingContainer;
    import oracle.binding.OperationBinding;

    import oracle.jbo.ViewObject;
    import oracle.jbo.domain.BlobDomain;

    import org.apache.myfaces.trinidad.model.UploadedFile;

    import upddwd.model.view.FileUpdDwnVORowImpl;

    Bean method to upload file in database
        /**Method to upload file in Database
    * @return
    */
    public String UploadFileActionToDB(UploadedFile file) {
    UploadedFile myfile = file;
    if (myfile != null) {
    //Get current row of viewObject using iterator
    DCIteratorBinding imageIter = (DCIteratorBinding) getBindingsCont().get("FileUpdDwn1Iterator");
    ViewObject vo = imageIter.getViewObject();
    FileUpdDwnVORowImpl curRow = (FileUpdDwnVORowImpl) vo.getCurrentRow();

    try {
    //Save image in Blob column in database
    curRow.setImageFile(createBlobDomain(myfile));

    } catch (Exception ex) {
    System.out.println("Exception-" + ex);
    }

    }
    return null;
    }

    /**Method to create blobdomain for uploaded file
    * */
    private BlobDomain createBlobDomain(UploadedFile file) {
    InputStream in = null;
    BlobDomain blobDomain = null;
    OutputStream out = null;

    try {
    in = file.getInputStream();

    blobDomain = new BlobDomain();
    out = blobDomain.getBinaryOutputStream();
    byte[] buffer = new byte[8192];
    int bytesRead = 0;

    while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
    out.write(buffer, 0, bytesRead);
    }

    in.close();

    } catch (IOException e) {
    e.printStackTrace();
    } catch (SQLException e) {
    e.fillInStackTrace();
    }

    return blobDomain;
    }

    AMImpl method to insert record in DB table for new file

        /**Method to set file path and name
    * @param name
    * @param path
    */
    public void setFileData(String name, String path, String contTyp) {
    ViewObject fileVo = this.getFileUpdDwn1();
    Row newRow = fileVo.createRow();
    newRow.setAttribute("FileName", name);
    newRow.setAttribute("Path", path);
    newRow.setAttribute("ContentType", contTyp);
    fileVo.insertRow(newRow);
    }

    AMImpl method to check for duplicate file record in DB table
        /**Method to check for duplicate files
    * @param fileNm
    * @return
    */
    public String checkDuplicateFile(String fileNm) {
    ViewObject fileVo = this.getFileUpdDwn1();
    Row duplFile[] = fileVo.getFilteredRows("FileName", fileNm);
    if (duplFile.length > 0) {
    return "N";
    } else {
    return "Y";
    }
    }

    ValueChangeListener to execute all methods
        /**
    * Generic Method to execute operation
    * */
    public OperationBinding executeOperation(String operation) {
    OperationBinding createParam = getBindingsCont().getOperationBinding(operation);
    return createParam;
    }

    /**Method to Upload Multiple Files to DB ,called on ValueChangeEvent of inputFile
    * @param vce
    */
    public void uploadFileVCE(ValueChangeEvent vce) {
    if (vce.getNewValue() != null) {
    //Get File Object from VC Event
    List<UploadedFile> lf = (List<UploadedFile>) vce.getNewValue();

    //Traverse over file list to upload all files
    for (UploadedFile fileVal : lf) {
    //Method to check if this file is uploaded previously or not
    OperationBinding duplOb = executeOperation("checkDuplicateFile");
    duplOb.getParamsMap().put("fileNm", fileVal.getFilename());
    duplOb.execute();
    if (duplOb.getResult() != null && "Y".equalsIgnoreCase(duplOb.getResult().toString())) {

    //Method to insert data in table to keep track of uploaded files
    OperationBinding ob = executeOperation("setFileData");
    ob.getParamsMap().put("name", fileVal.getFilename());
    ob.getParamsMap().put("path", "DB");
    ob.getParamsMap().put("contTyp", fileVal.getContentType());
    ob.execute();
    //Upload and Save file to DB
    UploadFileActionToDB(fileVal);
    //Commit the transaction
    executeOperation("Commit").execute();
    //Execute ViewObjecy
    executeOperation("Execute").execute();
    }
    }
    // Reset inputFile component after upload
    ResetUtils.reset(vce.getComponent());
    }
    }


  • Now run and check application , Drop single or multiple files in af:inputFile component


  • Check in DB table, all records are saved with file in BLOB :)


  • I have seen that developers often use servlet to download and open file in browser window using HTTP response , but no need to to do this as ADF provides built in component for this <af:fileDownloadActionListener> that automatically generate http response

  • Now Upload part is complete , for download functionality added a link in table column and dropped an af:fileDownloadActionListener inside link and set properties for DownloadActionListener



  • See Download Listener Code

  •     /**Method to download file from actual path
    * @param facesContext
    * @param outputStream
    */
    public void downloadFileListener(FacesContext facesContext, OutputStream outputStream) throws IOException {

    DCIteratorBinding imageIter = (DCIteratorBinding) getBindingsCont().get("FileUpdDwn1Iterator");
    ViewObject vo = imageIter.getViewObject();
    FileUpdDwnVORowImpl curRow = (FileUpdDwnVORowImpl) vo.getCurrentRow();

    BlobDomain blob = curRow.getImageFile();
    BufferedInputStream in = null;

    in = new BufferedInputStream(blob.getBinaryStream());

    int b;
    byte[] buffer = new byte[10240];
    while ((b = in.read(buffer, 0, 10240)) != -1) {
    outputStream.write(buffer, 0, b);
    }
    outputStream.close();
    }
Sample ADF Application- Download
Cheers :) Happy Learning
Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post I am putting some practices and that we should follow while using Oracle Application Development Framework for development




  • Call database (PL/SQL) function and procedure in model layer and then access in managed bean using page level bindings
    ADF Basics: Call PL/SQL Stored function in ADF Application
  • Use Exception Handler in Taskflow where required
    Global Exception Handler for ADF Task Flow Method Calls
  • Some ADF Component use animation for rendering like table, tree, popup. Consider animation-enabled false for better performance
    This can be controlled through ADF Skin
  • Ensure that each EnityObject/ ViewObject must have a primary key




  • Configure resource bundle before creating business components
    Using external XML file as list resource bundle in ADF Application
  • Avoid code duplication, Use utility classes instead - ADFUtil, JSFUtil etc
    ADF and JSF Utils Clasees
  • Avoid using editable tables, Use forms to edit data of tables
  • Avoid editable primary key attribute
  • Close iterators after use
  • Use ADF Logger instead of System.out.println
  • Choose bean scope carefully , lots of problem occurs due to wrong bean scope
    Memory Scope For ADF Managed Beans-As per Fusion Developer guide
  • Don't use getDBTransaction().postChanges unless you have a commit operation in same request
  • Check for null values instead of using try/catch block everywhere
  • Avoid circular dependency of list of values
  • Use createRowSetIterator() for view object programmatic iteration instead of using AllRowsInRange
  • Always use readOnly viewObject for view based or reference data, This helps in performance as it avoids EntityCache
  • Write business logic in model level implementation classes as AMImpl/VOImpl and call those methods in bean using binding layer
    ADF Basics: How to invoke model layer methods from managed bean (Best Practice to write business logic in ADF)
  • Implement bean serialization for applicationScope, sessionScope, pageFlowScope beans 
  • ADF Faces requires only one root component per fragment
  • Ensure uniqueness of taskflow name, managed bean name and application module name in entire application
  • Always check for null values while calculating transient attributes default values
  • Don't write bulky and unnecessary code in accessors of components or attributes as accessors are called multiple times so it'll affect performance
  • Catch Jbo Exceptions while calling pl/sql functions/procedure and show as a message on page instead of showing ADF/DB generated messages
  • To apply validation and autoSuggest like feature in search form use custom search instead of af:query component
  • Ensure that component bindings should be in a request scoped bean not greater than that
  • Instead of using setWhereClause() use query based bind variable to improve performance
  • Use basic tuning in ViewObjects to fetch rows from DB to improve performance
  • Don't set immediate true for editable input components
  • Don't use cached application module reference in bean instead of caching, look for AM when required as it is a pooled resource that's why it is never guaranteed that you will get same AM instance over a period of time. You'll end up getting lots of Null Pointer Exceptions
  • Don't use RowId as primary key in entity object , To avoid this define primary key in DB table itself
  • Never use SELECT * FROM in viewObject instead specify required column names
  • Avoid ViewObject expert mode for entity based viewObject. To add where clause , order by clause use viewObject or view object based bind variable
Oracle ADF Best Practices, Mistakes and Worst Practices - YouTube

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Hello All

Previously I have posted about a requiremnt of  hiding af:inputListOfValues search icon using CSS
ADF Skinning | Hiding search icon of af:inputListOfValues using CSS & StyleClass

In that solution search icon doesn't appear on page but it is a part of JSF component tree so when user press TAB+SPACE after entering a value in lov component then search popup appears on screen as this action invokes search icon click event

Recently a Friend of mine came across another requirement that was not showing lov popup at all as only autoSuggest behavior was required , so for this first way is to use autoSuggest behavior in an af:inputText compoent using Lov bindings and second way is to short circuit component life cycle



Suppose you have created lov on department name attribute

Enter some value and press TAB+SPACE



LOV search popup appears with some results 

Now to short-circuit JSF life cycle we'll use

FacesContext.getCurrentInstance().responseComplete();

responseComplete indicates that you have already handeled the response and JSF need not to reponse and lifecycle will skip to response as soon as current processing ends and final view of page is created as per JSF component tree

So create launchPopupListener method for LOV in managed bean and write this single line of code

af:inputListOfValues XML source on page
<af:inputListOfValues id="deptNameTransId"
popupTitle="Search and Select: #{bindings.DeptNameTrans.hints.label}"
value="#{bindings.DeptNameTrans.inputValue}"
label="Department"
model="#{bindings.DeptNameTrans.listOfValuesModel}"
required="#{bindings.DeptNameTrans.hints.mandatory}"
columns="#{bindings.DeptNameTrans.hints.displayWidth}"
shortDesc="#{bindings.DeptNameTrans.hints.tooltip}"
launchPopupListener="#{viewScope.InputLovBean.lovLaunchPopupListener}"
autoSubmit="true" contentStyle="width:300px;font-weight:bold;padding:2px;">
<f:validator binding="#{bindings.DeptNameTrans.validator}"/>
<af:autoSuggestBehavior suggestedItems="#{bindings.DeptNameTrans.suggestedItems}"/>
</af:inputListOfValues>

LaunchPopupListener code in managed bean
    /**Mehtod to handle launchEvent of Lov Popup
* @param launchPopupEvent
*/
public void lovLaunchPopupListener(LaunchPopupEvent launchPopupEvent) {
//responseComplete indicates that you have already handeled the response
//and JSF need not to reponse and lifecycle will skip to response as soon as
//current processing ends and final view of page is created as per
//JSF component tree
FacesContext.getCurrentInstance().responseComplete();
}

Cheers :) Happy Learning
Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hello All

This post is about a problem that occurs sometimes in af:table when we use icon in any column, I am not sure that it is a bug or not but sometimes table is not fully stretched on first load and last row doesn't appear properly on page but after refreshing page again problem is solved.



Recently I have seen a question on OTN forum about this and sharing that information here so that if anyone is facing same problem then look into it



So if you have to show specific number of rows and if you are facing this problem then set autoHeightRows property to -1 and set height in inlineStyle property of af:table

Check OTN Thread - Missing Last Record in ADF Table
Cheers :) Happy Learning
Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hello All

Recently I have seen a question on OTN forum - Question on cascading LOV

It was about cascading lovs in ADF
Suppose we have 2 dependent LOVs and requirement is that 2nd lov should not show any data until first one is selected , this is very simple and common use case but for beginners it's a tedious task

So I thought to write it here to help others



Let's see how to implement this

Here I am using Employees and Departments viewObject to create LOVs and Employees lov is dependent on Departments . I have a dual VO where I have to apply these LOVs

Hope you all know how to create a LOV :)
Created two LOVs on EmpId and DeptId




Now to make Employees Lov dependent on Departments, created a view Cirteria in EmployeesVO to filter Employees list using selected DepartmentId


and then pass bind variable value from view accessor to filter employees list using selected Department Id



Now run and check application module, You can see by default all Employees appears if you don't select a Department

Now requirement is to not show any employee until a department is selected, To do this go to Employees ViewObject and Open view criteria and select viewCritieriaItem tag in xml source and change this property


Set GenerateIsNullClauseForBindVars to false to check that if there is null value in bind var then data will not be filtered


After changing XML source is this

<ViewCriteriaItem
Name="DepartmentId"
ViewAttribute="DepartmentId"
Operator="="
Conjunction="AND"
Value=":BindDeptId"
IsBindVarValue="true"
Required="Optional"
GenerateIsNullClauseForBindVars="false"/>

Now run and check application module again


Cheers :) Happy Learning
Read Full Article
Visit website

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview