Please disable your adblock and script blockers to view this page

Search this blog

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

Wednesday 21 November 2018

Read text file in Java using FileInputStream


Recently I have seen some questions about reading text file content on the OTN forum, though it is a very simple task still some find it confusing. That’s why here I am showing how to read text files in java using FileInputStream


This is a sample text file


and here goes the java code to read text file using FileInputStream

  1. package client;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. public class ReadFileJava {
  6. public ReadFileJava() {
  7. super();
  8. }
  9. public static void main(String[] args) {
  10. // Absolute path of file that you want to read
  11. File f = new File("D:/sampleFile.txt");
  12. FileInputStream fis = null;
  13. try {
  14. fis = new FileInputStream(f);
  15. int data;
  16. //Iterate over file content
  17. while ((data = fis.read()) != -1) {
  18. System.out.print((char) data);
  19. }
  20. } catch (IOException ioe) {
  21. ioe.printStackTrace();
  22. } finally {
  23. try {
  24. if (fis != null)
  25. fis.close();
  26. } catch (IOException ioe) {
  27. ioe.printStackTrace();
  28. }
  29. }
  30. }
  31. }

Run this code

And output is


Cheers ðŸ™‚ Happy Learning

Saturday 3 June 2017

Access JAX-WS WebService from Java Class using Web Service Proxy in Jdeveloper


Web Service proxy class is a way to communicate with XML-based WebService using SOAP format,
In short, we can use service proxy class at client to access WebService

In JDeveloper IDE we can easily create client proxy class for WebService, Here in this post I am creating client proxy class to access a JAX-WS web service that I have created in previous blog post

Create POJO based JAX-WS WebService easily with Jdeveloper 12.1.3

Let's see how to implement this


Wednesday 15 March 2017

Fetch Tweets of a User using Twitter4J API and show in af:table in ADF & Java


In the previous blogs we learned about posting tweets on twitter timeline using Twitter4J API and sending direct meaages to followers using same API

This post is next in the series and about fetching a user tweets and showing in ADF Table , For this requirement we need to use same Consumer Key+ Secret and Access Token+Secret (Refer previous posts for this)

And In same way after authentication we can fetch a user tweets by using it's twitter handle. So for this requirement I have added a button to fetch tweets and a POJO based table to show fetched tweets in page

See the code to fetch tweets using user's twitter handle and it's retweets and favourites count, We can get tweets by passing page number as parameter and it returns a list of tweets


Thursday 9 March 2017

Send Direct Message to followers using Twiter4J API in Oracle ADF and Java


My previous post was about tweeting using Twitter4J API from Oracle ADF Application . Twitter4J is a Java API that simplifies accessting twitter features in our application easily

In this I am going to show how to send DM (Direct Message) to anyone using their twitter handle and for this we need to use same consumer key, secret and access token, secret (How to access all these is described in previous post)

Tuesday 7 March 2017

Post to twitter using Twitter4J API in Oracle ADF and Java


Hello All

In this post I am talking about how to post a tweet on your twitter timeline using Twitter4J Java API in your Oracle ADF Application
Using this API makes the process very simple , For accessing twitter we need Twitter API keys, It is called Consumer Key and Access Token

For this you need a twitter account and then follow these steps

Wednesday 8 February 2017

Get Facebook profile detail using restfb Graph API in Java & ADF


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

Wednesday 1 February 2017

Export ViewObject data to PDF file using Apache PDFBox

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

Thursday 5 January 2017

Get Installed Printer List using Java, Print a file with default Printer




This post shows that how can we get installed printers list using PrintServiceLookup class


Implementations of this class provide lookup services for print services


Monday 23 May 2016

Execute batch file from Java Code using Runtime class

We can call any exe file from Java code using Runtime class, Runtime class extends Object class and introduced in JDK1.0

What docs says-

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
An application cannot create its own instance of this class.

Here we will see how to execute .exe and .bat file from javacode, for executable files we just pass file path and Runtime class will invoke it. But for batch file we have to first open supporting application i;e Command Promt and then provide path for batch file

See Java Programs for both case:

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

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 :)

Monday 20 October 2014

Send SMS from Oracle ADF Application using Horizon SMS API

This post is about using SMS API to send SMS text to mobile from an Oracle ADF application
there are various SMS Gateway to send SMS using java and all java API's can be used with Oracle ADF

here i am using sms horizon (a bulk sms provider in india) see this SMS API integration with Java and Oracle ADF, follow the steps
First create an account with SMS Horizon - http://www.smshorizon.in/ or User Login- SMS Horizon

you can purchase a trial package to test your code, they provide 200 sms for Rs 25 only. So After purchasing trial pack you will get and API Key and username



Login to your account and see your dashboard-



you will see your API key in this type of box-



