Monday, January 9, 2017

Downloading jars separately and executing using JNLP and providing progress bar in Java Web Start application.



We have a JNLP file to provide the input in main method of the application as mentioned 
below :

Test.jnlp
-------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/examples/" href="Test.jnlp">
  <information>
    <title>Demo</title>
    <vendor>Demo</vendor>
   
    <description>DemoDesc</description>
   
    <offline-allowed/>
   <!-- Prefer a shortcut for online operation -->

 </information>
       <security>
          <all-permissions/>
    </security>

<resources>

       <j2se version="1.7+"/>

       <jar href="final.jar"/>
             
         
</resources>

     <application-desc main-class="com.b.Launcher">
        
        <!-- where to download   C:\Users\F1038\AppData\Roaming\-->
              <argument>folderName</argument>
             
              <!-- server location to download files from -->
              <argument> http://localhost:8080/examples/folderName/</argument>
        
        <!-- executing module application -->
              <argument> java -jar mainDemo.jar</argument>
        
           <!-- application's to download -->
             
              <argument>file:config.zip</argument>
              <argument>file:Prop.zip</argument>
              <argument>file:library.zip</argument>
             
              <argument>file:maindemo.jar</argument>
              <argument>file:demo.jar</argument>
             
             
             
             
             
       </application-desc>
</jnlp>

-----------------------------------------------------------------------------------------------------------------------

This program will get input from the JNLP file and download zip/jar files from the server on to local machine at specified input folder location and then extract them on local machine.After extracting we will delete those zip files through code.

Why we need to display progress bar ?
Because file downloading,extracting and deleting takes time. To improvise user experience, we have to display progress bar, otherwise he/she will not know that files are yet to get download and user may request again. After downloading is done, mainJar which contains main method will be executed through ProcessBuilder.

Note: There is no third party jar used for developing Java Web Start Application.

A progress bar will be show while downloading the files.

Launcher.java
----------------------------------------

package com.progress.download;

import java.awt.FlowLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;

public class Launcher extends JFrame {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    JProgressBar jb;
      
       //lable of the progress bar dialog
      
    JLabel lb = new JLabel("Please wait..");
    int i = 0, num = 0;
  

    public Launcher() {
        // TODO Auto-generated constructor stub
    }

    Launcher(String[] jarsToDownload) {
      
         
        setTitle("Downloading Files");
        setEnabled(false);
             
              //jarsToDownload.length  signifies the progress bar length
        jb = new JProgressBar(0, jarsToDownload.length - 1);
             
        jb.setBounds(40, 40, 160, 30);
        jb.setValue(0);
        jb.setStringPainted(true);
        add(lb);
        add(jb);
        pack();
             
              //center aligining of the progress bar dialog
               setLocationRelativeTo(null);
               
        setSize(250,70);
        setLayout(new FlowLayout());
    }

    public static void main(String[] args) {

        String[] jarsToDownload = null;
        String serverPathURL = null;
        String downloadFolderName = null;
        String runModule = null;

        try {
            downloadFolderName = args[0];
            serverPathURL = args[1];
            runModule = args[2];
            jarsToDownload = args;
        } catch (Exception e) {
              //showing the error alert
            showErrorDialog("unable to process!! input not valid");
            return;
        }

        System.out.println(" downloadFolderName : " + downloadFolderName);
        System.out.println(" serverPathURL : " + serverPathURL);
        System.out.println(" runModule : " + runModule);
        System.out.println(" jarsToDownload : " + jarsToDownload);

        Launcher m = new Launcher(jarsToDownload);
        m.setVisible(true);

        System.out.println(" showing progress bar ");

        m.downloadStart(jarsToDownload, serverPathURL, downloadFolderName, runModule);

    }

    private void downloadStart(String[] jarsToDownload, String serverPathURL, String downloadFolderName, String runModule) {
        System.out.println(" inside iterater ");
        String getenv = System.getenv("APPDATA");
             
              //creating folder location where jars will be downloaded
             
        String createFilesFolderPath = createFilesFolderPath(getenv + "\\" + downloadFolderName + "\\");
        System.out.println("created path " + createFilesFolderPath);
        try {
              //measuring time taken to download files
            long start=System.currentTimeMillis();
            downloadAllFiles(createFilesFolderPath, serverPathURL, jarsToDownload);
            long end=System.currentTimeMillis();

            System.out.println("file downloaded successfully in " + (end-start) +" Seconds");
        } catch (IOException e1) {
            setVisible(false);
            dispose(); //Destroy the JFrame object
            showErrorDialog("unable to download files: " + e1.getMessage());
            return;
        }
        setVisible(false);
        dispose(); //Destroy the JFrame object
        System.out.println("execurint module");
        executeModule(downloadFolderName, runModule, createFilesFolderPath);
    }

