How to upload file in ADF Mobile

Requirment- How to upload a file in ADF mobile

Solution- ADF Mobile carries with it a similar set of declarative components, but what is missing is an easy way to upload a local file from the mobile device to a remote server. In ADF Faces one would use the component but there is no equivalent present in ADF Mobile, thus leaving the developer no other option than to achieve this programmatically. However, thanks to the fact that ADF Mobile makes use of the PhoneGap (first release)/Apache Cordova (latest version) libraries, using these JavaScript libraries it is possible to implement the file upload facility relatively simply. This document demonstrates a way to upload a local file to a remote server in ADF Mobile.

Setup:
Install JDeveloper 11g Release 2 (version 11.1.2.3 or above) along with Oracle ADF Mobile extension for JDeveloper. This can be done from Help  Check for Updates and then either downloading the extension from Oracle or alternatively installing it from a local copy of the Extension Zip file.
Install Android SDK. Create a virtual device if you would like to deploy on an emulator or else you could also deploy directly to an actual Android device. Configure the ADF Mobile environment for Android from Tools ->Preferences->ADF Mobile-> Platforms.

Steps Involved
We will consider a simple business use case where the user is required to click a photograph with the device camera and upload it to a remote server.
Creating the application and task flow:
Open JDeveloper. Create a new application and select the type as Mobile Application (ADF)

1adf

Click “OK”, name your application (for this example we will name it as “FileTransferDemo”), and then click “Next” on all subsequent dialog windows, accepting all default options, and finally click on “Finish”.

2ad

Create a new feature in the adfmf-feature.xml. Name it as “FileTransfer”. Create a new AMX page under the Contents tab and name it “upload.amx”.

3adf

Create a new JavaScript file, name it “myjs.js”.

4adf

5adf

Include the myjs.js file in the current feature as shown below:

6adf

Now edit the JavaScript file as follows:

(function () {
    if (!window.application)
        window.application = {
        };

    snapUpload = function () {
        // take picture
        navigator.camera.getPicture(uploadPhoto, function (message) {
            alert("get picture failed");
        },
        {
            quality : 50, destinationType : navigator.camera.DestinationType.FILE_URI, 
  sourceType : navigator.camera.PictureSourceType.CAMERA
        });
    };

    function uploadPhoto(imageURI) {
        var options = new FileUploadOptions();
        options.fileKey = "file";
        // extract filename from URI
        options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
        options.mimeType = "image/jpeg";
        var params = {
        };
        options.params = params;
        var ft = new FileTransfer();
        // upload to server
        ft.upload(imageURI, encodeURI("http://10.87.194.23:7101/FileUpload-ViewController-
context-root/upload.jsp"), success, fail, options);
    }

    function success(response) {
        alert("File uploaded successfully");
        // log response
        console.log("Code = " + response.responseCode);
        console.log("Response = " + response.response);
        console.log("Sent = " + response.bytesSent);
    }

    function fail(error) {
        alert("An error has occurred: Code = " + error.code);
        // log error
        console.log("Upload error source " + error.source);
        console.log("Upload error target " + error.target);
    }
})();

Now we will add code in the AMX page that will call the JavaScript functions. First create a bean with a method that will call the JavaScript function snapUpload, and register it as a managed bean in the adf-mobile-config.xml file as shown:

7adf

package mobile; 
import oracle.adfmf.amx.event.ActionEvent;
import oracle.adfmf.framework.api.AdfmfContainerUtilities;

public class MyBean {
    
    public void snapUpload(ActionEvent ae) {	// action listener method
        // call JavaScript function to take picture and upload to server
        AdfmfContainerUtilities.invokeContainerJavaScriptFunction("FileTransfer", 
"snapUpload", new Object [] {});
    }
}

Edit the upload.amx page as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<amx:view xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amx="http://xmlns.oracle.com/adf/mf/amx"
          xmlns:dvtm="http://xmlns.oracle.com/adf/mf/amx/dvt">
  <amx:panelPage id="pp1">
    <amx:facet name="header">
      <amx:outputText value="Image Upload" id="ot1"/>
    </amx:facet>
    <amx:commandButton text="Upload Photo" id="cb1" actionListener="#{pageFlowScope.myBean.snapUpload}"/>
    </amx:panelPage>
</amx:view>

Basically, we are associating an action listener with a button that calls the JavaScript function from our Java code.
The server must be up and running for the file upload to work. The URL provided must point to a page that accepts a file whose contents are sent in the body of a POST request. In our case, we are using a JSP page, but any other web technology may be used like PHP, ASP.NET etc.
The following code lists our simple upload.jsp page:

<%@ page language="java" import="java.io.*" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%        
// get the content type information from JSP Request Header
String contentType = request.getContentType();        
// content type should not be null and data passed from mulitpart/form-data is greater than // or equal to 0
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
	DataInputStream in = new DataInputStream(request.getInputStream());
	// get length of the data content
	int formDataLength = request.getContentLength();
	byte dataBytes[] = new byte[formDataLength]; 
	int byteRead = 0;
	int totalBytesRead = 0;
	// read bytes while available
	while (totalBytesRead < formDataLength) {
		byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
		totalBytesRead += byteRead;
	}                                        
	String file = new String(dataBytes);                
	// get filename for saving                
	String saveFile = file.substring(file.indexOf("filename=\"") + 10);                
	saveFile = saveFile.substring(0, saveFile.indexOf("\n"));                
	saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));                
	int lastIndex = contentType.lastIndexOf("=");
          // get boundary delimiter from header               
	String boundary = contentType.substring(lastIndex + 1, contentType.length());                
	int pos;                
	// locate start and end positions of file data within request                 
	pos = file.indexOf("filename=\"");                
	pos = file.indexOf("\n", pos) + 1;                
	pos = file.indexOf("\n", pos) + 1;                
	pos = file.indexOf("\n", pos) + 1;                
	int boundaryLocation = file.indexOf(boundary, pos) - 4;                
	int startPos = ((file.substring(0, pos)).getBytes()).length;                
	int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
                
	// create a new file with the same name as source and copy the file contents to it                
	FileOutputStream fout = new FileOutputStream(saveFile);                
	fout.write(dataBytes, startPos, (endPos - startPos));                
	fout.flush();                
	fout.close();

