public static void launchBrowserSim(String initialUrl) {
    Activator.getDefault().countLaunchEvent();
    List<String> parameters = new ArrayList<String>();

    parameters.add(NOT_STANDALONE);
    if (initialUrl != null) {
      parameters.add(initialUrl);
    }

    IVMInstall jvm = getSelectedVM();
    if (jvm == null) { // no suitable vm
      ExternalProcessLauncher.showErrorDialog(Messages.BrowserSim);
    } else {
      String jvmPath = jvm.getInstallLocation().getAbsolutePath();
      String jrePath =
          jvm.getInstallLocation().getAbsolutePath() + File.separator + "jre"; // $NON-NLS-1$

      List<String> bundles = getBundles();

      if (!ExternalProcessLauncher.isGTK2()
          || (!BrowserSimUtil.isJavaFxAvailable(jvmPath)
              && !BrowserSimUtil.isJavaFxAvailable(jrePath))) {
        bundles.add("org.jboss.tools.vpe.browsersim.javafx.mock"); // $NON-NLS-1$
      }

      ExternalProcessLauncher.launchAsExternalProcess(
          bundles,
          RESOURCES_BUNDLES,
          BROWSERSIM_CALLBACKS,
          BROWSERSIM_CLASS_NAME,
          parameters,
          Messages.BrowserSim,
          jvm);
    }
  }
  public static void launchCordovaSim(List<String> parameters) {
    Activator.getDefault().countLaunchEvent();
    IVMInstall jvm = BrowserSimLauncher.getSelectedVM();
    if (jvm == null) { // no suitable vm
      ExternalProcessLauncher.showErrorDialog(Messages.CordovaSimLauncher_CORDOVASIM);
    } else {
      String jvmPath = jvm.getInstallLocation().getAbsolutePath();
      String jrePath =
          jvm.getInstallLocation().getAbsolutePath() + File.separator + "jre"; // $NON-NLS-1$

      List<String> bundles = getBundles();

      if (!ExternalProcessLauncher.isGTK2()
          || (!JavaFXUtil.isJavaFXAvailable(jvmPath) && !JavaFXUtil.isJavaFXAvailable(jrePath))) {
        bundles.add("org.jboss.tools.browsersim.javafx.mock"); // $NON-NLS-1$
      }

      ExternalProcessLauncher.launchAsExternalProcess(
          bundles,
          RESOURCES_BUNDLES,
          getJettyBundles(),
          CORDOVASIM_CALLBACKS,
          CORDOVASIM_CLASS_NAME,
          parameters,
          Messages.CordovaSimLauncher_CORDOVASIM,
          jvm);
    }
  }
  /**
   * Adds a duplicate of the selected VM to the block
   *
   * @since 3.2
   */
  protected void copyVM() {
    IStructuredSelection selection = (IStructuredSelection) fVMList.getSelection();
    Iterator<IVMInstall> it = selection.iterator();

    ArrayList<VMStandin> newEntries = new ArrayList<VMStandin>();
    while (it.hasNext()) {
      IVMInstall selectedVM = it.next();
      // duplicate & add VM
      VMStandin standin = new VMStandin(selectedVM, createUniqueId(selectedVM.getVMInstallType()));
      standin.setName(generateName(selectedVM.getName()));
      EditVMInstallWizard wizard =
          new EditVMInstallWizard(standin, fVMs.toArray(new IVMInstall[fVMs.size()]));
      WizardDialog dialog = new WizardDialog(getShell(), wizard);
      int dialogResult = dialog.open();
      if (dialogResult == Window.OK) {
        VMStandin result = wizard.getResult();
        if (result != null) {
          newEntries.add(result);
        }
      } else if (dialogResult == Window.CANCEL) {
        // Canceling one wizard should cancel all subsequent wizards
        break;
      }
    }
    if (newEntries.size() > 0) {
      fVMs.addAll(newEntries);
      fVMList.refresh();
      fVMList.setSelection(new StructuredSelection(newEntries.toArray()));
    } else {
      fVMList.setSelection(selection);
    }
    fVMList.refresh(true);
  }
 boolean isUnmodifiable(Object element) {
   if (element instanceof IVMInstall) {
     IVMInstall vm = (IVMInstall) element;
     return JavaRuntime.isContributedVMInstall(vm.getId());
   }
   return false;
 }
