package com.marinilli.b2.c11;
import com.marinilli.b2.c11.util.Utilities;
import javax.swing.*;
import java.awt.print.*;
import javax.jnlp.*;
import java.awt.*;
import java.io.*;
import java.net.*;
/**
 * Chapter 11 - Another Installer Example
 * @author Mauro Marinilli
 * @version 1.0
 */
public class InstallerExample implements Runnable {
  ExtensionInstallerService eis;
  public InstallerExample() {
    Utilities.getInstance("installer-msgs");
    eis = (ExtensionInstallerService)Utilities.getService("javax.jnlp.ExtensionInstallerService");
    Thread t = new Thread(this);
    t.start();
  }
  public void run() {
    setupDownloadWindow();
    doResourcesDownload();
    installationCompleted(true, false);
  }
  public void setupDownloadWindow() {
    eis.setHeading(Utilities.getMsg("heading1"));
    eis.setStatus(Utilities.getMsg("sometext"));
  }
  public void doResourcesDownload(){
    installOptionalPackage();
  }
  public void installationCompleted(boolean success, boolean reboot){
    if (success){
      if (reboot){
        //handle some reboot preparation
      }
      eis.installSucceeded(reboot);
    } else {
      //handle failure
      eis.installFailed();
    }
  }
  public void installOptionalPackage(){
    String optionalPackagesJARDirWin = "\\lib\\ext\\";//see Sun docs
    String jarName = "anapp.jar";
    String jarServerPath = "http://server/b2/c11/"+jarName;
    URL jreURL = null;
    try {
      jreURL = new URL("http://jsp.java.sun.com/servlet/javawsExtensionServer");
    } catch (Exception e) {
      System.out.println("creating URL: "+e);
    }
    String jrePath = eis.getInstalledJRE(jreURL,"1.3.0");
    File javaFile = new File(jrePath);//where java is located
    String jreRoot = javaFile.getParentFile().getParent();
    File libDir = new File(jreRoot+optionalPackagesJARDirWin);
    if (!libDir.exists())
      libDir.mkdirs();
    File jarFile = new File(jreRoot + optionalPackagesJARDirWin +jarName);
    try {
      FileOutputStream fos = new FileOutputStream(jarFile);
      URL jarURL = new URL(jarServerPath);
      URLConnection jarConn = jarURL.openConnection();
      InputStream is = jarConn.getInputStream();
      int q;
      while ((q = is.read()) != -1)
        fos.write(q);
      is.close();
      fos.close();
    } catch (Exception e) {
      System.out.println("creating & writing "+jarName+": "+e);
    }
  }
  public static void main(String[] args) {
    InstallerExample installer = new InstallerExample();
  }
}