Now first step is complete and second and last step is implement code in your managed bean
you can find Sample API files (code to use API in Java, C#, PHP etc) from there

So for this i have a created a Fusion Web Application and a page in it


created a managed bean and actionListener for this Send button
this url is used to send sms and it returns msgId of sent message

http://smshorizon.co.in/api/sendsms.php?user=******&apikey=*****8&mobile=xxyy&message=xxyy&senderid=xxyy&type=txt


See the ActionListener code -


    /**Method to send SMS using SMS Horizon API
     * @param actionEvent
     */
    public void sendSMSAction(ActionEvent actionEvent) {
        // get mobile number value using component binding
        if (mobNoBind.getValue() != null) {
            // Replace with your username
            String user = "userId";

            // Replace with your API KEY (We have sent API KEY on activation email, also available on panel)
            String apikey = "your_api_key";

            // Replace with the destination mobile Number to which you want to send sms
            String mobile = mobNoBind.getValue().toString();

            // Replace if you have your own Sender ID, else donot change
            String senderid = "WEBSMS";

            // Replace with your Message content
            String message = "SMS API -Oracle ADF";

            // For Plain Text, use "txt" ; for Unicode symbols or regional Languages like hindi/tamil/kannada use "uni"
            String type = "txt";

            //Prepare Url
            URLConnection myURLConnection = null;
            URL myURL = null;
            BufferedReader reader = null;

            //encoding message
            String encoded_message = URLEncoder.encode(message);

            //Send SMS API
            String mainUrl = "http://smshorizon.co.in/api/sendsms.php?";

            //Prepare parameter string
            StringBuilder sbPostData = new StringBuilder(mainUrl);
            sbPostData.append("user=" + user);
            sbPostData.append("&apikey=" + apikey);
            sbPostData.append("&message=" + encoded_message);
            sbPostData.append("&mobile=" + mobile);
            sbPostData.append("&senderid=" + senderid);
            sbPostData.append("&type=" + type);

            //final string
            mainUrl = sbPostData.toString();
            System.out.println("URL to Send SMS-" + mainUrl);
            try {
                //prepare connection
                myURL = new URL(mainUrl);
                myURLConnection = myURL.openConnection();
                myURLConnection.connect();
                reader = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
                //reading response
                String response;
                while ((response = reader.readLine()) != null) {
                    //print response
                    System.out.println(response);
                }
                System.out.println(response);
                //finally close connection
                reader.close();


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

    public void setMobNoBind(RichInputText mobNoBind) {
        this.mobNoBind = mobNoBind;
    }

    public RichInputText getMobNoBind() {
        return mobNoBind;
    }

you can check status of each SMS in your account that it is delivered of not, other than this you can also check status of msg in your code also using this url

http://smshorizon.co.in/api/status.php?user=*****&apikey=*********&msgid=xxyy

pass msgId returned from previous url and it will return you status of message as- PENDING , DELIVERED etc
see imports used in code-


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.faces.event.ActionEvent;

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

Thanks :) Happy Learning

Friday 23 May 2014

Reading html source of a webpage (url) using Oracle ADF (af:richTextEditor) & Java

This post is about a common question asked in java-

How to read page source of a website ? or how to get html source of an url?

so for that there is a simple piece of code to read html source of a webpage using it's url, and i have added  af:richTextEditor (ADF Faces component for ricj text formatting) to show html form of url source

  • I have a page with one input text to capture url entered by user, a button to fetch html source of that webpage and a af:richTextEditor to show source code in editing mode and in html mode 


  • See how to get webpage source from an url using java and save it to a html file (download a webpage ), Bind inputText and richInputText to managed bean and craete a actionListener on button to get source

  •     // Input text Binding to get URL
        private RichInputText webPageUrlBind;
        // RickInput text Binding to set Source
        private RichTextEditor richTextBind;
        public void setWebPageUrlBind(RichInputText webPageUrlBind) {
            this.webPageUrlBind = webPageUrlBind;
        }
    
        public RichInputText getWebPageUrlBind() {
            return webPageUrlBind;
        }
    
        public void setRichTextBind(RichTextEditor richTextBind) {
            this.richTextBind = richTextBind;
        }
    
        public RichTextEditor getRichTextBind() {
            return richTextBind;
        }
        /**Method to get html source of url (webpage) and set this to rickTextEditor
         * @param actionEvent
         */
        public void getSourceCodeAction(ActionEvent actionEvent) {
            URL url = null;
    
            try {
                if (webPageUrlBind.getValue() != null) {
                    // Define your URL- Get value from input text using binding
                    url = new URL(webPageUrlBind.getValue().toString());
                }
                URLConnection conn = url.openConnection();
    
                // open the stream and put it into BufferedReader
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
                String inputLine;
                String sourceCode = "";
    
                //Save html file (HTML Source Code of given URL)
                String fileName = "D:/web-content.html";
                File file = new File(fileName);
    
                if (!file.exists()) {
                    file.createNewFile();
                }
    
                //use FileWriter to write file
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                System.out.println("Printing WebPage source on console, Please wait...\n");
                while ((inputLine = br.readLine()) != null) {
                    System.out.println(inputLine);
                    bw.write(inputLine);
                    sourceCode = sourceCode.concat(inputLine);
                }
    
                bw.close();
                br.close();
                richTextBind.setValue(sourceCode);
                AdfFacesContext.getCurrentInstance().addPartialTarget(richTextBind);
                System.out.println("\n\nYour file is save in D drive! Congratulations ");
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    




  • now click on button and see , here i am getting source code of this blog http://oracleadf-java.blogspot.in/


  • now switch RichTextMode to see html preview of this source, it is exactly looking like live webpage, it shows one can practice in this ADF Faces's rickTextEditor to learn html tags


  • and see in D drive of your system a file named web-content created , it contains whole source of this webpage
 Cheers - Happy Learning :)