示例#5
0
 private void addToolsJar(ILaunchConfiguration configuration, List rtes, String path) {
   IRuntimeClasspathEntry tools = getToolsJar(configuration);
   if (tools == null) {
     if (path != null) {
       // use the global entry
       rtes.add(JavaRuntime.newArchiveRuntimeClasspathEntry(new Path(path)));
     } else {
       // use the default vm install to try to find a tools.jar
       IVMInstall install = JavaRuntime.getDefaultVMInstall();
       if (install != null) {
         IAntClasspathEntry entry =
             AntCorePlugin.getPlugin()
                 .getPreferences()
                 .getToolsJarEntry(new Path(install.getInstallLocation().getAbsolutePath()));
         if (entry != null) {
           rtes.add(
               JavaRuntime.newArchiveRuntimeClasspathEntry(
                   new Path(entry.getEntryURL().getPath())));
         }
       }
     }
   } else {
     rtes.add(tools);
   }
 }
 /**
  * Create a new IVMInstall of DefaultVM install type.
  *
  * @return
  */
 public static IVMInstall createVM(File location) {
   @SuppressWarnings("restriction")
   IVMInstallType vmType = JavaRuntime.getVMInstallType(ID_STANDARD_VM_TYPE);
   IVMInstall vm = vmType.createVMInstall(createVMId(vmType));
   vm.setInstallLocation(location);
   return vm;
 }
 public static void javaXXeveryone(String version) throws CoreException {
   // 1: The eclipse workspace default VM should be Java 7
   IVMInstall vm = ensureJavaXXdefaultVM(version);
   // 2: Compiler/source compliance for JDT
   JavaUtils.setJavaXXCompliance(version); // Compiler/source compliance also Java 7
   // 3: Force Gradle JVM default
   GradleCore.getInstance().getPreferences().setJavaHomeJREName(vm.getName());
 }
 /**
  * Sets the workspace default VM on the given working copy
  *
  * @param config
  * @since 3.5
  */
 @SuppressWarnings("deprecation")
 public static void setVM(ILaunchConfigurationWorkingCopy config) {
   IVMInstall vm = JavaRuntime.getDefaultVMInstall();
   String vmName = vm.getName();
   String vmTypeID = vm.getVMInstallType().getId();
   config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_NAME, vmName);
   config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_TYPE, vmTypeID);
 }
示例#9
0
 public static IVMInstall createLauncher(ILaunchConfiguration configuration) throws CoreException {
   IVMInstall launcher = getVMInstall(configuration);
   if (!launcher.getInstallLocation().exists())
     throw new CoreException(
         LauncherUtils.createErrorStatus(
             MDEMessages.WorkbenchLauncherConfigurationDelegate_jrePathNotFound));
   return launcher;
 }
 private String getDefaultJVMName() {
   IVMInstall install = JavaRuntime.getDefaultVMInstall();
   if (install != null) {
     return install.getName();
   } else {
     return Messages.NewBlackBerryProjectWizardPageOne_UnknownDefaultJRE_name;
   }
 }
示例#11
0
 public static boolean isExistingVMName(String name) {
   for (IVMInstall vm :
       JavaRuntime.getVMInstallType(StandardVMType.ID_STANDARD_VM_TYPE).getVMInstalls()) {
     if (vm.getName().equals(name)) {
       return true;
     }
   }
   return false;
 }
 /** @see IAddVMDialogRequestor#isDuplicateName(String) */
 @Override
 public boolean isDuplicateName(String name) {
   for (int i = 0; i < fVMs.size(); i++) {
     IVMInstall vm = fVMs.get(i);
     if (vm.getName().equals(name)) {
       return true;
     }
   }
   return false;
 }
示例#13
0
  /**
   * Get the default VMInstall name using the available info in the config, using the JavaProject if
   * available.
   *
   * @param configuration Launch configuration to check
   * @return name of the VMInstall
   * @throws CoreException thrown if there's a problem getting the VM name
   */
  public static String getDefaultVMInstallName(ILaunchConfiguration configuration)
      throws CoreException {
    IJavaProject javaProject = JavaRuntime.getJavaProject(configuration);
    IVMInstall vmInstall = null;
    if (javaProject != null) {
      vmInstall = JavaRuntime.getVMInstall(javaProject);
    }

    if (vmInstall != null) {
      return vmInstall.getName();
    }

    return VMUtil.getDefaultVMInstallName();
  }