    private void executeModule(String downloadFolderName, String runModule, String createFilesFolderPath) {
        try {
              //runModule is the main jar which we want to execute
             
            System.out.println("executing : " + downloadFolderName);
            ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", runModule);
            pb = pb.directory(new File(createFilesFolderPath));
            pb.start();
        } catch (IOException e) {
            setVisible(false);
            dispose(); //Destroy the JFrame object
            showErrorDialog("unable to process " + downloadFolderName + " : " + e.getMessage());
        }
    }
      
// downloading files and updating progress bar

    private void downloadAllFiles(String createFilesFolderPath, String serverPath, String[] jarsToDownload)
            throws MalformedURLException, IOException {
        System.out.println("inside downloadAllFiles ");
        int progressCounter = 0;
        while (progressCounter < jarsToDownload.length) {
            System.out.println(" progressCounter : " +progressCounter);
            String fileName = jarsToDownload[progressCounter];
            System.out.println("fileName : " +fileName);
            if (fileName.startsWith("file:")) {
                System.out.println(" inside if condition : " +progressCounter);
                String downloadFile = jarsToDownload[progressCounter].replaceFirst("file:", "");
                System.out.println(" downloading : " + downloadFile);
                downloadingConfigFiles(serverPath + downloadFile, createFilesFolderPath + downloadFile,
                        createFilesFolderPath);
                jb.setValue(progressCounter);
                progressCounter = progressCounter + 1;
            }else{
                System.out.println("inside else ");
                progressCounter = progressCounter + 1;
            }
          
        }
    }
//method to download zip files from server and extracting them at local machine and //then deleting those zip files from local machine folder
    private static void downloadingConfigFiles(String serverPropsPath, String createFilesFolderPath, String destPath)
            throws MalformedURLException, IOException {


        try (ReadableByteChannel in = Channels.newChannel(new URL(serverPropsPath).openStream());
                FileChannel out = new FileOutputStream(createFilesFolderPath).getChannel()) {

            out.transferFrom(in, 0, Long.MAX_VALUE);
        }
        unzip(createFilesFolderPath, destPath);

        deleteZipFolders(createFilesFolderPath);

       

    }

    private static void deleteZipFolders(String zipFilePath) {
        // TODO Auto-generated method stub
        File file = new File(zipFilePath);
        if (zipFilePath.contains(".zip")) {
            file.delete();
            System.out.println("deleted : " + file.getName());
        }
    }

    public static String createFilesFolderPath(String zaraOpsLocalPath) {

        File file = new File(zaraOpsLocalPath);
        if (!file.exists()) {
            if (file.mkdir()) {
                return zaraOpsLocalPath;

            } else {
                System.out.println("Failed to create directory!");
            }
        }
        return zaraOpsLocalPath;
    }

    private static void unzip(String zipFilePath, String destDir) {
        if (zipFilePath.contains(".zip")) {
            File dir = new File(destDir);
            // create output directory if it doesn't exist
            if (!dir.exists())
                dir.mkdirs();
            FileInputStream fis;
            // buffer for read and write data to file
            byte[] buffer = new byte[1024];
            try {
                fis = new FileInputStream(zipFilePath);
                ZipInputStream zis = new ZipInputStream(fis);
                ZipEntry ze = zis.getNextEntry();
                while (ze != null) {
                    String fileName = ze.getName();
                    File newFile = new File(destDir + File.separator + fileName);
                    System.out.println("Unzipping to " + newFile.getAbsolutePath());
                    new File(newFile.getParent()).mkdirs();
                    FileOutputStream fos = new FileOutputStream(newFile);
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                                        zis.closeEntry();
                    ze = zis.getNextEntry();
                }
                // close last ZipEntry
                zis.closeEntry();
                zis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
//this method will show progress bar and get close automatically after download //process ends
    private static void showErrorDialog(final String errorMessage) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }

            private void createAndShowGUI() {
                // Create and set up the window.
                JFrame frame = new JFrame("DialogDemo");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JOptionPane.showMessageDialog(frame, errorMessage, "Error", JOptionPane.INFORMATION_MESSAGE);

                // Display the window.
                frame.pack();
                frame.setVisible(false);
                frame.dispose();
            }
        });
        System.out.println(" System exit with input error ");
        return;
    }
}

Create a link to on web for your JNLP file.
 

After click on the MainJNLP hyperlinik, you will see the below output :


-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------

Java Web Start will start download all the files..

 

 Confirm security warning...click on Run button.

 

 Files shall start downloading to your local machine as progress bar is showing...



Here is the location where all the files will get downloaded

 





No comments:

Post a Comment

Fixing yum command on linux

You may find yourself having to fix more packages. So you can just remove everything you had installed via  pip and reinstall everythin...