/**
  * Disables the debugging if debug endpoint's type is changed to 'Internal', and if private port
  * is modified then assigns the new debugging port by setting the modified endpoint as a debugging
  * endpoint.
  *
  * @param oldType : old type of the endpoint.
  * @return retVal : false if any error occurs.
  * @throws WindowsAzureInvalidProjectOperationException
  */
 private boolean handleChangeForDebugEndpt(WindowsAzureEndpointType oldType, String privatePort)
     throws WindowsAzureInvalidProjectOperationException {
   boolean retVal = true;
   if (oldType.equals(WindowsAzureEndpointType.Input)
       && comboType.getSelectedItem().equals(WindowsAzureEndpointType.Internal.toString())) {
     int choice =
         Messages.showYesNoDialog(
             String.format(
                 "%s%s%s", message("dlgEPDel"), message("dlgEPChangeType"), message("dlgEPDel2")),
             message("dlgTypeTitle"),
             Messages.getQuestionIcon());
     if (choice == Messages.YES) {
       waEndpt.setEndPointType((WindowsAzureEndpointType) comboType.getSelectedItem());
       waRole.setDebuggingEndpoint(null);
     } else {
       retVal = false;
     }
   } else if (privatePort == null) {
     PluginUtil.displayErrorDialog(message("dlgInvldPort"), message("dbgPort"));
     retVal = false;
   } else if (!waEndpt.getPrivatePort().equalsIgnoreCase(privatePort)) {
     boolean isSuspended = waRole.getStartSuspended();
     waRole.setDebuggingEndpoint(null);
     waEndpt.setPrivatePort(privatePort);
     waRole.setDebuggingEndpoint(waEndpt);
     waRole.setStartSuspended(isSuspended);
   }
   return retVal;
 }
 /**
  * Disables the debugging if debug endpoint's type is changed to 'Internal', and if private port
  * is modified then assigns the new debugging port by setting the modified endpoint as a debugging
  * endpoint.
  *
  * @param oldType : old type of the endpoint.
  * @return retVal : false if any error occurs.
  * @throws WindowsAzureInvalidProjectOperationException
  */
 private boolean handleChangeForDebugEndpt(WindowsAzureEndpointType oldType)
     throws WindowsAzureInvalidProjectOperationException {
   boolean retVal = true;
   if (oldType.equals(WindowsAzureEndpointType.Input)
       && comboType.getText().equalsIgnoreCase(WindowsAzureEndpointType.Internal.toString())) {
     StringBuffer msg = new StringBuffer(Messages.dlgEPDel);
     msg.append(Messages.dlgEPChangeType);
     msg.append(Messages.dlgEPDel2);
     boolean choice =
         MessageDialog.openQuestion(new Shell(), Messages.dlgTypeTitle, msg.toString());
     if (choice) {
       waEndpt.setEndPointType(WindowsAzureEndpointType.valueOf(comboType.getText()));
       windowsAzureRole.setDebuggingEndpoint(null);
     } else {
       retVal = false;
     }
   } else if (!waEndpt.getPrivatePort().equalsIgnoreCase(txtPrivatePort.getText())) {
     boolean isSuspended = windowsAzureRole.getStartSuspended();
     windowsAzureRole.setDebuggingEndpoint(null);
     waEndpt.setPrivatePort(txtPrivatePort.getText());
     windowsAzureRole.setDebuggingEndpoint(waEndpt);
     windowsAzureRole.setStartSuspended(isSuspended);
   }
   return retVal;
 }
 /**
  * This method sets the status of debug option based on the user input.If user checks the debug
  * check box first time then it will add a debugging end point otherwise it will prompt the user
  * for removal of associated end point for debugging if user already has some debug end point
  * associated and unchecked the debug check box.
  */
 private void debugOptionStatus() {
   if (debugCheck.isSelected()) {
     makeDebugEnable();
     try {
       waRole.setDebuggingEndpoint(dbgSelEndpoint);
       waRole.setStartSuspended(jvmCheck.isSelected());
     } catch (WindowsAzureInvalidProjectOperationException e1) {
       PluginUtil.displayErrorDialogAndLog(message("adRolErrTitle"), message("dlgDbgErr"), e1);
     }
   } else {
     if (isDebugChecked && !"".equals(comboEndPoint.getSelectedItem())) {
       String msg =
           String.format("%s%s", message("dlgDbgEdPtAscMsg"), comboEndPoint.getSelectedItem());
       int choice =
           Messages.showOkCancelDialog(
               msg, message("dlgDbgEndPtErrTtl"), Messages.getQuestionIcon());
       if (choice == Messages.OK) {
         removeDebugAssociatedEndpoint();
       } else {
         makeAllDisable();
         try {
           waRole.setDebuggingEndpoint(null);
         } catch (WindowsAzureInvalidProjectOperationException e) {
           PluginUtil.displayErrorDialogAndLog(message("adRolErrTitle"), message("dlgDbgErr"), e);
         }
       }
     } else {
       removeDebugAssociatedEndpoint();
     }
   }
 }
 /** Listener for remove button, which removes the environment variable from the role. */
 @SuppressWarnings("unchecked")
 protected void removeBtnListener() {
   int selIndex = tblViewer.getTable().getSelectionIndex();
   if (selIndex > -1) {
     try {
       Entry<String, String> mapEntry =
           (Entry<String, String>) tblViewer.getTable().getItem(selIndex).getData();
       // Check environment variable is associated with component
       if (windowsAzureRole.getIsEnvPreconfigured(mapEntry.getKey())) {
         errorTitle = Messages.jdkDsblErrTtl;
         errorMessage = Messages.envJdkDslErrMsg;
         MessageUtil.displayErrorDialog(getShell(), errorTitle, errorMessage);
       } else {
         boolean choice =
             MessageDialog.openQuestion(new Shell(), Messages.evRemoveTtl, Messages.evRemoveMsg);
         if (choice) {
           // to delete call rename with newName(second param) as empty
           windowsAzureRole.renameRuntimeEnv(mapEntry.getKey(), "");
           tblViewer.refresh();
         }
       }
     } catch (Exception ex) {
       errorTitle = Messages.adRolErrTitle;
       errorMessage = Messages.adRolErrMsgBox1 + Messages.adRolErrMsgBox2;
       MessageUtil.displayErrorDialog(this.getShell(), errorTitle, errorMessage);
       Activator.getDefault().log(errorMessage, ex);
     }
   }
 }
 /**
  * Validates public and private ports. And also makes changes corresponding to the debug endpoint.
  *
  * @param oldEndptName : old name of the endpoint.
  * @return retVal : false if any error occurs.
  * @throws WindowsAzureInvalidProjectOperationException
  */
 private boolean validatePorts(String oldEndptName)
     throws WindowsAzureInvalidProjectOperationException {
   boolean retVal = true;
   WindowsAzureEndpointType oldType = waEndpt.getEndPointType();
   WindowsAzureEndpoint debugEndpt = windowsAzureRole.getDebuggingEndpoint();
   WindowsAzureEndpoint stickyEndpt = windowsAzureRole.getSessionAffinityInputEndpoint();
   WindowsAzureEndpoint stickyIntEndpt = windowsAzureRole.getSessionAffinityInternalEndpoint();
   String stcEndptName = "";
   String dbgEndptName = "";
   String stcIntEndptName = "";
   if (debugEndpt != null) {
     // get the debugging endpoint name
     dbgEndptName = debugEndpt.getName();
   }
   if (stickyEndpt != null) {
     stcEndptName = stickyEndpt.getName();
     stcIntEndptName = stickyIntEndpt.getName();
   }
   // validate ports
   boolean isValidendpoint =
       windowsAzureRole.isValidEndpoint(
           oldEndptName,
           WindowsAzureEndpointType.valueOf(comboType.getText()),
           txtPrivatePort.getText(),
           txtPublicPort.getText());
   if (isValidendpoint) {
     if (oldEndptName.equalsIgnoreCase(dbgEndptName)) {
       retVal = handleChangeForDebugEndpt(oldType);
     }
     if (oldEndptName.equalsIgnoreCase(stcEndptName)) {
       retVal = handleChangeForStickyEndpt(oldType);
     }
     if (oldEndptName.equalsIgnoreCase(stcIntEndptName)) {
       retVal = handleChangeForStickyEndpt(oldType);
     }
     if (retVal) {
       // set the new values in the endpoint object.
       waEndpt.setEndPointType(WindowsAzureEndpointType.valueOf(comboType.getText()));
       waEndpt.setName(txtName.getText());
       if (comboType.getText().equalsIgnoreCase(WindowsAzureEndpointType.Input.toString())
           || comboType
               .getText()
               .equalsIgnoreCase(WindowsAzureEndpointType.InstanceInput.toString())) {
         waEndpt.setPort(txtPublicPort.getText());
       }
       waEndpt.setPrivatePort(txtPrivatePort.getText());
     }
   } else {
     errorTitle = Messages.dlgInvldPort;
     errorMessage = Messages.dlgPortInUse;
     MessageUtil.displayErrorDialog(this.getShell(), errorTitle, errorMessage);
     retVal = false;
   }
   return retVal;
 }
  /**
   * Creates a table viewer for environment variables table, which a) sets the input data for table
   * b) enables in-place modification.
   */
  private void createTableViewer() {
    tblViewer = new TableViewer(tblEnvVariables);

    tblViewer.setUseHashlookup(true);
    tblViewer.setColumnProperties(new String[] {Messages.evColName, Messages.evColValue});

    CellEditor[] editors = new CellEditor[2];

    editors[0] = new TextCellEditor(tblEnvVariables);
    editors[1] = new TextCellEditor(tblEnvVariables);

    tblViewer.setCellEditors(editors);
    tblViewer.setContentProvider(new EnvVarContentProvider());
    tblViewer.setLabelProvider(new EnvVarLabelProvider());
    tblViewer.setCellModifier(new EnvVarCellModifier());

    try {
      mapEnvVar = windowsAzureRole.getRuntimeEnv();
      tblViewer.setInput(mapEnvVar.entrySet().toArray());
    } catch (Exception ex) {
      errorTitle = Messages.rolsErr;
      errorMessage = Messages.adRolErrMsgBox1 + Messages.adRolErrMsgBox2;
      MessageUtil.displayErrorDialog(getShell(), errorTitle, errorMessage);
      Activator.getDefault().log(errorMessage, ex);
    }
  }
  /** 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);
    }
  }
  public static WindowsAzureRole configureKeyFeatures(
      WindowsAzureRole role, Map<String, Boolean> ftrMap) throws Exception {
    try {
      // Enable Key features
      // Session Affinity
      if (ftrMap.get("ssnAffChecked")) {
        WindowsAzureEndpoint httpEndPt = role.getEndpoint(httpEp);
        if (httpEndPt == null) {
          /*
           * server is not enabled.
           * hence create new endpoint
           * for session affinity.
           */
          if (role.isValidEndpoint(
              httpEp, WindowsAzureEndpointType.Input, HTTP_PRV_PORT, HTTP_PORT)) {
            httpEndPt =
                role.addEndpoint(httpEp, WindowsAzureEndpointType.Input, HTTP_PRV_PORT, HTTP_PORT);
          }
        }
        if (httpEndPt != null) {
          role.setSessionAffinityInputEndpoint(httpEndPt);
        }
      }

      // Caching
      if (ftrMap.get("cacheChecked")) {
        role.setCacheMemoryPercent(CACH_DFLTVAL);
        role.setCacheStorageAccountName(dashAuto);
      }

      // Remote Debugging
      if (ftrMap.get("debugChecked")) {
        if (role.isValidEndpoint(dbgEp, WindowsAzureEndpointType.Input, DEBUG_PORT, DEBUG_PORT)) {
          WindowsAzureEndpoint dbgEndPt =
              role.addEndpoint(dbgEp, WindowsAzureEndpointType.Input, DEBUG_PORT, DEBUG_PORT);
          if (dbgEndPt != null) {
            role.setDebuggingEndpoint(dbgEndPt);
            role.setStartSuspended(false);
          }
        }
      }

    } catch (Exception e) {
      throw new Exception(e.getMessage(), e);
    }
    return role;
  }
 @Override
 protected void okPressed() {
   boolean okToProceed = true;
   try {
     if (isEditEndpt) {
       // if its an edit an endpoint scenario
       okToProceed = editEndpt();
     } else {
       // for add an endpoint scenario
       boolean isValid = windowsAzureRole.isAvailableEndpointName(txtName.getText());
       if (isValid) {
         boolean isValidendpoint =
             windowsAzureRole.isValidEndpoint(
                 txtName.getText(),
                 WindowsAzureEndpointType.valueOf(comboType.getText()),
                 txtPrivatePort.getText(),
                 txtPublicPort.getText());
         if (isValidendpoint) {
           windowsAzureRole.addEndpoint(
               txtName.getText(),
               WindowsAzureEndpointType.valueOf(comboType.getText()),
               txtPrivatePort.getText(),
               txtPublicPort.getText());
         } else {
           errorTitle = Messages.dlgInvldPort;
           errorMessage = Messages.dlgPortInUse;
           MessageUtil.displayErrorDialog(this.getShell(), errorTitle, errorMessage);
           okToProceed = false;
         }
       } else {
         errorTitle = Messages.dlgInvdEdPtName1;
         errorMessage = Messages.dlgInvdEdPtName2;
         MessageUtil.displayErrorDialog(this.getShell(), errorTitle, errorMessage);
         okToProceed = false;
       }
     }
   } catch (WindowsAzureInvalidProjectOperationException e) {
     errorTitle = Messages.rolsErr;
     errorMessage = Messages.adRolErrMsgBox1 + Messages.adRolErrMsgBox2;
     MessageUtil.displayErrorDialog(this.getShell(), errorTitle, errorMessage);
     Activator.getDefault().log(errorMessage, e);
   }
   if (okToProceed) {
     super.okPressed();
   }
 }
 /**
  * This method populates the endpoint list every time we made any changes in the endpoint list.
  *
  * @throws com.interopbridges.tools.windowsazure.WindowsAzureInvalidProjectOperationException
  */
 private void populateEndPointList() throws WindowsAzureInvalidProjectOperationException {
   List<WindowsAzureEndpoint> endpointsList;
   endpointsList = new ArrayList<WindowsAzureEndpoint>(waRole.getEndpoints());
   comboEndPoint.removeAll();
   for (WindowsAzureEndpoint endpoint : endpointsList) {
     if (((endpoint.getEndPointType().equals(WindowsAzureEndpointType.Input)
                 && endpoint.getPrivatePort() != null)
             || endpoint.getEndPointType().equals(WindowsAzureEndpointType.InstanceInput))
         && !endpoint.equals(waRole.getSessionAffinityInputEndpoint())
         && !endpoint.equals(waRole.getSslOffloadingInputEndpoint())) {
       comboEndPoint.addItem(
           String.format(
               message("dbgEndPtStr"),
               endpoint.getName(),
               endpoint.getPort(),
               endpoint.getPrivatePort()));
     }
   }
 }
 /** This method removed the associated debug end point if debug check box get unchecked. */
 private void removeDebugAssociatedEndpoint() {
   List<WindowsAzureEndpoint> endpointsList;
   try {
     endpointsList = new ArrayList<WindowsAzureEndpoint>(waRole.getEndpoints());
     for (WindowsAzureEndpoint endpoint : endpointsList) {
       if (((String) comboEndPoint.getSelectedItem())
           .equalsIgnoreCase(
               String.format(
                   message("dbgEndPtStr"),
                   endpoint.getName(),
                   endpoint.getPort(),
                   endpoint.getPrivatePort()))) {
         endpoint.delete();
       }
     }
     comboEndPoint.removeAllItems();
     //            comboEndPoint.setText("");
     makeAllDisable();
     waRole.setDebuggingEndpoint(null);
   } catch (WindowsAzureInvalidProjectOperationException e) {
     PluginUtil.displayErrorDialogAndLog(message("adRolErrTitle"), message("dlgDbgErr"), e);
   }
 }
 /**
  * This method edits an endpoint. For editing it also validates endpoint name and ports.
  *
  * @return retVal : false if any error occurs.
  * @throws WindowsAzureInvalidProjectOperationException
  */
 private boolean editEndpt() throws WindowsAzureInvalidProjectOperationException {
   boolean retVal = true;
   String oldEndptName = waEndpt.getName();
   if (!oldEndptName.equalsIgnoreCase(txtName.getText())) {
     // validate endpoint name
     boolean isValid = windowsAzureRole.isAvailableEndpointName(txtName.getText());
     if (!isValid) {
       // if name is not valid
       errorTitle = Messages.dlgInvdEdPtName1;
       errorMessage = Messages.dlgInvdEdPtName2;
       MessageUtil.displayErrorDialog(this.getShell(), errorTitle, errorMessage);
       retVal = false;
     }
   }
   if (retVal) {
     retVal = validatePorts(oldEndptName);
   }
   return retVal;
 }
 @Override
 protected void doOKAction() {
   boolean retVal;
   try {
     String name = txtName.getText().trim();
     String thumb = txtThumb.getText().trim();
     retVal = validateNameAndThumbprint(name, thumb);
     if (retVal) {
       waRole.addCertificate(name, thumb.toUpperCase());
       certNameAdded = name;
     }
   } catch (Exception ex) {
     PluginUtil.displayErrorDialogAndLog(
         message("rolsErr"), message("adRolErrMsgBox1") + message("adRolErrMsgBox2"), ex);
     retVal = false;
   }
   if (retVal) {
     super.doOKAction();
   }
 }
 private void newBtnListener() {
   NewCertificateDialogData data = new NewCertificateDialogData();
   String jdkPath;
   try {
     jdkPath = waRole.getJDKSourcePath();
   } catch (Exception e) {
     jdkPath = "";
   }
   NewCertificateDialog dialog = new NewCertificateDialog(data, jdkPath, module.getProject());
   dialog.show();
   if (dialog.isOK()) {
     if (txtName.getText().isEmpty()) {
       populateCertName(CertificateDialogUtilMethods.removeSpaceFromCN(data.getCnName()));
     }
     try {
       txtThumb.setText(CerPfxUtil.getThumbPrint(data.getCerFilePath()));
     } catch (Exception e) {
       PluginUtil.displayErrorDialog(message("certErrTtl"), message("certImpEr"));
     }
   }
 }
 /**
  * This method edits an endpoint. For editing it also validates endpoint name and ports.
  *
  * @return retVal : false if any error occurs.
  * @throws WindowsAzureInvalidProjectOperationException
  */
 private boolean editEndpt() throws WindowsAzureInvalidProjectOperationException {
   boolean retVal = true;
   String oldEndptName = waEndpt.getName();
   String newEndptName = txtName.getText().trim();
   // validate endpoint name
   /*
    * Ignore if end point name is not edited.
    */
   if (!oldEndptName.equalsIgnoreCase(newEndptName)) {
     /*
      * Check endpoint name contain
      * alphanumeric and underscore characters only.
      * Starts with alphabet.
      */
     if (WAEclipseHelperMethods.isAlphaNumericUnderscore(newEndptName)) {
       /*
        * Check already used endpoint name is given.
        */
       boolean isValid =
           waRole.isAvailableEndpointName(
               newEndptName, (WindowsAzureEndpointType) comboType.getSelectedItem());
       if (!isValid) {
         // if name is not valid
         PluginUtil.displayErrorDialog(message("dlgInvdEdPtName1"), message("dlgInvdEdPtName2"));
         retVal = false;
       }
     } else {
       PluginUtil.displayErrorDialog(message("dlgInvdEdPtName1"), message("enPtAlphNuMsg"));
       retVal = false;
     }
   }
   if (retVal) {
     retVal = validatePorts(oldEndptName);
   }
   return retVal;
 }
  private void init() {
    try {
      WindowsAzureEndpoint endPt = waRole.getDebuggingEndpoint();
      if (endPt == null) {
        debugCheck.setSelected(false);
        comboEndPoint.removeAllItems(); // todo: ???
        makeAllDisable();
      } else {
        populateEndPointList();
        comboEndPoint.setSelectedItem(
            String.format(
                message("dbgEndPtStr"), endPt.getName(), endPt.getPort(), endPt.getPrivatePort()));
      }
    } catch (Exception e) {
      PluginUtil.displayErrorDialogAndLog(message("adRolErrTitle"), message("dlgDbgErr"), e);
    }
    isDebugChecked = false;
    try {
      isDebugChecked = waRole.getDebuggingEndpoint() != null;
    } catch (Exception ex) {
      // As getTitle() is also showing the error message if any exception
      // occurs in role.getDebuggingEndpoint(), so only logging
      // the exception. getTitle() gets called every time this page is
      // selected but createContents() is called only once while creating
      // the page.
      log(message("dlgDbgErr"), ex);
    }
    debugCheck.setSelected(isDebugChecked);
    debugCheck.addItemListener(createDebugCheckListener());
    try {
      populateEndPointList();
    } catch (WindowsAzureInvalidProjectOperationException e1) {
      PluginUtil.displayErrorDialogAndLog(message("adRolErrTitle"), message("dlgDbgErr"), e1);
    }
    comboEndPoint.addItemListener(createComboEndPointListener());

    try {
      if (isDebugChecked) {
        jvmCheck.setSelected(waRole.getStartSuspended());
      } else {
        jvmCheck.setSelected(false);
      }

    } catch (WindowsAzureInvalidProjectOperationException e2) {
      PluginUtil.displayErrorDialogAndLog(message("adRolErrTitle"), message("dlgDbgErr"), e2);
    }
    jvmCheck.addItemListener(createJvmCheckListener());
    createDebug.addActionListener(createCreateDebugListener());

    try {
      if (isDebugChecked) {
        WindowsAzureEndpoint endPt = waRole.getDebuggingEndpoint();
        comboEndPoint.setSelectedItem(
            String.format(
                message("dbgEndPtStr"), endPt.getName(), endPt.getPort(), endPt.getPrivatePort()));
      } else {
        makeAllDisable();
      }
    } catch (WindowsAzureInvalidProjectOperationException e1) {
      PluginUtil.displayErrorDialogAndLog(message("adRolErrTitle"), message("dlgDbgErr"), e1);
    }
    if (debugCheck.isSelected() && comboEndPoint.getSelectedItem().equals("")) {
      //            setValid(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);
    }
  }
  /**
   * Validates public and private ports. And also makes changes corresponding to the debug endpoint.
   *
   * @param oldEndptName : old name of the endpoint.
   * @return retVal : false if any error occurs.
   * @throws WindowsAzureInvalidProjectOperationException
   */
  private boolean validatePorts(String oldEndptName)
      throws WindowsAzureInvalidProjectOperationException {
    boolean retVal = true;
    boolean isDash = false;
    WindowsAzureEndpointType oldType = waEndpt.getEndPointType();
    WindowsAzureEndpoint debugEndpt = waRole.getDebuggingEndpoint();
    WindowsAzureEndpoint stickyEndpt = waRole.getSessionAffinityInputEndpoint();
    WindowsAzureEndpoint stickyIntEndpt = waRole.getSessionAffinityInternalEndpoint();
    String stcEndptName = "";
    String dbgEndptName = "";
    String stcIntEndptName = "";
    if (debugEndpt != null) {
      // get the debugging endpoint name
      dbgEndptName = debugEndpt.getName();
    }
    if (stickyEndpt != null) {
      stcEndptName = stickyEndpt.getName();
      stcIntEndptName = stickyIntEndpt.getName();
    }

    WindowsAzureEndpointType newType = (WindowsAzureEndpointType) comboType.getSelectedItem();
    if (newType.equals(WindowsAzureEndpointType.InstanceInput)
        || newType.equals(WindowsAzureEndpointType.Internal)) {
      isDash =
          WAEndpointDialogUtilMethods.isDashPresent(
              newType,
              txtPrivatePort.getText(),
              txtPrivatePortRangeEnd.getText(),
              txtPublicPort.getText(),
              txtPublicPortRangeEnd.getText());
    }
    if (isDash) {
      PluginUtil.displayErrorDialog(message("dlgInvldPort"), message("portRangeErrMsg"));
      retVal = false;
    } else {
      // Check for valid range 1 to 65535
      if (WAEndpointDialogUtilMethods.isValidPortRange(
          newType,
          txtPrivatePort.getText(),
          txtPrivatePortRangeEnd.getText(),
          txtPublicPort.getText(),
          txtPublicPortRangeEnd.getText())) {
        // validate ports
        String publicPort =
            WAEndpointDialogUtilMethods.combinePublicPortRange(
                txtPublicPort.getText(),
                txtPublicPortRangeEnd.getText(),
                comboType.getSelectedItem().toString());
        String privatePort =
            WAEndpointDialogUtilMethods.combinePrivatePortRange(
                txtPrivatePort.getText(),
                txtPrivatePortRangeEnd.getText(),
                comboType.getSelectedItem().toString());
        if (privatePort.equalsIgnoreCase(AUTO)) {
          privatePort = null;
        }

        boolean isValidendpoint =
            waRole.isValidEndpoint(oldEndptName, newType, privatePort, publicPort);
        if (isValidendpoint) {
          if (oldEndptName.equalsIgnoreCase(dbgEndptName)) {
            retVal = handleChangeForDebugEndpt(oldType, privatePort);
          }
          /** Disables the session affinity if endpoint's type is changed to 'Internal'. */
          if (oldEndptName.equalsIgnoreCase(stcEndptName)
              || oldEndptName.equalsIgnoreCase(stcIntEndptName)) {
            retVal = false;
          }
          if (retVal) {
            // set the new values in the endpoint object.
            waEndpt.setEndPointType((WindowsAzureEndpointType) comboType.getSelectedItem());
            waEndpt.setName(txtName.getText());
            /*
             * Type is Input or Instance then
             * set public port as well as private port.
             */
            if (comboType.getSelectedItem() == WindowsAzureEndpointType.Input
                || comboType.getSelectedItem() == WindowsAzureEndpointType.InstanceInput) {
              waEndpt.setPort(publicPort);
            }
            /*
             * Type is Internal then
             * set private port only.
             */
            waEndpt.setPrivatePort(privatePort);
          }
        } else {
          PluginUtil.displayErrorDialog(message("dlgInvldPort"), message("dlgPortInUse"));
          retVal = false;
        }
      } else {
        PluginUtil.displayErrorDialog(message("dlgInvldPort"), message("rngErrMsg"));
        retVal = false;
      }
    }
    return retVal;
  }
 public void doOKAction() {
   try {
     if (waEndpt != null) {
       // Edit an endpoint scenario
       if (!editEndpt()) {
         return;
       }
     } else {
       // Add an endpoint scenario
       // validate name
       WindowsAzureEndpointType endPtType = (WindowsAzureEndpointType) comboType.getSelectedItem();
       String endPtName = txtName.getText().trim();
       /*
        * Check endpoint name contain
        * alphanumeric and underscore characters only.
        * Starts with alphabet.
        */
       if (WAEclipseHelperMethods.isAlphaNumericUnderscore(endPtName)) {
         boolean isValidName = waRole.isAvailableEndpointName(endPtName, endPtType);
         /*
          * Check already used endpoint name is given.
          */
         if (isValidName) {
           if (endPtType.equals(WindowsAzureEndpointType.InstanceInput)
               || endPtType.equals(WindowsAzureEndpointType.Internal)) {
             if (WAEndpointDialogUtilMethods.isDashPresent(
                 endPtType,
                 txtPrivatePort.getText(),
                 txtPrivatePortRangeEnd.getText(),
                 txtPublicPort.getText(),
                 txtPublicPortRangeEnd.getText())) {
               PluginUtil.displayErrorDialog(message("dlgInvldPort"), message("portRangeErrMsg"));
               return;
             }
           }
           // Check for valid range 1 to 65535
           if (WAEndpointDialogUtilMethods.isValidPortRange(
               endPtType,
               txtPrivatePort.getText(),
               txtPrivatePortRangeEnd.getText(),
               txtPublicPort.getText(),
               txtPublicPortRangeEnd.getText())) {
             // Combine port range
             String publicPort =
                 WAEndpointDialogUtilMethods.combinePublicPortRange(
                     txtPublicPort.getText(),
                     txtPublicPortRangeEnd.getText(),
                     endPtType.toString());
             String privatePort =
                 WAEndpointDialogUtilMethods.combinePrivatePortRange(
                     txtPrivatePort.getText(),
                     txtPrivatePortRangeEnd.getText(),
                     endPtType.toString());
             if (privatePort.equalsIgnoreCase(AUTO)) {
               privatePort = null;
             }
             // Validate and commit endpoint addition
             if (waRole.isValidEndpoint(endPtName, endPtType, privatePort, publicPort)) {
               waRole.addEndpoint(endPtName, endPtType, privatePort, publicPort);
             } else {
               PluginUtil.displayErrorDialog(message("dlgInvldPort"), message("dlgPortInUse"));
               return;
             }
           } else {
             PluginUtil.displayErrorDialog(message("dlgInvldPort"), message("rngErrMsg"));
             return;
           }
         } else {
           PluginUtil.displayErrorDialog(message("dlgInvdEdPtName1"), message("dlgInvdEdPtName2"));
           return;
         }
       } else {
         PluginUtil.displayErrorDialog(message("dlgInvdEdPtName1"), message("enPtAlphNuMsg"));
         return;
       }
     }
   } catch (WindowsAzureInvalidProjectOperationException ex) {
     PluginUtil.displayErrorDialogAndLog(
         message("rolsErr"), message("adRolErrMsgBox1") + message("adRolErrMsgBox2"), ex);
     return;
   }
   super.doOKAction();
 }
  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;
  }
  /**
   * Method creates tree structure of windows azure property pages. and opens property dialog with
   * desired property page selected & active.
   *
   * @param windowsAzureRole : worker role
   * @param pageToDisplay : property page Id which should be active after opening dialog
   * @return integer
   */
  public static int openRolePropertyDialog(
      WindowsAzureRole windowsAzureRole, String pageToDisplay) {
    int retVal = Window.CANCEL; // value corresponding to cancel
    try {
      // Node creation
      PreferenceNode nodeGeneral =
          new PreferenceNode(
              Messages.cmhIdGeneral, Messages.cmhLblGeneral, null, WARGeneral.class.toString());
      nodeGeneral.setPage(new WARGeneral());
      nodeGeneral.getPage().setTitle(Messages.cmhLblGeneral);

      PreferenceNode nodeCache =
          new PreferenceNode(
              Messages.cmhIdCach, Messages.cmhLblCach, null, WARCaching.class.toString());
      nodeCache.setPage(new WARCaching());
      nodeCache.getPage().setTitle(Messages.cmhLblCach);

      PreferenceNode nodeCmpnts =
          new PreferenceNode(
              Messages.cmhIdCmpnts, Messages.cmhLblCmpnts, null, WARComponents.class.toString());
      nodeCmpnts.setPage(new WARComponents());
      nodeCmpnts.getPage().setTitle(Messages.cmhLblCmpnts);

      PreferenceNode nodeDebugging =
          new PreferenceNode(
              Messages.cmhIdDbg, Messages.cmhLblDbg, null, WARDebugging.class.toString());
      nodeDebugging.setPage(new WARDebugging());
      nodeDebugging.getPage().setTitle(Messages.cmhLblDbg);

      PreferenceNode nodeEndPts =
          new PreferenceNode(
              Messages.cmhIdEndPts, Messages.cmhLblEndPts, null, WAREndpoints.class.toString());
      nodeEndPts.setPage(new WAREndpoints());
      nodeEndPts.getPage().setTitle(Messages.cmhLblEndPts);

      PreferenceNode nodeEnvVars =
          new PreferenceNode(
              Messages.cmhIdEnvVars, Messages.cmhLblEnvVars, null, WAREnvVars.class.toString());
      nodeEnvVars.setPage(new WAREnvVars());
      nodeEnvVars.getPage().setTitle(Messages.cmhLblEnvVars);

      PreferenceNode nodeLdBlnc =
          new PreferenceNode(
              Messages.cmhIdLdBlnc, Messages.cmhLblLdBlnc, null, WARLoadBalance.class.toString());
      nodeLdBlnc.setPage(new WARLoadBalance());
      nodeLdBlnc.getPage().setTitle(Messages.cmhLblLdBlnc);

      PreferenceNode nodeLclStg =
          new PreferenceNode(
              Messages.cmhIdLclStg, Messages.cmhLblLclStg, null, WARLocalStorage.class.toString());
      nodeLclStg.setPage(new WARLocalStorage());
      nodeLclStg.getPage().setTitle(Messages.cmhLblLclStg);

      PreferenceNode nodeSrvCnfg =
          new PreferenceNode(
              Messages.cmhIdSrvCnfg,
              Messages.cmhLblSrvCnfg,
              null,
              WAServerConfiguration.class.toString());
      nodeSrvCnfg.setPage(new WAServerConfiguration());
      nodeSrvCnfg.getPage().setTitle(Messages.cmhLblSrvCnfg);

      /*
       * Tree structure creation.
       * Don't change order while adding nodes.
       * Its the default alphabetical order given by eclipse.
       */
      nodeGeneral.add(nodeCache);
      nodeGeneral.add(nodeCmpnts);
      nodeGeneral.add(nodeDebugging);
      nodeGeneral.add(nodeEndPts);
      nodeGeneral.add(nodeEnvVars);
      nodeGeneral.add(nodeLdBlnc);
      nodeGeneral.add(nodeLclStg);
      nodeGeneral.add(nodeSrvCnfg);

      PreferenceManager mgr = new PreferenceManager();
      mgr.addToRoot(nodeGeneral);
      // Dialog creation
      PreferenceDialog dialog =
          new PreferenceDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), mgr);
      // make desired property page active.
      dialog.setSelectedNode(pageToDisplay);
      dialog.create();
      String dlgTitle = String.format(Messages.cmhPropFor, windowsAzureRole.getName());
      dialog.getShell().setText(dlgTitle);
      dialog.open();
      // return whether user has pressed OK or Cancel button
      retVal = dialog.getReturnCode();
    } catch (Exception ex) {
      PluginUtil.displayErrorDialogAndLog(
          new Shell(), Messages.rolsDlgErr, Messages.rolsDlgErrMsg, ex);
    }
    return retVal;
  }
  @Override
  protected void okPressed() {
    boolean isValid = true;
    if ((fileRadioBtn.getSelection() && !fileTxt.getText().isEmpty())) {
      File file = new File(fileTxt.getText());
      if (!file.exists()) {
        isValid = false;
        PluginUtil.displayErrorDialog(
            this.getShell(), Messages.appDlgInvFileTtl, Messages.appDlgInvFileMsg);
      }
    } else if (projRadioBtn.getSelection()
        && !asNameTxt.getText().isEmpty()
        && !projCombo.getText().isEmpty()) {
      boolean isValidName = true;
      try {
        isValidName = windowsAzureRole.isValidDeployName(asNameTxt.getText());
      } catch (Exception e) {
        isValidName = false;
      }
      if (!isValidName) {
        isValid = false;
        PluginUtil.displayErrorDialog(
            this.getShell(), Messages.appDlgInvNmeTtl, Messages.appDlgInvNmeMsg);
      }
    }
    if (isValid) {
      ArrayList<String> cmpList = null;
      if (depPage == null) {
        cmpList = serverConf.getAppsAsNames();
      } else {
        cmpList = depPage.getAppsAsNames();
      }

      if (fileRadioBtn.getSelection()) {
        if (cmpList.contains(new File(fileTxt.getText()).getName())) {
          PluginUtil.displayErrorDialog(
              this.getShell(), Messages.appDlgDupNmeTtl, Messages.appDlgDupNmeMsg);
          return;
        }
        try {
          List<WindowsAzureRoleComponent> components = windowsAzureRole.getComponents();
          for (int i = 0; i < components.size(); i++) {
            if (components
                .get(i)
                .getDeployName()
                .equalsIgnoreCase(new File(fileTxt.getText()).getName())) {
              PluginUtil.displayErrorDialog(
                  this.getShell(), Messages.appDlgDupNmeTtl, Messages.appDlgDupNmeMsg);
              return;
            }
          }
        } catch (WindowsAzureInvalidProjectOperationException e) {
          PluginUtil.displayErrorDialogAndLog(
              this.getShell(), Messages.addAppErrTtl, Messages.addAppErrMsg, e);
        }

        if (depPage == null) {
          serverConf.addToAppList(
              fileTxt.getText(), new File(fileTxt.getText()).getName(), Messages.methodCopy);
        } else {
          depPage.addToAppList(
              fileTxt.getText(), new File(fileTxt.getText()).getName(), Messages.methodCopy);
        }

      } else if (projRadioBtn.getSelection()) {
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot root = workspace.getRoot();
        IProject proj = root.getProject(projCombo.getText());
        if (cmpList.contains(new File(asNameTxt.getText()).getName())) {
          PluginUtil.displayErrorDialog(
              this.getShell(), Messages.appDlgDupNmeTtl, Messages.appDlgDupNmeMsg);
          return;
        }
        if (depPage == null) {
          serverConf.addToAppList(
              proj.getLocation().toOSString(), asNameTxt.getText(), Messages.methodAuto);
        } else {
          depPage.addToAppList(
              proj.getLocation().toOSString(), asNameTxt.getText(), Messages.methodAuto);
        }
      }
      super.okPressed();
    }
  }