/**
   * Parses the files.
   *
   * @exception Exception Description of the Exception
   */
  public void parseFiles() throws Exception {
    // Parses the files
    Iterator iter = files.iterator();
    while (iter.hasNext()) {
      // If interrupt is desired, return immediately.
      if (Unpacker.isInterruptDesired()) return;
      // Create a temporary file for the parsed data
      // (Use the same directory so that renaming works later)
      ParsableFile pfile = (ParsableFile) iter.next();

      // check whether the OS matches
      if (!OsConstraint.oneMatchesCurrentSystem(pfile.osConstraints)) {
        continue;
      }

      File file = new File(pfile.path);
      File parsedFile = File.createTempFile("izpp", null, file.getParentFile());

      // Parses the file
      // (Use buffering because substitutor processes byte at a time)
      FileInputStream inFile = new FileInputStream(file);
      BufferedInputStream in = new BufferedInputStream(inFile, 5120);
      FileOutputStream outFile = new FileOutputStream(parsedFile);
      BufferedOutputStream out = new BufferedOutputStream(outFile, 5120);
      vs.substitute(in, out, pfile.type, pfile.encoding);
      in.close();
      out.close();

      // Replace the original file with the parsed one
      file.delete();
      if (!parsedFile.renameTo(file))
        throw new IOException("Could not rename file " + parsedFile + " to " + file);
    }
  }
  /**
   * Loads custom data like listener and lib references if exist and fills the installdata.
   *
   * @param installdata installdata into which the custom action data should be stored
   * @throws Exception
   */
  private void loadCustomData(AutomatedInstallData installdata) throws Exception {
    // Usefull variables
    InputStream in;
    ObjectInputStream objIn;
    int i;
    // Load listeners if exist.
    String[] streamNames = AutomatedInstallData.CUSTOM_ACTION_TYPES;
    List[] out = new List[streamNames.length];
    for (i = 0; i < streamNames.length; ++i) {
      out[i] = new ArrayList();
    }
    in = InstallerBase.class.getResourceAsStream("/customData");
    if (in != null) {
      objIn = new ObjectInputStream(in);
      Object listeners = objIn.readObject();
      objIn.close();
      Iterator keys = ((List) listeners).iterator();
      while (keys != null && keys.hasNext()) {
        CustomData ca = (CustomData) keys.next();

        if (ca.osConstraints != null
            && !OsConstraint.oneMatchesCurrentSystem(
                ca.osConstraints)) { // OS constraint defined, but not matched; therefore ignore
          // it.
          continue;
        }
        switch (ca.type) {
          case CustomData.INSTALLER_LISTENER:
            Class clazz = Class.forName(ca.listenerName);
            if (clazz == null) {
              throw new InstallerException("Custom action " + ca.listenerName + " not bound!");
            }
            out[ca.type].add(clazz.newInstance());
            break;
          case CustomData.UNINSTALLER_LISTENER:
          case CustomData.UNINSTALLER_JAR:
            out[ca.type].add(ca);
            break;
          case CustomData.UNINSTALLER_LIB:
            out[ca.type].add(ca.contents);
            break;
        }
      }
      // Add the current custem action data to the installdata hash map.
      for (i = 0; i < streamNames.length; ++i) {
        installdata.customData.put(streamNames[i], out[i]);
      }
    }
    // uninstallerLib list if exist

  }
  // helper function
  private void readChoices(XMLElement element, ArrayList result) {
    Vector choices = element.getChildrenNamed("choice");

    if (choices == null) return;

    result.clear();

    Iterator choice_it = choices.iterator();

    while (choice_it.hasNext()) {
      XMLElement choice = (XMLElement) choice_it.next();

      String value = choice.getAttribute("value");

      if (value != null) {
        List osconstraints = OsConstraint.getOsList(choice);

        if (OsConstraint.oneMatchesCurrentSystem(osconstraints)) {
          result.add(this.vs.substitute(value, "plain"));
        }
      }
    }
  }
  /**
   *  Loads the installation data.
   *
   * @exception  Exception  Description of the Exception
   */
  public void loadInstallData(AutomatedInstallData installdata) throws Exception
  {
    // Usefull variables
    InputStream in;
    DataInputStream datIn;
    ObjectInputStream objIn;
    int size;
    int i;

    // We load the variables
    Properties variables = null;
    in = getClass().getResourceAsStream("/vars");
    if (null != in)
    {
      objIn = new ObjectInputStream(in);
      variables = (Properties) objIn.readObject();
      objIn.close();
    }

    // We load the Info data
    in = getClass().getResourceAsStream("/info");
    objIn = new ObjectInputStream(in);
    Info inf = (Info) objIn.readObject();
    objIn.close();

    // We put the Info data as variables
    installdata.setVariable(ScriptParser.APP_NAME, inf.getAppName());
    installdata.setVariable(ScriptParser.APP_URL, inf.getAppURL());
    installdata.setVariable(ScriptParser.APP_VER, inf.getAppVersion());

    // We read the panels order data
    in = getClass().getResourceAsStream("/panelsOrder");
    datIn = new DataInputStream(in);
    size = datIn.readInt();
    ArrayList panelsOrder = new ArrayList();
    for (i = 0; i < size; i++)
      panelsOrder.add(datIn.readUTF());
    datIn.close();

    String os = System.getProperty("os.name");
    // We read the packs data
    in = getClass().getResourceAsStream("/packs.info");
    objIn = new ObjectInputStream(in);
    size = objIn.readInt();
    ArrayList availablePacks = new ArrayList();
    ArrayList allPacks = new ArrayList();
    for (i = 0; i < size; i++) 
    {
      Pack pk = (Pack) objIn.readObject();
      allPacks.add(pk);
      if (OsConstraint.oneMatchesCurrentSystem(pk.osConstraints))
        availablePacks.add(pk);
    }
    objIn.close();

    // We determine the operating system and the initial installation path
    String user = System.getProperty("user.name");
    String dir;
    String installPath;
    if (os.regionMatches(true, 0, "windows", 0, 7))
    {
      dir = buildWindowsDefaultPath();
    }
    else if (os.regionMatches(true, 0, "mac os x", 0, 6))
    {
      dir = "/Applications" + File.separator;
    }
    else if (os.regionMatches(true, 0, "mac", 0, 3))
    {
      dir = "";
    }
    else
    {
      if (user.equals("root"))
      {
        dir = "/usr/local" + File.separator;
      }
      else
      {
        dir = System.getProperty("user.home") + File.separator;
      }
    }

    installPath = dir + inf.getAppName();

    // We read the installation kind
    in = getClass().getResourceAsStream("/kind");
    datIn = new DataInputStream(in);
    String kind = datIn.readUTF();
    datIn.close();

    installdata.setInstallPath(installPath);
    installdata.setVariable
      (ScriptParser.JAVA_HOME, System.getProperty("java.home"));
    installdata.setVariable
      (ScriptParser.USER_HOME, System.getProperty("user.home"));
    installdata.setVariable
      (ScriptParser.USER_NAME, System.getProperty("user.name"));
    installdata.setVariable
      (ScriptParser.FILE_SEPARATOR, File.separator);
    if (null != variables)
    {
      Enumeration enum = variables.keys();
      String varName = null;
      String varValue = null;
      while (enum.hasMoreElements())
      {
        varName = (String) enum.nextElement();
        varValue = (String) variables.getProperty(varName);
        installdata.setVariable(varName, varValue);
      }
    }
    installdata.info = inf;
    installdata.kind = kind;
    installdata.panelsOrder = panelsOrder;
    installdata.availablePacks = availablePacks;
    installdata.allPacks = allPacks;
    
    // get list of preselected packs
    Iterator pack_it = availablePacks.iterator();
    while (pack_it.hasNext())
    {
      Pack pack = (Pack)pack_it.next();
      if (pack.preselected)
        installdata.selectedPacks.add (pack);
    }

  }