示例#14
0
 /**
  * @param config
  * @return
  * @throws CoreException
  */
 protected String constructProgramString(VMRunnerConfiguration config) throws CoreException {
   File exe = ScriptDebugUtil.findJavaExecutable(fVMInstance.getInstallLocation());
   if (exe == null) {
     throw new Error("not java exe file"); // $NON-NLS-1$
   }
   return exe.getAbsolutePath();
 }
  public static IVMInstall ensureJavaXXdefaultVM(String version) throws CoreException {
    // Before doing anything check the current default VM
    IVMInstall vm = JavaRuntime.getDefaultVMInstall();
    if (JavaUtils.isJavaXX(vm, version)) {
      return vm; // Done!
    }

    vm = getJavaXXVM(version);
    if (vm == null) {
      vm = JavaUtils.createVM(getVMLocation(version));
    }
    if (!JavaUtils.isJavaXX(vm, version)) {
      throw new Error("vm at " + vm.getInstallLocation() + " doesn't look like a Java " + version);
    }
    JavaRuntime.setDefaultVMInstall(vm, new NullProgressMonitor());
    return vm;
  }
  protected List getStartClasspath() {
    List startClasspath = super.getStartClasspath();
    GenericServerRuntime runtime = getRuntimeDelegate();

    IVMInstall vmInstall = runtime.getVMInstall();
    File jdkLib = new File(vmInstall.getInstallLocation(), "lib");

    if (jdkLib.exists() && jdkLib.isDirectory()) {
      for (String cpath : jdkLib.list()) {
        Path newCPath = new Path(new File(jdkLib, cpath).toString());
        String fileExtension = newCPath.getFileExtension();
        if (fileExtension != null && fileExtension.equalsIgnoreCase("jar"))
          startClasspath.add(JavaRuntime.newArchiveRuntimeClasspathEntry(newCPath));
      }
    }
    return startClasspath;
  }
 /** Enables the buttons based on selected items counts in the viewer */
 private void enableButtons() {
   IStructuredSelection selection = (IStructuredSelection) fVMList.getSelection();
   int selectionCount = selection.size();
   fEditButton.setEnabled(selectionCount == 1);
   fCopyButton.setEnabled(selectionCount > 0);
   if (selectionCount > 0 && selectionCount <= fVMList.getTable().getItemCount()) {
     Iterator<IVMInstall> iterator = selection.iterator();
     while (iterator.hasNext()) {
       IVMInstall install = iterator.next();
       if (JavaRuntime.isContributedVMInstall(install.getId())) {
         fRemoveButton.setEnabled(false);
         return;
       }
     }
     fRemoveButton.setEnabled(true);
   } else {
     fRemoveButton.setEnabled(false);
   }
 }
