Please disable your adblock and script blockers to view this page

Search this blog

Thursday 27 June 2013

Using af:poll to refresh and push data in page and databound table in ADF

Poll component delivers poll event to server at fixed intervals, we use poll in adf as an alternative of ADS (Active Data Service), this is very simple example of pushing data to page at some fix interval.
Basically af:poll component push data to UI from server.

  • This example contains a page with an af:table binded to Department VO, and I have used a poll component to refresh table periodically.

  • and defined pollListener on af:poll component that sends request to server in every 4 sec, and table get refreshed







  • Other approach to actively push data is ADS, but af:poll is still in use , to refresh table i have written in poll listener

  •         AppModuleAMImpl am = (AppModuleAMImpl)resolvElDC("AppModuleAMDataControl");
    
            ViewObject vo = am.getDepartment1();
            vo.executeQuery();
            i = i + 1;
            this.refreshInfo = "Data Reloaded-" + i+"  Total Row-->"+vo.getRowCount();
            AdfFacesContext.getCurrentInstance().addPartialTarget(refrshMsgBind);
    

  • See the jspx page source code-

  • <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
        <jsp:directive.page contentType="text/html;charset=UTF-8"/>
        <f:view>
            <af:document title="activePushing.jspx" id="d1">
                <af:messages id="m1"/>
                <af:form id="f1">
                    <af:panelBox id="pb1" showDisclosure="false" text="Active Data Pushing">
                        <f:facet name="toolbar">
                            <af:activeOutputText value="#{ActiveDataPushing.refreshInfo}" id="aot1"
                                                 inlineStyle="font-weight:bold;color:red;"
                                                 binding="#{ActiveDataPushing.refrshMsgBind}"/>
                        </f:facet>
                        <af:table value="#{bindings.Department1.collectionModel}" var="row"
                                  rows="#{bindings.Department1.rangeSize}"
                                  emptyText="#{bindings.Department1.viewable ? 'No data to display.' : 'Access Denied.'}"
                                  fetchSize="#{bindings.Department1.rangeSize}" rowBandingInterval="1"
                                  selectedRowKeys="#{bindings.Department1.collectionModel.selectedRow}"
                                  selectionListener="#{bindings.Department1.collectionModel.makeCurrent}"
                                  rowSelection="single" id="t1" styleClass="AFStretchWidth" contentDelivery="immediate">
                            <af:column sortProperty="#{bindings.Department1.hints.DepartmentId.name}" sortable="true"
                                       headerText="#{bindings.Department1.hints.DepartmentId.label}" id="c1" width="103">
                                <af:inputText value="#{row.bindings.DepartmentId.inputValue}"
                                              label="#{bindings.Department1.hints.DepartmentId.label}"
                                              required="#{bindings.Department1.hints.DepartmentId.mandatory}"
                                              columns="#{bindings.Department1.hints.DepartmentId.displayWidth}"
                                              maximumLength="#{bindings.Department1.hints.DepartmentId.precision}"
                                              shortDesc="#{bindings.Department1.hints.DepartmentId.tooltip}" id="it1"
                                              readOnly="true">
                                    <f:validator binding="#{row.bindings.DepartmentId.validator}"/>
                                    <af:convertNumber groupingUsed="false"
                                                      pattern="#{bindings.Department1.hints.DepartmentId.format}"/>
                                </af:inputText>
                            </af:column>
                            <af:column sortProperty="#{bindings.Department1.hints.DepartmentName.name}" sortable="true"
                                       headerText="#{bindings.Department1.hints.DepartmentName.label}" id="c2" width="107">
                                <af:inputText value="#{row.bindings.DepartmentName.inputValue}"
                                              label="#{bindings.Department1.hints.DepartmentName.label}"
                                              required="#{bindings.Department1.hints.DepartmentName.mandatory}"
                                              columns="#{bindings.Department1.hints.DepartmentName.displayWidth}"
                                              maximumLength="#{bindings.Department1.hints.DepartmentName.precision}"
                                              shortDesc="#{bindings.Department1.hints.DepartmentName.tooltip}" id="it2"
                                              readOnly="true">
                                    <f:validator binding="#{row.bindings.DepartmentName.validator}"/>
                                </af:inputText>
                            </af:column>
                            <af:column sortProperty="#{bindings.Department1.hints.ManagerId.name}" sortable="true"
                                       headerText="#{bindings.Department1.hints.ManagerId.label}" id="c3" width="105">
                                <af:inputText value="#{row.bindings.ManagerId.inputValue}"
                                              label="#{bindings.Department1.hints.ManagerId.label}"
                                              required="#{bindings.Department1.hints.ManagerId.mandatory}"
                                              columns="#{bindings.Department1.hints.ManagerId.displayWidth}"
                                              maximumLength="#{bindings.Department1.hints.ManagerId.precision}"
                                              shortDesc="#{bindings.Department1.hints.ManagerId.tooltip}" id="it3"
                                              readOnly="true">
                                    <f:validator binding="#{row.bindings.ManagerId.validator}"/>
                                    <af:convertNumber groupingUsed="false"
                                                      pattern="#{bindings.Department1.hints.ManagerId.format}"/>
                                </af:inputText>
                            </af:column>
                            <af:column sortProperty="#{bindings.Department1.hints.LocationId.name}" sortable="true"
                                       headerText="#{bindings.Department1.hints.LocationId.label}" id="c4" width="105">
                                <af:inputText value="#{row.bindings.LocationId.inputValue}"
                                              label="#{bindings.Department1.hints.LocationId.label}"
                                              required="#{bindings.Department1.hints.LocationId.mandatory}"
                                              columns="#{bindings.Department1.hints.LocationId.displayWidth}"
                                              maximumLength="#{bindings.Department1.hints.LocationId.precision}"
                                              shortDesc="#{bindings.Department1.hints.LocationId.tooltip}" id="it4"
                                              readOnly="true">
                                    <f:validator binding="#{row.bindings.LocationId.validator}"/>
                                    <af:convertNumber groupingUsed="false"
                                                      pattern="#{bindings.Department1.hints.LocationId.format}"/>
                                </af:inputText>
                            </af:column>
                        </af:table>
                        <af:poll id="p1" pollListener="#{ActiveDataPushing.pollListenerActive}" interval="4000"
                                 timeout="5000"/>
                    </af:panelBox>
                </af:form>
            </af:document>
        </f:view>
    </jsp:root>
    

  • Run your application, and do changes from Database and see updated UI at every 4 sec. :-)
 Reloading- 26th times-
 Reloading- 33th times-
 Reloading- 40th times-