예제 #5
0
  /* (non-Javadoc)
   * @see com.izforge.izpack.installer.IUnpacker#run()
   */
  public void run() {
    addToInstances();
    try {
      //
      // Initialisations
      FileOutputStream out = null;
      ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>();
      ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>();
      ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>();
      List packs = idata.selectedPacks;
      int npacks = packs.size();
      handler.startAction("Unpacking", npacks);
      udata = UninstallData.getInstance();
      // Custom action listener stuff --- load listeners ----
      List[] customActions = getCustomActions();
      // Custom action listener stuff --- beforePacks ----
      informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler);
      packs = idata.selectedPacks;
      npacks = packs.size();

      // We unpack the selected packs
      for (int i = 0; i < npacks; i++) {
        // We get the pack stream
        // int n = idata.allPacks.indexOf(packs.get(i));
        Pack p = (Pack) packs.get(i);

        // evaluate condition
        if (p.hasCondition()) {
          if (rules != null) {
            if (!rules.isConditionTrue(p.getCondition())) {
              // skip pack, condition is not fullfilled.
              continue;
            }
          } else {
            // TODO: skip pack, because condition can not be checked
          }
        }

        // Custom action listener stuff --- beforePack ----
        informListeners(
            customActions, InstallerListener.BEFORE_PACK, packs.get(i), npacks, handler);
        ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall));

        // We unpack the files
        int nfiles = objIn.readInt();

        // We get the internationalized name of the pack
        final Pack pack = ((Pack) packs.get(i));
        String stepname = pack.name; // the message to be passed to the
        // installpanel
        if (langpack != null && !(pack.id == null || "".equals(pack.id))) {

          final String name = langpack.getString(pack.id);
          if (name != null && !"".equals(name)) {
            stepname = name;
          }
        }
        handler.nextStep(stepname, i + 1, nfiles);
        for (int j = 0; j < nfiles; j++) {
          // We read the header
          PackFile pf = (PackFile) objIn.readObject();
          // TODO: reaction if condition can not be checked
          if (pf.hasCondition() && (rules != null)) {
            if (!rules.isConditionTrue(pf.getCondition())) {
              if (!pf.isBackReference()) {
                // skip, condition is not fulfilled
                objIn.skip(pf.length());
              }
              continue;
            }
          }
          if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints())) {
            // We translate & build the path
            String path = IoHelper.translatePath(pf.getTargetPath(), vs);
            File pathFile = new File(path);
            File dest = pathFile;
            if (!pf.isDirectory()) {
              dest = pathFile.getParentFile();
            }

            if (!dest.exists()) {
              // If there are custom actions which would be called
              // at
              // creating a directory, create it recursively.
              List fileListeners = customActions[customActions.length - 1];
              if (fileListeners != null && fileListeners.size() > 0) {
                mkDirsWithEnhancement(dest, pf, customActions);
              } else
              // Create it in on step.
              {
                if (!dest.mkdirs()) {
                  handler.emitError(
                      "Error creating directories",
                      "Could not create directory\n" + dest.getPath());
                  handler.stopAction();
                  this.result = false;
                  return;
                }
              }
            }

            if (pf.isDirectory()) {
              continue;
            }

            // Custom action listener stuff --- beforeFile ----
            informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf, null);
            // We add the path to the log,
            udata.addFile(path, pack.uninstall);

            handler.progress(j, path);

            // if this file exists and should not be overwritten,
            // check
            // what to do
            if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE)) {
              boolean overwritefile = false;

              // don't overwrite file if the user said so
              if (pf.override() != PackFile.OVERRIDE_FALSE) {
                if (pf.override() == PackFile.OVERRIDE_TRUE) {
                  overwritefile = true;
                } else if (pf.override() == PackFile.OVERRIDE_UPDATE) {
                  // check mtime of involved files
                  // (this is not 100% perfect, because the
                  // already existing file might
                  // still be modified but the new installed
                  // is just a bit newer; we would
                  // need the creation time of the existing
                  // file or record with which mtime
                  // it was installed...)
                  overwritefile = (pathFile.lastModified() < pf.lastModified());
                } else {
                  int def_choice = -1;

                  if (pf.override() == PackFile.OVERRIDE_ASK_FALSE) {
                    def_choice = AbstractUIHandler.ANSWER_NO;
                  }
                  if (pf.override() == PackFile.OVERRIDE_ASK_TRUE) {
                    def_choice = AbstractUIHandler.ANSWER_YES;
                  }

                  int answer =
                      handler.askQuestion(
                          idata.langpack.getString("InstallPanel.overwrite.title")
                              + " - "
                              + pathFile.getName(),
                          idata.langpack.getString("InstallPanel.overwrite.question")
                              + pathFile.getAbsolutePath(),
                          AbstractUIHandler.CHOICES_YES_NO,
                          def_choice);

                  overwritefile = (answer == AbstractUIHandler.ANSWER_YES);
                }
              }

              if (!overwritefile) {
                if (!pf.isBackReference() && !((Pack) packs.get(i)).loose) {
                  objIn.skip(pf.length());
                }
                continue;
              }
            }

            // We copy the file
            InputStream pis = objIn;
            if (pf.isBackReference()) {
              InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall);
              pis = new ObjectInputStream(is);
              // must wrap for blockdata use by objectstream
              // (otherwise strange result)
              // skip on underlaying stream (for some reason not
              // possible on ObjectStream)
              is.skip(pf.offsetInPreviousPack - 4);
              // but the stream header is now already read (== 4
              // bytes)
            } else if (((Pack) packs.get(i)).loose) {
              /* Old way of doing the job by using the (absolute) sourcepath.
               * Since this is very likely to fail and does not confirm to the documentation,
               * prefer using relative path's
              pis = new FileInputStream(pf.sourcePath);
               */

              File resolvedFile = new File(getAbsolutInstallSource(), pf.getRelativeSourcePath());
              if (!resolvedFile.exists()) {
                // try alternative destination - the current working directory
                // user.dir is likely (depends on launcher type) the current directory of the
                // executable or jar-file...
                final File userDir = new File(System.getProperty("user.dir"));
                resolvedFile = new File(userDir, pf.getRelativeSourcePath());
              }
              if (resolvedFile.exists()) {
                pis = new FileInputStream(resolvedFile);
                // may have a different length & last modified than we had at compiletime, therefore
                // we have to build a new PackFile for the copy process...
                pf =
                    new PackFile(
                        resolvedFile.getParentFile(),
                        resolvedFile,
                        pf.getTargetPath(),
                        pf.osConstraints(),
                        pf.override(),
                        pf.getAdditionals());
              } else {
                // file not found
                // issue a warning (logging api pending)
                // since this file was loosely bundled, we continue with the installation.
                System.out.println(
                    "Could not find loosely bundled file: " + pf.getRelativeSourcePath());
                out.close();
                continue;
              }
            }

            if (pf.isPack200Jar()) {
              int key = objIn.readInt();
              InputStream pack200Input =
                  Unpacker.class.getResourceAsStream("/packs/pack200-" + key);
              Pack200.Unpacker unpacker = getPack200Unpacker();
              java.util.jar.JarOutputStream jarOut =
                  new java.util.jar.JarOutputStream(new FileOutputStream(pathFile));
              unpacker.unpack(pack200Input, jarOut);
              jarOut.close();
            } else {
              out = new FileOutputStream(pathFile);
              byte[] buffer = new byte[5120];
              long bytesCopied = 0;
              while (bytesCopied < pf.length()) {
                if (performInterrupted()) { // Interrupt was initiated; perform it.
                  out.close();
                  if (pis != objIn) {
                    pis.close();
                  }
                  return;
                }
                int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length);
                int bytesInBuffer = pis.read(buffer, 0, maxBytes);
                if (bytesInBuffer == -1) {
                  throw new IOException("Unexpected end of stream (installer corrupted?)");
                }

                out.write(buffer, 0, bytesInBuffer);

                bytesCopied += bytesInBuffer;
              }
              out.close();
            }

            if (pis != objIn) {
              pis.close();
            }

            // Set file modification time if specified
            if (pf.lastModified() >= 0) {
              pathFile.setLastModified(pf.lastModified());
            }
            // Custom action listener stuff --- afterFile ----
            informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf, null);

          } else {
            if (!pf.isBackReference()) {
              objIn.skip(pf.length());
            }
          }
        }

        // Load information about parsable files
        int numParsables = objIn.readInt();
        for (int k = 0; k < numParsables; k++) {
          ParsableFile pf = (ParsableFile) objIn.readObject();
          if (pf.hasCondition() && (rules != null)) {
            if (!rules.isConditionTrue(pf.getCondition())) {
              // skip, condition is not fulfilled
              continue;
            }
          }
          pf.path = IoHelper.translatePath(pf.path, vs);
          parsables.add(pf);
        }

        // Load information about executable files
        int numExecutables = objIn.readInt();
        for (int k = 0; k < numExecutables; k++) {
          ExecutableFile ef = (ExecutableFile) objIn.readObject();
          if (ef.hasCondition() && (rules != null)) {
            if (!rules.isConditionTrue(ef.getCondition())) {
              // skip, condition is false
              continue;
            }
          }
          ef.path = IoHelper.translatePath(ef.path, vs);
          if (null != ef.argList && !ef.argList.isEmpty()) {
            String arg = null;
            for (int j = 0; j < ef.argList.size(); j++) {
              arg = ef.argList.get(j);
              arg = IoHelper.translatePath(arg, vs);
              ef.argList.set(j, arg);
            }
          }
          executables.add(ef);
          if (ef.executionStage == ExecutableFile.UNINSTALL) {
            udata.addExecutable(ef);
          }
        }
        // Custom action listener stuff --- uninstall data ----
        handleAdditionalUninstallData(udata, customActions);

        // Load information about updatechecks
        int numUpdateChecks = objIn.readInt();

        for (int k = 0; k < numUpdateChecks; k++) {
          UpdateCheck uc = (UpdateCheck) objIn.readObject();

          updatechecks.add(uc);
        }

        objIn.close();

        if (performInterrupted()) { // Interrupt was initiated; perform it.
          return;
        }

        // Custom action listener stuff --- afterPack ----
        informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i), i, handler);
      }

      // We use the scripts parser
      ScriptParser parser = new ScriptParser(parsables, vs);
      parser.parseFiles();
      if (performInterrupted()) { // Interrupt was initiated; perform it.
        return;
      }

      // We use the file executor
      FileExecutor executor = new FileExecutor(executables);
      if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0) {
        handler.emitError("File execution failed", "The installation was not completed");
        this.result = false;
      }

      if (performInterrupted()) { // Interrupt was initiated; perform it.
        return;
      }

      // We put the uninstaller (it's not yet complete...)
      putUninstaller();

      // update checks _after_ uninstaller was put, so we don't delete it
      performUpdateChecks(updatechecks);

      if (performInterrupted()) { // Interrupt was initiated; perform it.
        return;
      }

      // Custom action listener stuff --- afterPacks ----
      informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
      if (performInterrupted()) { // Interrupt was initiated; perform it.
        return;
      }

      // write installation information
      writeInstallationInformation();

      // The end :-)
      handler.stopAction();
    } catch (Exception err) {
      // TODO: finer grained error handling with useful error messages
      handler.stopAction();
      if ("Installation cancelled".equals(err.getMessage())) {
        handler.emitNotification("Installation cancelled");
      } else {
        handler.emitError("An error occured", err.getMessage());
        err.printStackTrace();
      }
      this.result = false;
      Housekeeper.getInstance().shutDown(4);
    } finally {
      removeFromInstances();
    }
  }
  /**
   * Loads the installation data. Also sets environment variables to <code>installdata</code>. All
   * system properties are available as $SYSTEM_<variable> where <variable> is the actual name _BUT_
   * with all separators replaced by '_'. Properties with null values are never stored. Example:
   * $SYSTEM_java_version or $SYSTEM_os_name
   *
   * @param installdata Where to store the installation data.
   * @throws Exception Description of the Exception
   */
  public void loadInstallData(AutomatedInstallData installdata) throws Exception {
    // Usefull variables
    InputStream in;
    ObjectInputStream objIn;
    int size;
    int i;

    // We load the variables
    Properties variables = null;
    in = InstallerBase.class.getResourceAsStream("/vars");
    if (null != in) {
      objIn = new ObjectInputStream(in);
      variables = (Properties) objIn.readObject();
      objIn.close();
    }

    // We load the Info data
    in = InstallerBase.class.getResourceAsStream("/info");
    objIn = new ObjectInputStream(in);
    Info inf = (Info) objIn.readObject();
    objIn.close();

    // We put the Info data as variables
    installdata.setVariable(ScriptParser.APP_NAME, inf.getAppName());
    if (inf.getAppURL() != null) {
      installdata.setVariable(ScriptParser.APP_URL, inf.getAppURL());
    }
    installdata.setVariable(ScriptParser.APP_VER, inf.getAppVersion());
    if (inf.getUninstallerCondition() != null) {
      installdata.setVariable("UNINSTALLER_CONDITION", inf.getUninstallerCondition());
    }
    // We read the panels order data
    in = InstallerBase.class.getResourceAsStream("/panelsOrder");
    objIn = new ObjectInputStream(in);
    List panelsOrder = (List) objIn.readObject();
    objIn.close();

    // We read the packs data
    in = InstallerBase.class.getResourceAsStream("/packs.info");
    objIn = new ObjectInputStream(in);
    size = objIn.readInt();
    ArrayList availablePacks = new ArrayList();
    ArrayList<Pack> allPacks = new ArrayList<Pack>();
    for (i = 0; i < size; i++) {
      Pack pk = (Pack) objIn.readObject();
      allPacks.add(pk);
      if (OsConstraint.oneMatchesCurrentSystem(pk.osConstraints)) {
        availablePacks.add(pk);
      }
    }
    objIn.close();

    // We determine the operating system and the initial installation path
    String dir;
    String installPath;
    if (OsVersion.IS_WINDOWS) {
      dir = buildWindowsDefaultPath();
    } else if (OsVersion.IS_OSX) {
      dir = "/Applications";
    } else {
      if (new File("/usr/local/").canWrite()) {
        dir = "/usr/local";
      } else {
        dir = System.getProperty("user.home");
      }
    }

    // We determine the hostname and IPAdress
    String hostname;
    String IPAddress;

    try {
      InetAddress addr = InetAddress.getLocalHost();

      // Get IP Address
      IPAddress = addr.getHostAddress();

      // Get hostname
      hostname = addr.getHostName();
    } catch (Exception e) {
      hostname = "";
      IPAddress = "";
    }

    installdata.setVariable("APPLICATIONS_DEFAULT_ROOT", dir);
    dir += File.separator;
    installdata.setVariable(ScriptParser.JAVA_HOME, System.getProperty("java.home"));
    installdata.setVariable(ScriptParser.CLASS_PATH, System.getProperty("java.class.path"));
    installdata.setVariable(ScriptParser.USER_HOME, System.getProperty("user.home"));
    installdata.setVariable(ScriptParser.USER_NAME, System.getProperty("user.name"));
    installdata.setVariable(ScriptParser.IP_ADDRESS, IPAddress);
    installdata.setVariable(ScriptParser.HOST_NAME, hostname);
    installdata.setVariable(ScriptParser.FILE_SEPARATOR, File.separator);

    Enumeration e = System.getProperties().keys();
    while (e.hasMoreElements()) {
      String varName = (String) e.nextElement();
      String varValue = System.getProperty(varName);
      if (varValue != null) {
        varName = varName.replace('.', '_');
        installdata.setVariable("SYSTEM_" + varName, varValue);
      }
    }

    if (null != variables) {
      Enumeration enumeration = variables.keys();
      String varName;
      String varValue;
      while (enumeration.hasMoreElements()) {
        varName = (String) enumeration.nextElement();
        varValue = variables.getProperty(varName);
        installdata.setVariable(varName, varValue);
      }
    }

    installdata.info = inf;
    installdata.panelsOrder = panelsOrder;
    installdata.availablePacks = availablePacks;
    installdata.allPacks = allPacks;

    // get list of preselected packs
    Iterator pack_it = availablePacks.iterator();
    while (pack_it.hasNext()) {
      Pack pack = (Pack) pack_it.next();
      if (pack.preselected) {
        installdata.selectedPacks.add(pack);
      }
    }
    // Set the installation path in a default manner
    installPath = dir + inf.getAppName();
    if (inf.getInstallationSubPath() != null) { // A subpath was defined, use it.
      installPath =
          IoHelper.translatePath(
              dir + inf.getInstallationSubPath(),
              new VariableSubstitutor(installdata.getVariables()));
    }
    installdata.setInstallPath(installPath);
    // Load custom action data.
    loadCustomData(installdata);
  }
