Wednesday, 20 January 2016

How to load HTTPS url from Java FX Webview component?

JavaFx has WebView component that can be used to load the Http & Https Url.
The basic steps to load any url using WebView is

WebView view = new WebView();
engine = view.getEngine();
engine.load(new URL("http://www.google.com));
engine.load(new URL("https://mail.google.com));

The problem comes when we have Https url to be loaded.
If the https url that we want to load have signed certificate, we can easily load it.
But if https url that we want to load does not have a signed certificate, it becomes difficult to load the Url.

To solve this, we disable the certificate check and mark the connection object to trust all the certificates.

Below is the code snippet that you should write just before loading the URL.

 TrustManager[] trustAllCerts = new TrustManager[] {  
         new X509TrustManager() {  
           public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
             return null;  
           }  
           public void checkClientTrusted(  
               java.security.cert.X509Certificate[] certs, String authType) {  
           }  
           public void checkServerTrusted(  
               java.security.cert.X509Certificate[] certs, String authType) {  
           }  
         }  
     };  
     // Install the all-trusting trust manager  
     try {  
       SSLContext sc = SSLContext.getInstance("SSL");  
       sc.init(null, trustAllCerts, new java.security.SecureRandom());  
       HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
     } catch (GeneralSecurityException e) {  
     }  

To create a full embeded browser that is able to load urls having self signed certificates.

 package utility;  
 import javafx.application.Platform;  
 import javafx.beans.value.ChangeListener;  
 import javafx.beans.value.ObservableValue;  
 import javafx.concurrent.Worker;  
 import javafx.embed.swing.JFXPanel;  
 import javafx.event.EventHandler;  
 import javafx.scene.Scene;  
 import javafx.scene.web.WebEngine;  
 import javafx.scene.web.WebEvent;  
 import javafx.scene.web.WebView;  
 import javax.net.ssl.HttpsURLConnection;  
 import javax.net.ssl.SSLContext;  
 import javax.net.ssl.TrustManager;  
 import javax.net.ssl.X509TrustManager;  
 import javax.swing.*;  
 import java.awt.*;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.security.GeneralSecurityException;  
 import static javafx.concurrent.Worker.State.FAILED;  
 public class SimpleWebBrowser extends JFrame {  
   private final JFXPanel jfxPanel = new JFXPanel();  
   private WebEngine engine;  
   private final JPanel panel = new JPanel(new BorderLayout());  
   private final JLabel lblStatus = new JLabel();  
   private final JProgressBar progressBar = new JProgressBar();  
   public SimpleWebBrowser() {  
     super();  
     initComponents();  
   }  
   private void initComponents() {  
     createScene();  
     progressBar.setPreferredSize(new Dimension(150, 18));  
     progressBar.setStringPainted(true);  
     JPanel topBar = new JPanel(new BorderLayout(5, 0));  
     topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));  
     JPanel statusBar = new JPanel(new BorderLayout(5, 0));  
     statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));  
     statusBar.add(lblStatus, BorderLayout.CENTER);  
     statusBar.add(progressBar, BorderLayout.EAST);  
     panel.add(topBar, BorderLayout.NORTH);  
     panel.add(jfxPanel, BorderLayout.CENTER);  
     panel.add(statusBar, BorderLayout.SOUTH);  
     getContentPane().add(panel);  
     setPreferredSize(new Dimension(1024, 600));  
     pack();  
   }  
   private void createScene() {  
     Platform.runLater(new Runnable() {  
       @Override  
       public void run() {  
         WebView view = new WebView();  
         engine = view.getEngine();  
         engine.titleProperty().addListener(new ChangeListener<String>() {  
           @Override  
           public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {  
             SwingUtilities.invokeLater(new Runnable() {  
               @Override  
               public void run() {  
                 SimpleWebBrowser.this.setTitle(newValue);  
               }  
             });  
           }  
         });  
         engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {  
           @Override  
           public void handle(final WebEvent<String> event) {  
             SwingUtilities.invokeLater(new Runnable() {  
               @Override  
               public void run() {  
                 lblStatus.setText(event.getData());  
               }  
             });  
           }  
         });  
         engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {  
           @Override  
           public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {  
             SwingUtilities.invokeLater(new Runnable() {  
               @Override  
               public void run() {  
                 progressBar.setValue(newValue.intValue());  
               }  
             });  
           }  
         });  
         engine.getLoadWorker()  
             .stateProperty()  
             .addListener(new ChangeListener<Worker.State>() {  
               @Override  
               public void changed(ObservableValue<? extends Worker.State> observableValue, Worker.State state, Worker.State state2) {  
                 if(state2 == Worker.State.SUCCEEDED){  
                   System.out.println("Completed");  
                 }  
               }  
             });  
         engine.getLoadWorker()  
             .exceptionProperty()  
             .addListener(new ChangeListener<Throwable>() {  
               public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {  
                 if (engine.getLoadWorker().getState() == FAILED) {  
                   SwingUtilities.invokeLater(new Runnable() {  
                     @Override public void run() {  
                       JOptionPane.showMessageDialog(  
                           panel,  
                           (value != null) ?  
                               engine.getLocation() + "\n" + value.getMessage() :  
                               engine.getLocation() + "\nUnexpected error.",  
                           "Loading error...",  
                           JOptionPane.ERROR_MESSAGE);  
                     }  
                   });  
                 }  
               }  
             });  
         jfxPanel.setScene(new Scene(view));  
       }  
     });  
   }  
   public void loadURL(final String url) {  
     TrustManager[] trustAllCerts = new TrustManager[] {  
         new X509TrustManager() {  
           public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
             return null;  
           }  
           public void checkClientTrusted(  
               java.security.cert.X509Certificate[] certs, String authType) {  
           }  
           public void checkServerTrusted(  
               java.security.cert.X509Certificate[] certs, String authType) {  
           }  
         }  
     };  
     // Install the all-trusting trust manager  
     try {  
       SSLContext sc = SSLContext.getInstance("SSL");  
       sc.init(null, trustAllCerts, new java.security.SecureRandom());  
       HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
     } catch (GeneralSecurityException e) {  
     }  
     Platform.runLater(new Runnable() {  
       @Override  
       public void run() {  
         String tmp = toURL(url);  
         if (tmp == null) {  
           tmp = toURL("http://" + url);  
         }  
         engine.load(tmp);  
       }  
     });  
   }  
   private static String toURL(String str) {  
     try {  
       return new URL(str).toExternalForm();  
     } catch (MalformedURLException exception) {  
       return null;  
     }  
   }  
   public static void main(String[] args) {  
     SwingUtilities.invokeLater(new Runnable() {  
       public void run() {  
         SimpleWebBrowser browser = new SimpleWebBrowser();  
         browser.setVisible(true);  
         browser.loadURL("https://self-sgned-url.com");  
         try {  
           Thread.sleep(5000);  
         } catch (InterruptedException e) {  
           e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.  
         }  
       }  
     });  
   }  
 }  