示例#18
0
  /**
   * Returns the tools.jar to use for this launch configuration, or <code>null</code> if none.
   *
   * @param configuration configuration to resolve a tools.jar for
   * @return associated tools.jar archive, or <code>null</code>
   */
  private IRuntimeClasspathEntry getToolsJar(ILaunchConfiguration configuration) {
    try {
      IVMInstall install = JavaRuntime.computeVMInstall(configuration);
      if (install != null) {
        IAntClasspathEntry entry =
            AntCorePlugin.getPlugin()
                .getPreferences()
                .getToolsJarEntry(new Path(install.getInstallLocation().getAbsolutePath()));
        if (entry != null) {
          return JavaRuntime.newArchiveRuntimeClasspathEntry(
              new Path(entry.getEntryURL().getPath()));
        }
      }
    } catch (CoreException ce) {
      // likely dealing with a non-Java project
    }

    return null;
  }
  protected void validateServerStructure(IServer server) throws CoreException {
    IControllableServerBehavior jbsBehavior =
        JBossServerBehaviorUtils.getControllableBehavior(server);

    Trace.trace(Trace.STRING_FINEST, "Verifying server structure"); // $NON-NLS-1$
    JBossExtendedProperties props =
        ExtendedServerPropertiesAdapterFactory.getJBossExtendedProperties(server);
    IStatus status = props.verifyServerStructure();
    if (!status.isOK()) {
      ((ControllableServerBehavior) jbsBehavior).setServerStopped();
      throw new CoreException(status);
    }

    Trace.trace(
        Trace.STRING_FINEST, "Verifying jdk is available if server requires jdk"); // $NON-NLS-1$
    boolean requiresJDK = props.requiresJDK();
    if (requiresJDK) {
      IRuntime rt = server.getRuntime();
      IJBossServerRuntime rt2 = RuntimeUtils.getJBossServerRuntime(rt);
      IVMInstall vm = rt2.getVM();

      if (!JavaUtils.isJDK(vm)) {
        // JBIDE-14568 do not BLOCK launch, but log error
        Trace.trace(
            Trace.STRING_FINEST,
            "The VM to launch server '"
                + //$NON-NLS-1$
                server.getName()
                + "' does not appear to be a JDK: "
                + vm.getInstallLocation().getAbsolutePath()); // $NON-NLS-1$
        IStatus stat =
            new Status(
                IStatus.ERROR,
                JBossServerCorePlugin.PLUGIN_ID,
                NLS.bind(
                    Messages.launch_requiresJDK,
                    server.getName(),
                    vm.getInstallLocation().getAbsolutePath()));
        logStatus(server, stat);
      }
    }
  }
 private StringBuffer appendVMAttributes(IVMInstall vmInstall, StringBuffer buf) {
   if (vmInstall != null) {
     String str = vmInstall.getName();
     buf.append('[').append(str.length()).append(']').append(str);
     str = vmInstall.getVMInstallType().getName();
     buf.append('[').append(str.length()).append(']').append(str);
     if (vmInstall.getVMArguments() != null && vmInstall.getVMArguments().length > 0) {
       buf.append('[').append(vmInstall.getVMArguments().length).append(']');
       for (int i = 0; i < vmInstall.getVMArguments().length; i++) {
         str = vmInstall.getVMArguments()[i];
         buf.append('[').append(str.length()).append(']').append(str);
       }
     }
     str = vmInstall.getInstallLocation().getAbsolutePath();
     buf.append('[').append(str.length()).append(']').append(str).append(';');
   } else {
     buf.append('[').append(']').append(';');
   }
   return buf;
 }
 /** @see ITableLabelProvider#getColumnText(Object, int) */
 @Override
 public String getColumnText(Object element, int columnIndex) {
   if (element instanceof IVMInstall) {
     IVMInstall vm = (IVMInstall) element;
     switch (columnIndex) {
       case 0:
         if (JavaRuntime.isContributedVMInstall(vm.getId())) {
           return NLS.bind(JREMessages.InstalledJREsBlock_19, new String[] {vm.getName()});
         }
         if (fVMList.getChecked(element)) {
           return NLS.bind(JREMessages.InstalledJREsBlock_7, vm.getName());
         }
         return vm.getName();
       case 1:
         return vm.getInstallLocation().getAbsolutePath();
       case 2:
         return vm.getVMInstallType().getName();
     }
   }
   return element.toString();
 }
  /** Search for installed VMs in the file system */
  protected void search() {
    if (Platform.OS_MACOSX.equals(Platform.getOS())) {
      doMacSearch();
      return;
    }
    // choose a root directory for the search
    DirectoryDialog dialog = new DirectoryDialog(getShell());
    dialog.setMessage(JREMessages.InstalledJREsBlock_9);
    dialog.setText(JREMessages.InstalledJREsBlock_10);
    String path = dialog.open();
    if (path == null) {
      return;
    }

    // ignore installed locations
    final Set<File> exstingLocations = new HashSet<File>();
    for (IVMInstall vm : fVMs) {
      exstingLocations.add(vm.getInstallLocation());
    }

    // search
    final File rootDir = new File(path);
    final List<File> locations = new ArrayList<File>();
    final List<IVMInstallType> types = new ArrayList<IVMInstallType>();

    IRunnableWithProgress r =
        new IRunnableWithProgress() {
          @Override
          public void run(IProgressMonitor monitor) {
            monitor.beginTask(JREMessages.InstalledJREsBlock_11, IProgressMonitor.UNKNOWN);
            search(rootDir, locations, types, exstingLocations, monitor);
            monitor.done();
          }
        };

    try {
      ProgressMonitorDialog progress =
          new ProgressMonitorDialog(getShell()) {
            /*
             * Overridden createCancelButton to replace Cancel label with Stop label
             * More accurately reflects action taken when button pressed.
             * Bug [162902]
             */
            @Override
            protected void createCancelButton(Composite parent) {
              cancel =
                  createButton(
                      parent, IDialogConstants.CANCEL_ID, IDialogConstants.STOP_LABEL, true);
              if (arrowCursor == null) {
                arrowCursor = new Cursor(cancel.getDisplay(), SWT.CURSOR_ARROW);
              }
              cancel.setCursor(arrowCursor);
              setOperationCancelButtonEnabled(enableCancelButton);
            }
          };
      progress.run(true, true, r);
    } catch (InvocationTargetException e) {
      JDIDebugUIPlugin.log(e);
    } catch (InterruptedException e) {
      // canceled
      return;
    }

    if (locations.isEmpty()) {
      String messagePath = path.replaceAll("&", "&&"); // @see bug 29855  //$NON-NLS-1$//$NON-NLS-2$
      MessageDialog.openInformation(
          getShell(),
          JREMessages.InstalledJREsBlock_12,
          NLS.bind(JREMessages.InstalledJREsBlock_13, new String[] {messagePath})); //
    } else {
      Iterator<IVMInstallType> iter2 = types.iterator();
      for (File location : locations) {
        IVMInstallType type = iter2.next();
        AbstractVMInstall vm = new VMStandin(type, createUniqueId(type));
        String name = location.getName();
        String nameCopy = new String(name);
        int i = 1;
        while (isDuplicateName(nameCopy)) {
          nameCopy = name + '(' + i++ + ')';
        }
        vm.setName(nameCopy);
        vm.setInstallLocation(location);
        if (type instanceof AbstractVMInstallType) {
          // set default java doc location
          AbstractVMInstallType abs = (AbstractVMInstallType) type;
          vm.setJavadocLocation(abs.getDefaultJavadocLocation(location));
          vm.setVMArgs(abs.getDefaultVMArguments(location));
        }
        vmAdded(vm);
      }
    }
  }
  /* (non-Javadoc)
   * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
   */
  public String getText(Object element) {
    IRuntimeClasspathEntry entry = (IRuntimeClasspathEntry) element;
    switch (entry.getType()) {
      case IRuntimeClasspathEntry.PROJECT:
        IResource res = entry.getResource();
        IJavaElement proj = JavaCore.create(res);
        if (proj == null) {
          return entry.getPath().lastSegment();
        } else {
          return lp.getText(proj);
        }
      case IRuntimeClasspathEntry.ARCHIVE:
        IPath path = entry.getPath();
        if (path == null) {
          return MessageFormat.format("Invalid path: {0}", new Object[] {"null"}); // $NON-NLS-1$
        }
        if (!path.isAbsolute() || !path.isValidPath(path.toString())) {
          return MessageFormat.format("Invalid path: {0}", new Object[] {path.toOSString()});
        }
        String[] segments = path.segments();
        StringBuffer displayPath = new StringBuffer();
        if (segments.length > 0) {
          String device = path.getDevice();
          if (device != null) {
            displayPath.append(device);
            displayPath.append(File.separator);
          }
          for (int i = 0; i < segments.length - 1; i++) {
            displayPath.append(segments[i]).append(File.separator);
          }
          displayPath.append(segments[segments.length - 1]);

          // getDevice means that's a absolute path.
          if (path.getDevice() != null && !path.toFile().exists()) {
            displayPath.append(" (missing) ");
          }
        } else {
          displayPath.append(path.toOSString());
        }
        return displayPath.toString();
      case IRuntimeClasspathEntry.VARIABLE:
        path = entry.getPath();
        IPath srcPath = entry.getSourceAttachmentPath();
        StringBuffer buf = new StringBuffer(path.toString());
        if (srcPath != null) {
          buf.append(" ["); // $NON-NLS-1$
          buf.append(srcPath.toString());
          IPath rootPath = entry.getSourceAttachmentRootPath();
          if (rootPath != null) {
            buf.append(IPath.SEPARATOR);
            buf.append(rootPath.toString());
          }
          buf.append(']');
        }
        // append JRE name if we can compute it
        if (path.equals(new Path(JavaRuntime.JRELIB_VARIABLE)) && fLaunchConfiguration != null) {
          try {
            IVMInstall vm = JavaRuntime.computeVMInstall(fLaunchConfiguration);
            buf.append(" - "); // $NON-NLS-1$
            buf.append(vm.getName());
          } catch (CoreException e) {
          }
        }
        return buf.toString();
      case IRuntimeClasspathEntry.CONTAINER:
        path = entry.getPath();
        if (fLaunchConfiguration != null) {
          try {
            IJavaProject project = null;
            try {
              project = JavaRuntime.getJavaProject(fLaunchConfiguration);
            } catch (CoreException e) {
            }
            if (project == null) {
            } else {
              IClasspathContainer container =
                  JavaCore.getClasspathContainer(entry.getPath(), project);
              if (container != null) {
                if (container.getDescription().startsWith("Persisted container")) {
                  return container.getPath().toString();
                } else {
                  return container.getDescription();
                }
              }
            }
          } catch (CoreException e) {
          }
        }
        return entry.getPath().toString();
      case IRuntimeClasspathEntry.OTHER:
        IRuntimeClasspathEntry delegate = entry;
        if (entry instanceof ClasspathEntry) {
          delegate = ((ClasspathEntry) entry).getDelegate();
        }
        String name = lp.getText(delegate);
        if (name == null || name.length() == 0) {
          return ((IRuntimeClasspathEntry2) delegate).getName();
        }
        return name;
    }
    return ""; //$NON-NLS-1$
  }
  @SuppressWarnings("unchecked")
  public void launch(
      ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {

    try {

      GrailsVersion version = GrailsLaunchArgumentUtils.getGrailsVersion(configuration);
      IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 5);
      checkCancelled(subMonitor);
      subMonitor.beginTask("Starting Grails", 5);
      subMonitor.worked(1);
      checkCancelled(subMonitor);
      subMonitor.subTask("Configuring launch parameters...");

      // FIXKDV FIXADE Copies of this code exist in
      // GrailsLaunchArgumentUtils.prepareClasspath()
      // and GrailsLaunchConfigurationDelegate.launch()
      // consider refactoring to combine

      IVMRunner runner;
      IVMInstall vm = verifyVMInstall(configuration);
      if (GrailsVersion.V_2_3_.compareTo(version) <= 0) {
        // We'll be debugging the forked process, not the run-app command.
        runner = vm.getVMRunner(ILaunchManager.RUN_MODE);
      } else {
        runner = vm.getVMRunner(mode);
      }
      if (runner == null) {
        runner = vm.getVMRunner(ILaunchManager.RUN_MODE);
      }

      String projectName =
          configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "");
      IProject project = null;
      if (!"".equals(projectName)) {
        project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
      }

      String grailsHome = GrailsLaunchArgumentUtils.getGrailsHome(configuration);
      String baseDir =
          configuration.getAttribute(GrailsLaunchArgumentUtils.PROJECT_DIR_LAUNCH_ATTR, "");
      if (baseDir.equals("")) {
        baseDir = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString();
      }
      String script = getScript(configuration);

      File workingDir = verifyWorkingDirectory(configuration);
      String workingDirName = null;
      if (workingDir != null) {
        workingDirName = workingDir.getAbsolutePath();
      } else {
        workingDirName = baseDir;
      }

      List<String> programArguments = new ArrayList<String>();
      programArguments.add("--conf");
      programArguments.add(grailsHome + "conf" + File.separatorChar + "groovy-starter.conf");
      programArguments.add("--main");
      programArguments.add("org.codehaus.groovy.grails.cli.GrailsScriptRunner");

      StringBuilder grailsCommand = new StringBuilder();
      String grailsWorkDir =
          configuration.getAttribute(GrailsLaunchArgumentUtils.GRAILS_WORK_DIR_LAUNCH_ATTR, "");
      if (!grailsWorkDir.equals("")) {
        grailsCommand.append("-Dgrails.work.dir=" + grailsWorkDir + " ");
      }
      grailsCommand.append(script + " ");
      programArguments.add(grailsCommand.toString().trim());

      List<String> vmArgs = new ArrayList<String>();
      // vmArgs.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8123");

      // add manual configured vm options to the argument list
      String existingVmArgs = getVMArguments(configuration);
      boolean launchConfHasVMArgs = false;
      if (existingVmArgs != null && existingVmArgs.length() > 0) {
        launchConfHasVMArgs = true;
        StringTokenizer additionalArguments = new StringTokenizer(existingVmArgs, " ");
        while (additionalArguments.hasMoreTokens()) {
          vmArgs.add(additionalArguments.nextToken());
        }
      }

      Map<String, String> systemProps =
          GrailsCoreActivator.getDefault().getLaunchSystemProperties();
      GrailsLaunchArgumentUtils.setMaybe(systemProps, "base.dir", baseDir);
      GrailsLaunchArgumentUtils.setMaybe(systemProps, "grails.home", grailsHome);
      for (Map.Entry<String, String> prop : systemProps.entrySet()) {
        vmArgs.add("-D" + prop.getKey() + "=" + prop.getValue());
      }
      int forkedProcessDebugPort = addForkedModeDebuggingArgs(configuration, mode, vmArgs);
      ArrayList<Integer> killPorts = addKillPortArg(project, vmArgs);

      if (!launchConfHasVMArgs) {
        // If the user added their own vmargs to the launch config then the 'default' from global
        // prefs should
        // not be used.
        GrailsLaunchArgumentUtils.addUserDefinedJVMArgs(vmArgs);
      }
      // Grails uses some default memory settings that we want to use as well if no others have been
      // configured
      vmArgs = GrailsLaunchArgumentUtils.addMemorySettings(vmArgs);
      vmArgs = GrailsLaunchArgumentUtils.addSpringLoadedArgs(configuration, vmArgs);

      String[] envp = getEnvironment(configuration);
      Map<String, String> extra = new HashMap<String, String>();
      extra.put("JAVA_HOME", vm.getInstallLocation().getAbsolutePath());
      extra.put(
          "GROOVY_PAGE_ADD_LINE_NUMBERS", "true"); // Enables line number info for GSP debugging
      envp = GrailsLaunchArgumentUtils.addToEnvMaybe(envp, extra);

      Map<String, Object> vmAttributesMap = getVMSpecificAttributesMap(configuration);

      String[] classpath = getClasspath(configuration);
      String mainTypeName = verifyMainTypeName(configuration);

      VMRunnerConfiguration runConfiguration = new VMRunnerConfiguration(mainTypeName, classpath);
      runConfiguration.setProgramArguments(
          programArguments.toArray(new String[programArguments.size()]));
      runConfiguration.setVMArguments(vmArgs.toArray(new String[vmArgs.size()]));
      runConfiguration.setWorkingDirectory(workingDirName);
      runConfiguration.setEnvironment(envp);
      runConfiguration.setVMSpecificAttributesMap(vmAttributesMap);

      String[] bootpath = getBootpath(configuration);
      if (bootpath != null && bootpath.length > 0) {
        runConfiguration.setBootClassPath(bootpath);
      }

      subMonitor.worked(1);
      checkCancelled(subMonitor);

      subMonitor.subTask("Setting up source locator...");
      setDefaultSourceLocator(launch, configuration);
      subMonitor.worked(1);
      checkCancelled(subMonitor);

      subMonitor.worked(1);
      checkCancelled(subMonitor);

      subMonitor.subTask("Launching Grails...");

      if (ILaunchManager.DEBUG_MODE.equals(mode)) {
        launchRemote(forkedProcessDebugPort, configuration, mode, launch, subMonitor);
      }
      GrailsCoreActivator.getDefault().notifyCommandStart(project);
      runner.run(runConfiguration, launch, monitor);
      AbstractLaunchProcessListener listener = getLaunchListener(configuration);
      if (listener != null) {
        listener.init(launch.getProcesses()[0]);
      }
      DebugPlugin.getDefault()
          .addDebugEventListener(
              new GrailsProcessListener(launch.getProcesses(), project, killPorts));
      subMonitor.worked(1);
    } catch (Exception e) {
      GrailsCoreActivator.log(e);
    }
  }
  public void launch(
      ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {
    IServer server = ServerUtil.getServer(configuration);
    if (server == null) {
      Trace.trace(Trace.FINEST, "Launch configuration could not find server");
      // throw CoreException();
      return;
    }

    if (server.shouldPublish() && ServerCore.isAutoPublishing())
      server.publish(IServer.PUBLISH_INCREMENTAL, monitor);

    PreviewServerBehaviour previewServer =
        (PreviewServerBehaviour) server.loadAdapter(PreviewServerBehaviour.class, null);

    int size = REQUIRED_BUNDLE_IDS.length;
    String[] jars = new String[size];
    for (int i = 0; i < size; i++) {
      Bundle b = Platform.getBundle(REQUIRED_BUNDLE_IDS[i]);
      IPath path = null;
      if (b != null) path = PreviewRuntime.getJarredPluginPath(b);
      if (path == null)
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                PreviewPlugin.PLUGIN_ID,
                "Could not find required bundle " + REQUIRED_BUNDLE_IDS[i]));
      jars[i] = path.toOSString();
    }

    // Appending the bin onto the classpath is to support running from the workbench
    // when org.eclipse.wst.server.preview is checked out
    Trace.trace(Trace.FINEST, jars[CLASSPATH_BIN_INDEX_PREVIEW_SERVER] + File.separator + "bin");
    if (new File(jars[CLASSPATH_BIN_INDEX_PREVIEW_SERVER] + File.separator + "bin").exists())
      jars[CLASSPATH_BIN_INDEX_PREVIEW_SERVER] =
          jars[CLASSPATH_BIN_INDEX_PREVIEW_SERVER] + File.separator + "bin";

    IVMInstall vm = verifyVMInstall(configuration);

    IVMRunner runner = vm.getVMRunner(mode);
    if (runner == null) runner = vm.getVMRunner(ILaunchManager.RUN_MODE);

    File workingDir = verifyWorkingDirectory(configuration);
    String workingDirName = null;
    if (workingDir != null) workingDirName = workingDir.getAbsolutePath();

    // Program & VM args
    String pgmArgs =
        "\"" + previewServer.getTempDirectory().append("preview.xml").toOSString() + "\"";
    // getProgramArguments(configuration);
    String vmArgs = getVMArguments(configuration);
    String[] envp = getEnvironment(configuration);

    ExecutionArguments execArgs = new ExecutionArguments(vmArgs, pgmArgs);

    // VM-specific attributes
    Map vmAttributesMap = getVMSpecificAttributesMap(configuration);

    // Classpath
    String[] classpath2 = getClasspath(configuration);
    String[] classpath = new String[classpath2.length + REQUIRED_BUNDLE_IDS.length];
    System.arraycopy(jars, 0, classpath, 0, REQUIRED_BUNDLE_IDS.length);
    System.arraycopy(classpath2, 0, classpath, REQUIRED_BUNDLE_IDS.length, classpath2.length);

    // Create VM config
    VMRunnerConfiguration runConfig = new VMRunnerConfiguration(MAIN_CLASS, classpath);
    runConfig.setProgramArguments(execArgs.getProgramArgumentsArray());
    runConfig.setVMArguments(execArgs.getVMArgumentsArray());
    runConfig.setWorkingDirectory(workingDirName);
    runConfig.setEnvironment(envp);
    runConfig.setVMSpecificAttributesMap(vmAttributesMap);

    // Bootpath
    String[] bootpath = getBootpath(configuration);
    if (bootpath != null && bootpath.length > 0) runConfig.setBootClassPath(bootpath);

    setDefaultSourceLocator(launch, configuration);

    // Launch the configuration
    previewServer.setupLaunch(launch, mode, monitor);

    if (ILaunchManager.PROFILE_MODE.equals(mode))
      ServerProfilerDelegate.configureProfiling(launch, vm, runConfig, monitor);

    try {
      runner.run(runConfig, launch, monitor);
      previewServer.addProcessListener(launch.getProcesses()[0]);
    } catch (Exception e) {
      // ignore - process failed
    }
  }
 private String getDefaultBBJRE() {
   IVMInstall vm = VMUtils.getDefaultBBVM();
   return vm != null ? vm.getName() : "";
 }