Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label in Java. Show all posts
Showing posts with label in Java. Show all posts

Monday 3 August 2015

Iterate over HashMap to get Key and Value in Java , Add records to HashMap


Iterating over HashMap is not same as other collections , It's a bit tricky than normal iteration ;)
See in this code -
How to add values to HashMap ?
and How to iterate over HashMap to get Key and Values?






package client;

import java.util.HashMap;
import java.util.Iterator;

public class IterateHashMap {
    public IterateHashMap() {
        super();
    }

    public static void main(String[] args) {
        HashMap<Integer, String> mapVal = new HashMap<Integer, String>();

        //Add values to Map
        mapVal.put(1, "value 1");
        mapVal.put(2, "value 2");
        mapVal.put(3, "value 3");
        mapVal.put(4, "value 4");

        //Create Iterator from keySet
        Iterator iter = mapVal.keySet().iterator();
        //Iterate over hashmap to get key
        while (iter.hasNext()) {
            int key = (Integer) iter.next();
            //Use this key to find value
            String value = mapVal.get(key).toString();
            System.out.println("**KEY**  " + key + " AND VALUE**  " + value);
        }

    }
}


Cheers :) Happy Learning

Tuesday 7 July 2015

Create shortcut of page on a button click in Oracle ADF using JShortcut library (For windows)

This post is about a small trick to create shortcut file from ADF application
Actually this type of requirement doesn't come in picture when you are working in web application , for web application bookmarks replaces desktop shortcut
Still if you want to do this then you can follow approach mentioned in this post

Creating shortcut programmatically requires access of operating system but you need not to worry about that
There is a java library to do this for you - JShortcut
Download jar files from here..

1. Now first step is to create a fusion web application and add this jar to viewController project


2. Create a page (independent runnable like jspx or jsf not fragments) and drop a button in that
3. Create a managed bean to handle button's action
    Here we will make use of JShellLink class of this library

See what docs says about this -

Provide access to shortcuts (shell links) from Java. The native library (jshortcut.dll) is loaded when JShellLink is first loaded. By default, JShellLink first looks for the native library in the PATH, using System.loadLibrary. If the native library is not found in the PATH, JShellLink then looks through each directory in the CLASSPATH (as determined by the value of the system property java.class.path). If an entry in the CLASSPATH is a jar file, then JShellLink looks for the native library in the directory containing that jar file. The application can override this behavior and force JShellLink to look for the native library in a specific directory by setting the system property JSHORTCUT_HOME to point to that directory. This property must be set before the JShellLink class is loaded. This makes it possible to use this library from a self-extracting jar file. 



4. Get the url of current page
 How to get url of current page in ADF Application?
 (See button action listener code for this )
5. Check code written in managed bean-


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

import javax.servlet.http.HttpServletRequest;

import net.jimmc.jshortcut.JShellLink;

import oracle.adf.controller.ControllerContext;

    JShellLink link;
    String filePath;

    /**Button action listener to create shortcurt of current page on desktop
     * @param actionEvent
     */
    public void createSortcutonDpAction(ActionEvent actionEvent) {
        try {
            //Get url of current ViewPort
            String viewId = ControllerContext.getInstance().getCurrentViewPort().getViewId();
            String viewUrl = ControllerContext.getInstance().getGlobalViewActivityURL(viewId);

            //Get Server Name and Port
            FacesContext fctx = FacesContext.getCurrentInstance();
            HttpServletRequest hsrequest = (HttpServletRequest) fctx.getExternalContext().getRequest();

            String serverName = hsrequest.getServerName();
            int serverPort = hsrequest.getServerPort();

            String runnableUrl = "http://" + serverName + ":" + serverPort + viewUrl;

            //Create Object of shortcurt link
            link = new JShellLink();
            filePath = JShellLink.getDirectory("") + runnableUrl;
            //Set Where you want to create shortcut
            link.setFolder(JShellLink.getDirectory("desktop"));
            //Set shortcut file name
            link.setName("Programmatically Created Shortcut");
            //Use ico file to use as shortcut icon
            link.setIconLocation("C://Users//Admin//Desktop//Jdev_Logo.ico");
            link.setPath(filePath);
            link.save();

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

    }

6.  All done :) , run and check application
Click on button and check on desktop



Same code can be used to create shortcut from pure java application
Cheers :) Happy Learning

Sunday 22 March 2015

Java Database Connectivity- JDBC Tutorial, PreparedStatement, ResultSet

JDBC is java based API or technology to access data from database and use in Java Desktop or Enterprize application. In short we can say JDBC is an interface between Java and Database, using JDBC you can interact with any of database as Oracle, MySQL, Access.
JDBC is released with JDK(Java Development Kit)1.1 on 19 Feb 1997 and It is a part of Java Standard Edition. if you know about DBMS(Database Management Systems) then you should know about Database Drivers, drivers are of 4 types.
  1. Type 1 Driver - JDBC-ODBC bridge
  2. Type 2 Driver - Native-API Driver
  3. Type 3 Driver - Network-Protocol Driver(MiddleWare Driver)
  4. Type 4 Driver - Native-Protocol Driver(Pure Java Driver)-Thin Driver
If you don't have java installed , follow the link below to donload it

JDK1.7- Download jdk1.7
Now we will learn that how to implement Database connection in Java. To start with JDBC you must have a little knowledge of DBMS and SQL(Structured Query Language) to interact with Database
here i will show you that how to connect with Oracle Database
Follow these steps to connect with Oracle Database



1. Load Driver (Thin Driver)

The very first step towards database connection is Loading Driver, as discussed we use pure java driver in JDBC connectivity there are two steps to load driver for connection

A. Using DriverManager class
The syntax is - DriverManager.registerDriver(DriverName);


  1.         try {
  2.             DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  3.            
  4.         } catch (SQLException e) {
  5.         }
  6.        

B. Using Class.Forname class
The syntax is - Class.forName(”DriverName”);

  1.         try {
  2.              Class.forName("oracle.jdbc.driver.OracleDriver");
  3.            
  4.         } catch (SQLException e) {
  5.         }
  6.        


2. Create Connection


Connection interface is inside java.sql package and extends Wrapper interface. now to create Connection we register driver with DriverManager class.
Syntax is- DriverManager.getConnection("url string", "username", "password");

  1.  try {
  2.      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  3.      con=DriverManager.getConnection(
  4.      "jdbc:oracle:thin:@192.168.1.234:1521:XE", "hr", "hr");
  5.  } catch (SQLException e) {
  6.  }

You have to change url string with your ip address and SID according to your database setting

3. Execute PreparedStatement and return Resultset


Now we see that how to execute SQL query using PreparedStatement and store its result in ResultSet object
Here i am getting username and password from LOGIN_DET table (you can use your own query here)

  1.         Connection con;
  2.         try {
  3.             DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  4.             con = DriverManager.getConnection("
  5.            jdbc:oracle:thin:@192.168.1.241:1521:eadf", "hr", "hr");
  6.             PreparedStatement psmt = con.prepareStatement("SELECT * FROM LOGIN_DET");
  7.             ResultSet rs = psmt.executeQuery();
  8.             if (rs.next()) {
  9.                 while (rs.next()) {
  10.                 System.out.println("Username is--" + rs.getString(1)
  11.                + "and Password is-->" + rs.getString(2) +
  12.                "Email Id is--->" + rs.getString("E_ID"));
  13.                 }
  14.             }
  15.             psmt.close();
  16.             con.close();
  17.         } catch (SQLException e) {
  18.         }


This is the brief overview of using JDBC with Oracle Database, For others you have to change only DriverName respectively
Happy Learning :)

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