Done.

Saturday, 5 December 2015

How to programmatically extract the zip file using Java ?

This article is about how to write a utility class for extracting files and directories in a compressed zip archive, using built-in Java API.
The java.util.zip package provides the following classes for extracting files and directories from a ZIP archive:
    • ZipInputStream: this is the main class which can be used for reading zip file and extracting files and directories (entries) within the archive. Here are some important usages of this class:
      • read a zip via its constructor ZipInputStream(FileInputStream)
      • read entries of files and directories via method getNextEntry()
      • read binary data of current entry via method read(byte)
      • close current entry via method closeEntry()
      • close the zip file via method close()
       
    • ZipEntry: this class represents an entry in the zip file. Each file or directory is represented as a ZipEntry object. Its method getName() returns a String which represents path of the file/directory. The path is in the following form:
      folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext
       
Based on the path of a ZipEntry, we re-create directory structure when extracting the zip file. In addition, the BufferedOutputStream class is used to write content of the current ZipEntry to a file on disk, via its method write(byte[] bytes, int offset, int length). Following is source code of UnzipUtility.java class:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
/**
 * This utility extracts files and directories of a standard zip file to
 * a destination directory.
 * @author www.codejava.net
 *
 */
public class UnzipUtility {
    /**
     * Size of the buffer to read/write data
     */
    private static final int BUFFER_SIZE = 4096;
    /**
     * Extracts a zip file specified by the zipFilePath to a directory specified by
     * destDirectory (will be created if does not exists)
     * @param zipFilePath
     * @param destDirectory
     * @throws IOException
     */
    public void unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }
    /**
     * Extracts a zip entry (file entry)
     * @param zipIn
     * @param filePath
     * @throws IOException
     */
    private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}

How to download a zip file using Java code?

Below is the code snippet that will show you how to download the zip file from any url and save it to your local machine using java code.


import java.net.*;
import java.io.*;
 
public class URLConnectionReader {
    public void download_zip_file(String save_to) {
        URL url = new URL("http://pc-2011.com/downloads/test.zip");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream in = connection.getInputStream();
        FileOutputStream out = new FileOutputStream("test.zip");
        copy(in, out, 1024);
        out.close();
    }
 
    public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
        byte[] buf = new byte[bufferSize];
        int n = input.read(buf);
        while (n >= 0) {
            output.write(buf, 0, n);
            n = input.read(buf);
        }
        output.flush();
    }
}

Saturday, 31 October 2015

How to perform a join on two foreign keys from the same table

Let me describe the scenario in little more details.

Lets say i have a Taxi and Location Table.
Taxi table has 2 columns "startLocationId" and "endLocationId". Both these columns are foreign key to Location table.