예제 #7
0
  protected void iterateAndPerformAction(String strAction) throws Exception {
    if (!checkInstallerRequirements(this.installdata)) {
      Debug.log("not all installerconditions are fulfilled.");
      return;
    }
    Debug.log("[ Starting console installation ] " + strAction);

    try {
      this.result = true;
      Iterator<Panel> panelsIterator = this.installdata.panelsOrder.iterator();
      this.installdata.curPanelNumber = -1;
      VariableSubstitutor substitutor = new VariableSubstitutor(this.installdata.getVariables());
      while (panelsIterator.hasNext()) {
        Panel p = (Panel) panelsIterator.next();
        this.installdata.curPanelNumber++;
        String praefix = "com.izforge.izpack.panels.";
        if (p.className.compareTo(".") > -1) {
          praefix = "";
        }
        if (!OsConstraint.oneMatchesCurrentSystem(p.osConstraints)) {
          continue;
        }
        String panelClassName = p.className;
        String consoleHelperClassName = praefix + panelClassName + "ConsoleHelper";
        Class<PanelConsole> consoleHelperClass = null;

        Debug.log("ConsoleHelper:" + consoleHelperClassName);
        try {

          consoleHelperClass = (Class<PanelConsole>) Class.forName(consoleHelperClassName);

        } catch (ClassNotFoundException e) {
          Debug.log("ClassNotFoundException-skip :" + consoleHelperClassName);
          continue;
        }
        PanelConsole consoleHelperInstance = null;
        if (consoleHelperClass != null) {
          try {
            Debug.log("Instantiate :" + consoleHelperClassName);
            refreshDynamicVariables(substitutor, installdata);
            consoleHelperInstance = consoleHelperClass.newInstance();
          } catch (Exception e) {
            Debug.log(
                "ERROR: no default constructor for " + consoleHelperClassName + ", skipping...");
            continue;
          }
        }

        if (consoleHelperInstance != null) {
          try {
            Debug.log(
                "consoleHelperInstance." + strAction + ":" + consoleHelperClassName + " entered.");
            boolean bActionResult = true;
            boolean bIsConditionFulfilled = true;
            String strCondition = p.getCondition();
            if (strCondition != null) {
              bIsConditionFulfilled = installdata.getRules().isConditionTrue(strCondition);
            }

            if (strAction.equals("doInstall") && bIsConditionFulfilled) {
              do {
                bActionResult = consoleHelperInstance.runConsole(this.installdata);
              } while (!validatePanel(p));
            } else if (strAction.equals("doGeneratePropertiesFile")) {
              bActionResult =
                  consoleHelperInstance.runGeneratePropertiesFile(
                      this.installdata, this.printWriter);
            } else if (strAction.equals("doInstallFromPropertiesFile") && bIsConditionFulfilled) {
              bActionResult =
                  consoleHelperInstance.runConsoleFromPropertiesFile(
                      this.installdata, this.properties);
            }
            if (!bActionResult) {
              this.result = false;
              return;
            } else {
              Debug.log(
                  "consoleHelperInstance."
                      + strAction
                      + ":"
                      + consoleHelperClassName
                      + " successfully done.");
            }
          } catch (Exception e) {
            Debug.log("ERROR: console installation failed for panel " + panelClassName);
            e.printStackTrace();
            this.result = false;
          }
        }
      }

      if (this.result) {
        System.out.println("[ Console installation done ]");
      } else {
        System.out.println("[ Console installation FAILED! ]");
      }
    } catch (Exception e) {
      this.result = false;
      System.err.println(e.toString());
      e.printStackTrace();
      System.out.println("[ Console installation FAILED! ]");
    }
  }