Tuesday 25 June 2013

Conditional Execution of Model (EO) level Validation- Oracle ADF

You all know about ADF model level validation , we can apply variety of validation on model (Entity Object), as for length, compare, key, regular expression, script and unique key etc.

I am not going to describe whole process for model layer validation, for detailed tutorial on EO level validation see -Dynamic (parameterize) model level validation using message token
Now see how we can execute these validation conditionally -

  • When we apply unique key validation on Entity Object- this window appears-
  • Now go to Validation Execution and write your condition in given box for that you want to execute validation

  • Now go to Failure Handling tab and write your failure handling message, and you are done




  • Now run your application and see how validation executes for your condition
  • this functionality is really helpful and sometimes avoids writing lot of managed bean code

Thursday 20 June 2013

Bing language Translation API integration with Java- microsoft-translator-java-api

Google Translation is very popular and widely used for language translation as it is now paid service,
so i  came to know about Microsoft Translator (Bing Translator), it is providing free API up to 2000,000 character/Month to translate.

Key features and point-
  • Provides java wrapper around microsoft translator (Bing Translator)
  • Developed as alternative of Google Translator
  • Follow coding standard, naming, functionality and usage patterns of widely used google translation API
This is very very simple to use -Follow steps




  • First Download JAR for API- http://code.google.com/p/microsoft-translator-java-api/  with all dependencies
  • Now obtain client secret key and client id in order to access API , see this http://msdn.microsoft.com/en-us/library/hh454950.aspx
  • After this create a simple java class and just write this code-
  • Don't forget to add JAR in your project's class path

  • package translation;
    
    import com.memetix.mst.language.Language;
    import com.memetix.mst.translate.Translate;
    
    public class MicrosoftTranslator {
        public static void main(String[] args) throws Exception {
            
            Translate.setClientId("secret client id");
            Translate.setClientSecret("secret key");
    
    
            String translatedText = Translate.execute("hello", Language.ENGLISH, Language.FRENCH);
            System.out.println(translatedText);
        }
    }
    

  • Enter your key and id in code, you can change language with available list, and run this code
  • To use this in web application , you must handle SSL certificate

Sunday 16 June 2013

Using Java API for getting Weather information in Oracle ADF-wunderground-core

hello everyone, here is nice tutorial for all ADF techies-
i have developed an application in ADF that retrieves weather information of a country's weather stations.
as-temperature, humidity, dew, rain rate, wind speed etc using wunderground-core 
API . This API fetch weather data for a weater station by given month and year or data for all the stations of a country.