%>
<br></br>
<table border="2">
    <tr>
        <td>
            <b>You have successfully uploaded the file by the name of:</b>
            <%=new File(saveFile).getAbsolutePath()%>
        </td>
    </tr>
</table>
<%
} // end if
%>

Finally, deploy the application to an Android device or emulator using the Application  Deploy menu.
Tapping on the “Upload Photo” button opens up the device camera using which you can snap a picture.
8adf

9adf

After you have clicked the photo the file is uploaded to the server. Upon successful upload the user is alerted accordingly.

10adf

Looking at the log file “FileTransferDemo.txt” under the sdcard root you can see the response code, the HTML response from the server and the number of bytes transferred has been logged. You can view the log file by typing “file:///sdcard/FileTransferDemo.txt” in the address bar of the device browser.

Notes
Using PhoneGap/Apache Cordova it is possible to upload any kind of file by simply changing the URI and the MIME type. For a better user experience we could integrate a file browser to locate and select our desired file from the device’s local file system. For a demonstration on using a filesystem browser in ADF
At the server side we have used a very simple implementation of an upload page. However, depending on requirements this upload page might need to be able to read one or more parameters and involve other complexities. Typically, if we are leveraging Apache and JEE technology to host our server it is often a popular choice to use Apache HttpClient or HttpComponents libraries.

References

1. Oracle Fusion Middleware Mobile Developer’s Guide for Oracle Application Development Framework (http://docs.oracle.com/cd/E35521_01/doc.111230/e24475/toc.htm)
2. PhoneGap API Documentation (http://docs.phonegap.com/en/1.0.0/index.html)
3. Uploading Single File by Using JSP (http://www.roseindia.net/jsp/file_upload/Sinle_upload.xhtml.shtml)

Happy ADF Mobile learning with Vinay Kumar in techartifact…..

Setting Styles & Formula in excel file using Apache POI

Requirement – Setting styles on excel cells

Solutions– You can set FONT,Color, Bold etc.Use cell.setCellStyle(style) method.

Following is code for setting styles

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Style example");
<strong> //Example 1 of setting styles in cell</strong>
HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName(HSSFFont.FONT_ARIAL); 
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
 
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Setting text in BOLD and in Arial font");
cell.setCellStyle(style);
 
<strong>  //Example 2 of setting styles in cell</strong>
font = workbook.createFont();
font .setItalic(true);  // setting cell value as italic
font setFontHeightInPoints((short) 12);   //setting font height.
font.setColor(HSSFColor.GREEN.index);  // setting color as green
style = workbook.createCellStyle();
style.setFont(font);
 
row = sheet.createRow(1);
cell = row.createCell(0);
cell.setCellValue("Setting text in italic & green");
cell.setCellStyle(style);
 
try {
    FileOutputStream out = new FileOutputStream(new File("C:\\Vinaystyle.xls"));
    workbook.write(out);
    out.close();
    System.out.println("Excel written successfully..");
     
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}


You can also set the background color for the rows as well in sheet

  // Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(CellStyle.BIG_SPOTS);
row.setRowStyle(style);

Setting Formula in Excel –

    Row row= sheet.createRow(1);
    row.createCell(0).setCellValue(100);
    rpw.createCell(1).setCellValue(200);
    row.createCell(2).setCellValue(300);
    row.createCell(3).setCellFormula("SUM(A1:A4)");
  or 
    cell.setCellFormula("A2*B3*C4")
 

For evaluating formula you can use –

FormulaEvaluator evaluator = 
workbook.getCreationHelper().createFormulaEvaluator(); 

evaluateFormulaCell(Cell cell) will check to see if the supplied cell is a formula cell. If it isn’t, then no changes will be made to it. If it is, then the formula is evaluated. The value for the formula is saved alongside it, to be displayed in excel. The formula remains in the cell, just with a new value.

Happy coding with Vinay in techartifact