/** Default constructor. */
  public WAProjectWizard() {
    setWindowTitle(Messages.pWizWindowTitle);
    String zipFile = "";
    try {
      zipFile =
          String.format(
              "%s%s%s%s%s",
              PluginUtil.pluginFolder,
              File.separator,
              Messages.pluginId,
              File.separator,
              Messages.starterKitFileName);

      // Extract the WAStarterKitForJava.zip to temp dir
      waProjMgr = WindowsAzureProjectManager.create(zipFile);
      //	By deafult - disabling remote access
      //  when creating new project
      waProjMgr.setRemoteAccessAllRoles(false);
      waProjMgr.setClassPathInPackage("azure.lib.dir", PluginUtil.getAzureLibLocation());
      waRole = waProjMgr.getRoles().get(0);
      // remove http endpoint
      WindowsAzureEndpoint endpoint = waRole.getEndpoint(Messages.httpEp);
      if (endpoint != null) {
        endpoint.delete();
      }
    } catch (IOException e) {
      PluginUtil.displayErrorDialogAndLog(
          this.getShell(), Messages.pWizErrTitle, Messages.pWizErrMsg, e);
    } catch (Exception e) {
      errorTitle = Messages.adRolErrTitle;
      errorMessage = Messages.pWizErrMsgBox1 + Messages.pWizErrMsgBox2;
      PluginUtil.displayErrorDialogAndLog(this.getShell(), errorTitle, errorMessage, e);
    }
  }
 /**
  * If project name present in package.xml and WindowsAzureProjectBuilder.launch does not match
  * with the actual one then correct it accordingly.
  *
  * @param project
  * @param mngr : WindowsAzureProjectManager
  */
 public static void correctProjectName(IProject project, WindowsAzureProjectManager mngr) {
   String strPath = project.getLocation().toOSString();
   String launchFile =
       strPath
           + File.separator
           + Messages.resCLExtToolBldr
           + File.separator
           + Messages.resCLLaunchFile;
   try {
     ParseXML.setProjectNameinLaunch(launchFile, mngr.getProjectName(), project.getName());
     mngr.setProjectName(project.getName());
     mngr.save();
   } catch (Exception e) {
     Activator.getDefault().log(e.getMessage());
   }
 }
  /** Add page to the wizard. */
  @Override
  public void addPages() {
    String sdkPath = null;
    if (Activator.IS_WINDOWS) {
      try {
        sdkPath = WindowsAzureProjectManager.getLatestAzureSdkDir();
      } catch (IOException e) {
        sdkPath = null;
        Activator.getDefault().log(errorMessage, e);
      }
    } else {
      Activator.getDefault().log("Not Windows OS, skipping getSDK");
    }
    try {
      if (sdkPath == null && Activator.IS_WINDOWS) {
        errorTitle = Messages.sdkInsErrTtl;
        errorMessage = Messages.sdkInsErrMsg;
        boolean choice = MessageDialog.openQuestion(getShell(), errorTitle, errorMessage);
        if (choice) {
          PlatformUI.getWorkbench()
              .getBrowserSupport()
              .getExternalBrowser()
              .openURL(new URL(Messages.sdkInsUrl));
        }
        addPage(null);
      } else {
        waProjWizPage = new WAProjectWizardPage(Messages.projWizPg);
        tabPg = new WATabPage(Messages.tbPg, waRole, this, true);
        /*
         * If wizard activated through right click on
         * Dynamic web project then
         * Add that as an WAR application.
         */
        if (Activator.getDefault().isContextMenu()) {
          IProject selProj = getSelectProject();
          tabPg.addToAppList(
              selProj.getLocation().toOSString(),
              selProj.getName() + ".war",
              WindowsAzureRoleComponentImportMethod.auto.name());
        }

        waKeyPage = new WAKeyFeaturesPage(Messages.keyPg);
        addPage(waProjWizPage);
        addPage(tabPg);
        addPage(waKeyPage);
      }
    } catch (Exception ex) {
      // only logging the error in log file not showing anything to
      // end user
      Activator.getDefault().log(errorMessage, ex);
    }
  }
 @Override
 public boolean performOk() {
   boolean okToProceed = true;
   try {
     if (!Activator.getDefault().isSaved()) {
       waProjManager.save();
       Activator.getDefault().setSaved(true);
     }
     WAEclipseHelper.refreshWorkspace(Messages.rolsRefTitle, Messages.rolsRefMsg);
   } catch (WindowsAzureInvalidProjectOperationException e) {
     errorTitle = Messages.adRolErrTitle;
     errorMessage = Messages.adRolErrMsgBox1 + Messages.adRolErrMsgBox2;
     MessageUtil.displayErrorDialog(this.getShell(), errorTitle, errorMessage);
     Activator.getDefault().log(errorMessage, e);
     okToProceed = false;
   }
   if (okToProceed) {
     okToProceed = super.performOk();
   }
   return okToProceed;
 }
  public void actionPerformed(AnActionEvent event) {
    try {
      String strKitLoc = WAHelper.getTemplateFile(message("pWizStarterKit"));
      StringBuilder output = new StringBuilder();
      ZipFile zipFile = new ZipFile(strKitLoc);

      // copy elevate.vbs to temp location
      String tmpPath = System.getProperty("java.io.tmpdir");
      FileUtil.copyFileFromZip(
          new File(strKitLoc),
          "%proj%/.templates/emulatorTools/.elevate.vbs",
          new File(String.format("%s%s%s", tmpPath, File.separator, ".elevate.vbs")));

      @SuppressWarnings("rawtypes")
      Enumeration entries = zipFile.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        if (entry.getName().toLowerCase().indexOf(message("rstEmCmd")) != -1) {
          InputStream in = zipFile.getInputStream(entry);
          Reader reader = new InputStreamReader(in);
          char[] buf = new char[BUFF_SIZE];
          int length = reader.read(buf, 0, buf.length);
          while (length > 0) {
            output.append(buf, 0, length);
            length = reader.read(buf, 0, buf.length);
          }
          break;
        }
      }
      zipFile.close();
      WindowsAzureProjectManager.resetEmulator(output.toString());
    } catch (WindowsAzureInvalidProjectOperationException e) {
      PluginUtil.displayErrorDialogAndLog(message("rstEmltrErrTtl"), message("rstEmuErrMsg"), e);
    } catch (IOException e1) {
      AzurePlugin.log(message("ioErrMsg"), e1);
    }
  }
 @Override
 public void apply() throws ConfigurationException {
   // check for child window's OK button was pressed or not
   // if not then we do not need to create a debug configuration otherwise
   // we do need to create debug configuration based on the user
   // selected options.
   if (childOk) {
     String emuCheck = debugMap.get(message("dlgDbgEmuChkd"));
     String cloudCheck = debugMap.get(message("dlgDbgCldChkd"));
     if (emuCheck != null && emuCheck.equals("true")) {
       // todo!!!
       //                createLaunchConfig(
       //                        debugMap.get(Messages.dlgDbgEmuConf),
       //                        debugMap.get(Messages.dlgDbgEmuProj),
       //                        debugMap.get(Messages.dlgDbgEmuHost),
       //                        debugMap.get(Messages.dlgDbgEmuPort));
     }
     if (cloudCheck != null && cloudCheck.equals("true")) {
       //                createLaunchConfig(
       //                        debugMap.get(Messages.dlgDbgCldConf),
       //                        debugMap.get(Messages.dlgDbgCldProj),
       //                        debugMap.get(Messages.dlgDbgCldHost),
       //                        debugMap.get(Messages.dlgDbgCldPort));
     }
   }
   boolean okToProceed = true;
   try {
     waProjManager.save();
   } catch (WindowsAzureInvalidProjectOperationException e) {
     PluginUtil.displayErrorDialogAndLog(
         message("adRolErrTitle"), message("adRolErrMsgBox1") + message("adRolErrMsgBox2"), e);
     throw new ConfigurationException(
         message("adRolErrMsgBox1") + message("adRolErrMsgBox2"), message("adRolErrTitle"));
   }
   myModified = false;
 }
  /**
   * Move the project structure to the location provided by user. Also configure JDK, server, server
   * application and key features like session affinity, caching, debugging if user wants to do so.
   *
   * @param projName : Name of the project
   * @param projLocation : Location of the project
   * @param isDefault : whether location of project is default
   * @param selWorkingSets
   * @param workingSetManager
   * @param depMap : stores configurations done on WATagPage
   * @param ftrMap : stores configurations done on WAKeyFeaturesPage
   * @param selProj
   */
  private void doFinish(
      String projName,
      String projLocation,
      boolean isDefault,
      IWorkingSet[] selWorkingSets,
      IWorkingSetManager workingSetManager,
      Map<String, String> depMap,
      Map<String, Boolean> ftrMap,
      IProject selProj) {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    IProject project = null;
    try {
      WindowsAzureRole role = waProjMgr.getRoles().get(0);
      // logic for handling deploy page components and their values.
      if (!depMap.isEmpty()) {
        File templateFile = new File(depMap.get("tempFile"));
        role = WizardUtilMethods.configureJDKServer(role, depMap);
        /*
         * Handling adding server application
         * without configuring server/JDK.
         * Always add cloud attributes as
         * approot directory is not created yet
         * hence all applications are
         * imported from outside of the Azure project
         */
        if (!tabPg.getAppsAsNames().isEmpty()) {
          for (int i = 0; i < tabPg.getAppsList().size(); i++) {
            AppCmpntParam app = tabPg.getAppsList().get(i);
            if (!app.getImpAs().equalsIgnoreCase(Messages.helloWorld)) {
              role.addServerApplication(
                  app.getImpSrc(), app.getImpAs(), app.getImpMethod(), templateFile, true);
            }
          }
        }
      }

      /** Handling for HelloWorld application in plug-in */
      if (tabPg != null) {
        if (!tabPg.getAppsAsNames().contains(Messages.helloWorld)) {
          List<WindowsAzureRoleComponent> waCompList =
              waProjMgr.getRoles().get(0).getServerApplications();
          for (WindowsAzureRoleComponent waComp : waCompList) {
            if (waComp.getDeployName().equalsIgnoreCase(Messages.helloWorld)
                && waComp.getImportPath().isEmpty()) {
              waComp.delete();
            }
          }
        }
      }
      role = WizardUtilMethods.configureKeyFeatures(role, ftrMap);

      waProjMgr.save();
      WindowsAzureProjectManager.moveProjFromTemp(projName, projLocation);
      String launchFilePath = projLocation + File.separator + projName + LAUNCH_FILE_PATH;
      ParseXML.setProjectNameinLaunch(launchFilePath, Messages.pWizWinAzureProj, projName);

      root.touch(null);
      project = root.getProject(projName);
      IProjectDescription projDescription = workspace.newProjectDescription(projName);

      Path path = new Path(projLocation + File.separator + projName);
      projDescription.setLocation(path);
      projDescription.setNatureIds(new String[] {WAProjectNature.NATURE_ID});

      if (!project.exists()) {
        if (isDefault) {
          project.create(null);
        } else {
          project.create(projDescription, null);
        }
      }
      project.open(null);

      projDescription = project.getDescription();
      projDescription.setName(projName);
      projDescription.setNatureIds(new String[] {WAProjectNature.NATURE_ID});

      project.move(projDescription, IResource.FORCE, null);

      workingSetManager.addToWorkingSets(project, selWorkingSets);

      root.touch(null);
      if (project != null) {
        WADependencyBuilder builder = new WADependencyBuilder();
        builder.addBuilder(project, "com.persistent.winazure.eclipseplugin.Builder");
      }
    } catch (Exception e) {
      Display.getDefault()
          .syncExec(
              new Runnable() {
                public void run() {
                  MessageDialog.openError(null, Messages.pWizErrTitle, Messages.pWizErrMsg);
                }
              });
      Activator.getDefault().log(Messages.pWizErrMsg, e);
    }
  }
  public static WindowsAzureRole configureJDKServer(
      WindowsAzureRole role, Map<String, String> depMap) throws Exception {
    try {
      File templateFile = new File(depMap.get("tempFile"));
      if (!(depMap.get("jdkChecked").equalsIgnoreCase("false")
          && depMap.get("jdkAutoDwnldChecked").equalsIgnoreCase("true"))) {
        // Third party JDK name
        if (depMap.get("jdkThrdPartyChecked").equalsIgnoreCase("true")) {
          String jdkName = depMap.get("jdkName");
          role.setJDKSourcePath(depMap.get("jdkLoc"), templateFile, jdkName);
          role.setJDKCloudName(jdkName);
        } else {
          role.setJDKSourcePath(depMap.get("jdkLoc"), templateFile, "");
        }
        // JDK download group
        // By default auto upload will be selected.
        String jdkTabUrl = depMap.get("jdkUrl");
        if (depMap.get("jdkAutoDwnldChecked").equalsIgnoreCase("true")
            || depMap.get("jdkThrdPartyChecked").equalsIgnoreCase("true")) {
          if (jdkTabUrl.equalsIgnoreCase(AUTO_TXT)) {
            jdkTabUrl = auto;
          }
          role.setJDKCloudUploadMode(WARoleComponentCloudUploadMode.auto);
        }
        role.setJDKCloudURL(jdkTabUrl);
        role.setJDKCloudKey(depMap.get("jdkKey"));
        /*
         * By default package type is local,
         * hence store JAVA_HOME for cloud.
         */
        role.setJDKCloudHome(depMap.get("javaHome"));
      }

      // Server
      if (depMap.get("serChecked").equalsIgnoreCase("true")) {
        String srvName = depMap.get("servername");
        if (!srvName.isEmpty()) {
          String srvPriPort = WindowsAzureProjectManager.getHttpPort(srvName, templateFile);
          if (role.isValidEndpoint(httpEp, WindowsAzureEndpointType.Input, srvPriPort, HTTP_PORT)) {
            role.addEndpoint(httpEp, WindowsAzureEndpointType.Input, srvPriPort, HTTP_PORT);
          }

          role.setServer(srvName, depMap.get("serLoc"), templateFile);

          if (depMap.get("srvThrdPartyChecked").equalsIgnoreCase("true")) {
            String altSrcUrl = depMap.get("srvThrdAltSrc");
            if (!altSrcUrl.isEmpty()) {
              role.setServerCldAltSrc(altSrcUrl);
            }
            String thrdName = depMap.get("srvThrdPartyName");
            if (!thrdName.isEmpty()) {
              role.setServerCloudName(thrdName);
            }
            role.setServerCloudValue(depMap.get("srvHome"));
          }

          String srvTabUrl = depMap.get("srvUrl");
          if (depMap.get("srvAutoDwnldChecked").equalsIgnoreCase("true")
              || depMap.get("srvThrdPartyChecked").equalsIgnoreCase("true")) {
            if (srvTabUrl.equalsIgnoreCase(AUTO_TXT)) {
              srvTabUrl = auto;
            }
            role.setServerCloudUploadMode(WARoleComponentCloudUploadMode.auto);
          }
          role.setServerCloudURL(srvTabUrl);
          role.setServerCloudKey(depMap.get("srvKey"));
          role.setServerCloudHome(depMap.get("srvHome"));
        }
      }
    } catch (Exception e) {
      throw new Exception(e.getMessage(), e);
    }
    return role;
  }
  /**
   * Returns the server name whose detection patterns is matched under path.
   *
   * @param serverDetectors
   * @param path
   * @return
   */
  public static String detectServer(File path) {
    Map<String, String> serverDetectors;

    // Get the templates files
    String templateFilePath = WAEclipseHelper.getTemplateFile();
    if (templateFilePath == null || path == null || !path.isDirectory() || !path.exists()) {
      return null;
    }

    // Get the server detectors from the templates
    try {
      if (null
          == (serverDetectors =
              WindowsAzureProjectManager.getServerTemplateDetectors(new File(templateFilePath)))) {
        return null;
      }
    } catch (WindowsAzureInvalidProjectOperationException e) {
      return null;
    }

    // Check each pattern
    for (Map.Entry<String, String> entry : serverDetectors.entrySet()) {
      String serverName = entry.getKey();
      String patternText = entry.getValue();
      if (patternText == null || patternText.isEmpty()) {
        continue;
      }

      /*
       * Fast path: Check the pattern directly
       * (like, if it has no wild cards)
       */
      File basePathFile = new File(path, patternText);
      if (basePathFile.exists()) {
        return serverName;
      }

      /*
       * Split pattern path into parts
       * and check for existence of each part
       */
      basePathFile = path;
      String[] pathParts = patternText.split("\\\\");
      boolean foundSoFar = false;
      for (int i = 0; i < pathParts.length; i++) {
        String pathPart = pathParts[i];
        // Try direct match first
        File pathPartFile = new File(basePathFile, pathPart);
        if (pathPartFile.exists()) {
          foundSoFar = true;
          // Check for wildcards
        } else if (!pathPart.contains("*") && !pathPart.contains("?")) {
          foundSoFar = false;
          // Wildcards present, so check pattern
        } else {
          String[] fileNames = basePathFile.list();
          String patternRegex = windowsPathToRegex(pathPart) + "$";
          Pattern pattern = Pattern.compile(patternRegex);
          Matcher matcher = pattern.matcher("");
          foundSoFar = false;
          for (String fileName : fileNames) {
            matcher.reset(fileName);
            if (matcher.find()) {
              foundSoFar = true;
              break;
            }
          }
        }

        if (foundSoFar) {
          basePathFile = new File(basePathFile, pathPart);
        } else {
          break;
        }
      }

      if (foundSoFar) {
        return serverName;
      }
    }
    // No matches found
    return null;
  }