Feature of this wunderground-core-
  1. Very simple to use
  2. Date Listener support
  3. Fetch weather data for all stations of country
  4. can be used with desktop or web application
  5. Ajax supported
  6. Real Time weather values
Snap-
 Change Country-

and download jar distribution with all dependencies

  • Now start , create a fusion web application and add jar file to  classpath
  • Now create a bounded taskflow and a .jsff page inside this , now see the simple code to get all weather station of acountry and their weather data

  •         /*  create an instance of WeatherStationService */
            WeatherStationService weatherStationService = new WeatherStationService();
    
            /*  find all weather stations */
            List<WeatherStation> stations = weatherStationService.findAllWeatherStationsByCountry("INDIA");
    
            
            for (WeatherStation weatherStation : stations) {
                System.out.println(weatherStation.getStationId() + "\t" + "\t" + weatherStation.getCity() + "\t" +
                                   weatherStation.getCountry());
    
                HttpDataReaderService dataReader = new HttpDataReaderService();
                dataReader.setWeatherStation(weatherStation);
                DataSet current = dataReader.getCurrentData();
    
                System.out.println(current.getDateTime() + "Temperature- " + current.getTemperature() + "Humidity-" +
                                   current.getHumidity());
    

  • I have used this code on my af:commandButton for getting weather data, and a table on page to show this information on page using list (arrayList) , rest is same and simple like other ADF Application
  • Download Sample Application and see it, you will also learn that how to show a table using List(Java) Sample ADF Application




  • See source of .jsff page for tables'use and values-

  • <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:af="http://xmlns.oracle.com/adf/faces/rich"
              xmlns:f="http://java.sun.com/jsf/core">
        <af:panelBox text="Weather Report App-www.javadrive.co.in" id="pb1" showDisclosure="false">
            <f:facet name="toolbar"/>
            <af:panelFormLayout id="pfl1">
                <af:inputText label="Country Name" id="it1"
                              contentStyle="text-transform:upperCase;color:green;font-weight:bold;"
                              binding="#{WeatherReportBean.cntryNameBind}"/>
                <af:commandButton text="Get Report" id="cb1" actionListener="#{WeatherReportBean.getWeatherReportButton}"
                                  inlineStyle="font-weight:bold;"/>
            </af:panelFormLayout>
            <af:popup childCreation="deferred" autoCancel="disabled" id="p1">
                <af:dialog id="d1" title="User-User4" type="none">
                    <f:facet name="buttonBar"/>
                    <af:message id="m1" message="You are not authorize to make an order of 25000, your limit is 20000 !!!"
                                messageType="error"/>
                </af:dialog>
            </af:popup>
            <af:panelGroupLayout id="pgl1" layout="horizontal">
                <af:table var="row" rowBandingInterval="1" id="t1" value="#{WeatherReportBean.stations}"
                          partialTriggers="::cb1" contentDelivery="immediate" width="500">
                    <af:column sortable="false" headerText="Country" id="c3">
                        <af:spacer width="10" height="10" id="s2"/>
                        <af:outputText value="#{row.country}" id="ot3" inlineStyle="font-weight:bold;color:red;"/>
                        <af:spacer width="10" height="10" id="s1"/>
                    </af:column>
                    <af:column sortable="false" headerText="Locality" id="c4" width="150">
                        <af:outputText value="#{row.neighborhood}" id="ot4"/>
                    </af:column>
                    <af:column sortable="false" headerText="City" id="c2">
                        <af:outputText value="#{row.city}" id="ot2" inlineStyle="font-weight:bold;color:darkgreen;"/>
                    </af:column>
                    <af:column sortable="false" headerText="Station Id" id="c1">
                        <af:outputText value="#{row.stationId}" id="ot1" inlineStyle="font-weight:bold;color:darkblue;"/>
                    </af:column>
                </af:table>
                <af:table value="#{WeatherReportBean.reportL}" var="row" rowBandingInterval="1" id="t2"
                          contentDelivery="immediate" partialTriggers="::t1 ::cb1" styleClass="AFStretchWidth" width="800">
                    <af:column sortable="false" headerText="Date" align="start" id="c5">
                        <af:spacer width="10" height="10" id="s4"/>
                        <af:outputText value="#{row.currDate}" id="ot5" inlineStyle="font-weight:bold;">
                            <af:convertDateTime pattern="dd/MMM/yyyy"/>
                        </af:outputText>
                        <af:spacer width="10" height="10" id="s3"/>
                    </af:column>
                    <af:column sortable="false" headerText="Temperature" align="end" id="c6" width="70">
                        <af:outputText value="#{row.temp} C" id="ot6" inlineStyle="font-weight:bold;color:teal;"/>
                    </af:column>
                    <af:column id="c7" headerText="Humidity" align="right" width="70">
                        <af:outputText value="#{row.humid}" id="ot7" inlineStyle="font-weight:bold;color:orange;"/>
                    </af:column>
                    <af:column id="c8" headerText="Dew Point" align="right" width="70">
                        <af:outputText value="#{row.dewR}" id="ot8" inlineStyle="font-weight:bold;color:green;"/>
                    </af:column>
                    <af:column id="c9" headerText="Wind Direction" align="right" width="70">
                        <af:outputText value="#{row.windDirec}" id="ot9" inlineStyle="font-weight:bold; color:Olive;"/>
                    </af:column>
                    <af:column id="c10" headerText="Wind Speed (Km/H)" align="right">
                        <af:outputText value="#{row.windSpd}" id="ot10"
                                       inlineStyle="color:ActiveCaption;font-weight:bold;"/>
                    </af:column>
                    <af:column id="c11" headerText="Rain Rate" align="right" width="70">
                        <af:outputText value="#{row.rainRt}" id="ot11" inlineStyle="font-weight:bold;color:maroon;"/>
                    </af:column>
                    <af:column id="c12">
                        <af:image shortDesc="Weather" id="i1"
                                  source="#{row.temp >35 ? resource['images:sun.png'] : resource['images:sun_slush.png']}"/>
                    </af:column>
                </af:table>
            </af:panelGroupLayout>
        </af:panelBox>
    </jsp:root>
    

  • And see managed bean code to populate data in tables on page, other than manged bean i have used a java bean to populate value in list and then in table
  • WeatherReportBean.java

  • package weather.view.bean;
    
    import de.mbenning.weather.wunderground.api.domain.DataSet;
    import de.mbenning.weather.wunderground.api.domain.WeatherStation;
    import de.mbenning.weather.wunderground.impl.services.HttpDataReaderService;
    import de.mbenning.weather.wunderground.impl.services.WeatherStationService;
    
    import java.io.Serializable;
    
    import java.sql.SQLException;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.faces.event.ActionEvent;
    
    import oracle.adf.view.rich.component.rich.input.RichInputText;
    
    import oracle.jbo.domain.Date;
    
    public class WeatherReportBean implements Serializable {
        private RichInputText cntryNameBind;
    
        public WeatherReportBean() {
        }
        WeatherStationService weatherStationService = new WeatherStationService();
    
        List<WeatherStation> stations;
        List<Report> reportL;
    
    
        public void getWeatherReportButton(ActionEvent actionEvent) throws SQLException {
            if (cntryNameBind.getValue() != null) {
                String cntryName = cntryNameBind.getValue().toString();
    
                stations = weatherStationService.findAllWeatherStationsByCountry(cntryName);
                reportL = new ArrayList<Report>(50);
                for (WeatherStation weatherStation : stations) {
    
                    HttpDataReaderService dataReader = new HttpDataReaderService();
                    dataReader.setWeatherStation(weatherStation);
                    DataSet current = dataReader.getCurrentData();
    
                    java.util.Date b = new java.util.Date();
                    Double c = new Double(0);
                    Integer humidity = 0;
                    Double dew = new Double(0);
                    String windDir = "";
                    Double windSp = new Double(0);
                    Double rainRate = new Double(0);
    
                    if (current != null) {
                        if (current.getDateTime() != null) {
                            b = current.getDateTime();
                            c = current.getTemperature();
                            humidity = current.getHumidity();
                            dew = current.getDewPoint();
                            windDir = current.getWindDirection();
                            windSp = current.getWindSpeedKmh();
                            rainRate = current.getRainRateHourlyMm();
                            System.out.println("Humidity is-->" + current.getHumidity() + "dew point-->" +
                                               current.getDewPoint() + "wind -->" + current.getWindDirection() +
                                               "speed--" + current.getWindSpeedKmh());
    
    
                        }
                    }
    
                    reportL.add(new Report(b, c, humidity, dew, windDir, windSp, rainRate));
    
                }
    
    
            }
    
        }
    
        public void setStations(List<WeatherStation> stations) {
            this.stations = stations;
        }
    
        public List<WeatherStation> getStations() {
            return stations;
        }
    
        public void setReportL(List<Report> reportL) {
            this.reportL = reportL;
        }
    
        public List<Report> getReportL() {
            return reportL;
        }
    
        public void setCntryNameBind(RichInputText cntryNameBind) {
            this.cntryNameBind = cntryNameBind;
        }
    
        public RichInputText getCntryNameBind() {
            return cntryNameBind;
        }
    }
    

  • Report.java- bean class to populate list

  • package weather.view.bean;
    
    import java.util.Date;
    
    public class Report {
    
        private Date CurrDate;
        private double temp;
        Integer humid;
        Double dewR;
        String windDirec;
        Double windSpd;
        Double rainRt;
    
        public Report(Date date, Double double1, Integer hum, Double de, String windD, Double windS, Double Rain) {
            System.out.println("date is-->" + date + "and temp is-->" + double1);
    
            this.CurrDate = date;
            setTemp(double1);
            this.humid = hum;
            this.dewR = de;
            this.windDirec = windD;
            this.windSpd = windS;
            this.rainRt = Rain;
    
    
        }
    
    
        public void setCurrDate(Date CurrDate) {
            this.CurrDate = CurrDate;
        }
    
        public Date getCurrDate() {
            return CurrDate;
        }
    
        public void setTemp(double temp) {
            this.temp = temp;
        }
    
        public double getTemp() {
            return temp;
        }
    
        public void setHumid(Integer humid) {
            this.humid = humid;
        }
    
        public Integer getHumid() {
            return humid;
        }
    
        public void setDewR(Double dewR) {
            this.dewR = dewR;
        }
    
        public Double getDewR() {
            return dewR;
        }
    
        public void setWindDirec(String windDirec) {
            this.windDirec = windDirec;
        }
    
        public String getWindDirec() {
            return windDirec;
        }
    
        public void setWindSpd(Double windSpd) {
            this.windSpd = windSpd;
        }
    
        public Double getWindSpd() {
            return windSpd;
        }
    
        public void setRainRt(Double rainRt) {
            this.rainRt = rainRt;
        }
    
        public Double getRainRt() {
            return rainRt;
        }
    }
    

Wednesday 5 June 2013

Download file from url using Oracle ADF & Java- Download Manager

In this tutorial i will show you how to download a file from its url (web)-
as- http://www.tutorialspoint.com/java/java_tutorial.pdf
This will work as a simple download manager, you can add file url to download it and save it.
This tutorial makes use of FileHandling and java.net.URL class in java.

  • User Interface is very simple to design as it have only one input text and one button, so create a fusion web application , and a bounded taskflow with a page fragment in it
  • Now drag a Input text to enter url and a button to perform action on it from Componenet palette .
  • Bind input text to bean to get its value from page

  •  private RichInputText fileUrlBind;
    
        public void setFileUrlBind(RichInputText fileUrlBind) {
            this.fileUrlBind = fileUrlBind;
        }
    
        public RichInputText getFileUrlBind() {
            return fileUrlBind;
        }
    
  • Now create actionListener to managed bean and write code for downloading file from given url- see code

  •     public void DownloadFileButton(ActionEvent actionEvent) {
            try {
                if (fileUrlBind.getValue() != null) {
                    String fileUrl = fileUrlBind.getValue().toString();
                    if (fileUrl.startsWith("http://")) {
                        String msgNm = fileUrl.substring(7);
    
                        cnctmsgBind.setValue("Connecting to " + msgNm + "....");
    
                        URL url = new URL(fileUrl);
                        url.openConnection();
                        InputStream reader = url.openStream();
    
    
                        FileOutputStream writer =
                            new FileOutputStream("C:/javadrive." + fileUrl.substring(fileUrl.lastIndexOf(".")));
                        byte[] buffer = new byte[153600];
                        int totalBytesRead = 0;
                        int bytesRead = 0;
    
                       
                        dwnldMsgBind.setValue("Reading file 150KB blocks at a time");
                        while ((bytesRead = reader.read(buffer)) > 0) {
                            writer.write(buffer, 0, bytesRead);
                            buffer = new byte[153600];
                            totalBytesRead += bytesRead;
                        }
                     
                        alerMsgBind.setValue("File is downloaded successfully, look at your c drive :-)");
                        writer.close();
                        reader.close();
                    } else {
                        FacesMessage errMsg = new FacesMessage("Something went wrong");
                        errMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        errMsg.setDetail("Example- http://www.javadrive.co.in/java.pdf");
                        FacesContext context = FacesContext.getCurrentInstance();
                        context.addMessage(fileUrlBind.getClientId(), errMsg);
                    }
                }
            } catch (MalformedURLException e) {
                FacesMessage errMsg = new FacesMessage("Something went wrong");
                errMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, errMsg);
                e.printStackTrace();
            } catch (IOException e) {
                FacesMessage errMsg = new FacesMessage("Something went wrong");
                errMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, errMsg);
                e.printStackTrace();
            }
    
    
        }
    
    




  • Now Run your application and see downloaded file in your c drive as path is hard coded in bean


  •  See your downloaded file in c drive