Now while printing the results of Taxi Table, I want to print the Location Name and not just Location Id.

Here is the query.

select t.TaxiNo, l1.LocationName as "startLocation", l2.LocationName as "endLocation" from Taxi t join Location l1 on t.startLocationId=l1.locationId join Location l2 on t.endLocationId=l2.LocationId

Monday, 7 September 2015

How to downgrade your Xperia T2 Ultra Lolipop to Android Kitkat

I was facing very bad experience in using my Sony Xperia T2 ultra phone after i upgraded it to Lolipop version.

The phone was pathetically working slow. I wanted to go back to factory version of this.

If you wish to do the same, here are the below steps and then a you tube video from external source to show how these steps can be followed.

1. Download Flashtool from
https://drive.google.com/file/d/0B1AAC4lt7nzOQzR3aTZKUFZqem8/view?usp=sharing

2. Download Kitkat 4.4.3 from
https://drive.google.com/file/d/0B1oU02TyhZkAVTBvUU9MamRQZzg/edit

3. Copy above downloaded kitkat 4.4.3 file to C:\users\<username>\.flashtools\firmwares

4. Start Flash Tool.

5. Wait for any pending things to be completed in flash tool.

6. Click on left most button (which looks like zigzag spike). This will start the flash mode.

7. Now select the file which would be the one we just copied to flashtool directory.

8. Start the flashing. Wait for some time. Follow the onscreen instructions. When asked to press the back button, press the volume down key.

9. Wait for flashing to complete.

10. Disconnect and restart the phone.

Below is the youtube video to explain the above process


    Saturday, 15 November 2014

    How to make Spring beans thread-safe ?

    Spring beans are singleton by default.
    Singleton means bean identified by a particular bean id will have only one instance.

    Consider the following code:
    @Controller
    public class MyServlet {
    
        @Autowired
        private HelloService service;
    
        @RequestMapping(value="/hello", method = RequestMethod.GET)
        public void sayHello(HttpServletRequest req, HttpServletResponse res) throws IOException {
            service.doStuff();
        }
    
    }
    
    
    public class HelloService {
    
        private int i = 1;
    
        public void doStuff() {
            System.out.println("Started " + i);
            i++;
            System.out.println(Thread.currentThread().getName() + " Done " + i);
        }
    }
    The output will be something like this:
    32911580@qtp-28064776-0 - Started 1
    7802158@qtp-28064776-2 - Started 2
    32911580@qtp-28064776-0 - Done 3
    7802158@qtp-28064776-2 - Done 3
    This prove the "i" var is shared between multiple threads.
    Now lets try to define the HelloService bean as prototype, like this
    <bean id="helloService" class="my.package.HelloService" scope="prototype" />
    In this case as well, the result is the same.
    The only ways this can be solved is : move the declaration into doStuff() method, but it's not what we want - make the doStuff() method, but this means have locks
    What I would like is have a new instance of HelloService on every call.
    Since you have only one instance of MyServlet you will also have only one instance of HelloService.
    One of the following spring scopes help: request A new instance for each HTTP request. session A new instance of the class for each new HttpSession created in a servlet container.
    This will change the semantics of your code. If you declare the bean in the scope request your counter will always be 1.
    So, to make bean thread-safe, make the bean definition scope as "request" or "session".

    Wednesday, 12 November 2014

    How to create a Bootable Windows 7 USB Flash Drive

    Instructions to create a Bootable Windows 7 USB Flash Drive 

    rufus How to Create a Bootable Windows 7 USB Flash Drive
    • Step 1: Download rufus on your computerand run it .
    • Step 2: Plug in your USB flash drive into your computer .
    • Step 3: From Rufu’s settings, Choose NTFS as the file system.
    • Step 4: Check ” Quick format ” and ”Create extended label and icon files “
    • Step 5: Check ” Create a bootable disk using ” and click the drive icon beside it to select the windows 7 ISO file .
    • Step 6: Now click on start to create a bootable window 7 USB flash drive .
    After a few minutes your Windows 7 bootable  USB flash drive will be  ready for installation. Reboot your PC and set the bootable flash drive as a first boot priority in the bios settings. Save the bios settings and reboot once again to continue with the windows 7 installation process .
     Note: You have to allow booting from USB devices in your BIOS settings in order to proceed further with the windows 7 installation .

    For those who install using the bootable USB Flash Drive

    For newer desktop computer or laptop with USB 3.0 Ports, be sure to plug it in USB 2.0 ports to avoid the error. 

    The rest proceed to the next step

    To fix the problem:


    • Browse the file f6flpy-x86 or f6flpy-x64 file included in DVD drivers

    • If the file is not in the DVD, download the file in Microsoft Website

    • extract the file, put it in usb and browse the file.

    Additional Resources

    • f6flpy-x64  f6flpy-x86  Windows 7 download f6flpy-x86 sata drivers