Example #1
0
 @Override
 public void launch(
     final ILaunchConfiguration configuration,
     String mode,
     ILaunch launch,
     IProgressMonitor monitor)
     throws CoreException {
   final RunletEvaluator main =
       new RunletEvaluator(
           configuration.getAttribute(RunletMainTab.PROJECT_ATTRIBUTE, RunletMainTab.NGPM_STDLIB));
   if (mode.equals("debug")) {
     RunletDebugTarget debugTarget =
         new RunletDebugTarget(main, launch, configuration.getName(), new RunletObjectFormatter());
     launch.addDebugTarget(debugTarget);
     launch.addProcess(debugTarget.getProcess());
     // TODO for testing, request to suspend immediately
     debugTarget.suspend();
     // debugSession.suspend(main.getInterpreter());
   }
   new Thread(mode + " Runlet " + configuration.getName()) {
     public void run() {
       try {
         RunletObject<AssociationEnd, TypeDefinition, ClassTypeDefinition>[] result =
             main.evaluate(
                 configuration.getAttribute(
                     RunletMainTab.EXPRESSION_ATTRIBUTE, "")); // $NON-NLS-1$
         main.getInterpreter().terminate();
         log.info(Messages.LaunchConfig_1 + Arrays.asList(result));
       } catch (Exception e) {
         log.throwing(getClass().getName(), "launch", e); // $NON-NLS-1$
       }
     }
   }.start();
 }
  public boolean preLaunchCheck(
      ILaunchConfiguration configuration, String mode, IProgressMonitor monitor)
      throws CoreException {
    ExporterAttributes attributes = new ExporterAttributes(configuration);

    String configName = attributes.getConsoleConfigurationName();
    if (StringHelper.isEmpty(configName)) {
      abort(
          HibernateConsoleMessages
                  .CodeGenerationLaunchDelegate_console_configuration_name_is_empty_in
              + configuration.getName(),
          null,
          ICodeGenerationLaunchConstants.ERR_UNSPECIFIED_CONSOLE_CONFIGURATION);
    }

    if (KnownConfigurations.getInstance().find(configName) == null) {
      String out =
          NLS.bind(
              HibernateConsoleMessages
                  .CodeGenerationLaunchDelegate_console_configuration_not_found_in,
              configName,
              configuration.getName());
      abort(out, null, ICodeGenerationLaunchConstants.ERR_CONSOLE_CONFIGURATION_NOTFOUND);
    }

    if (StringHelper.isEmpty(attributes.getOutputPath())) {
      abort(
          HibernateConsoleMessages.CodeGenerationLaunchDelegate_output_has_to_be_specified_in
              + configuration.getName(),
          null,
          ICodeGenerationLaunchConstants.ERR_OUTPUT_PATH_NOTFOUND);
    }

    List<ExporterFactory> exporterFactories = attributes.getExporterFactories();
    for (Iterator<ExporterFactory> iter = exporterFactories.iterator(); iter.hasNext(); ) {
      ExporterFactory exFactory = iter.next();
      if (exFactory.isEnabled(configuration)
          && exFactory
              .getExporterDefinitionId()
              .equals("org.hibernate.tools.query")) { // $NON-NLS-1$
        if (!exFactory.getProperties().containsKey("query_string")) { // $NON-NLS-1$
          abort(
              "Query property should be explicitly set for Query Exporter",
              null,
              ICodeGenerationLaunchConstants.ERR_OUTPUT_PATH_NOTFOUND); // $NON-NLS-1$
        }
      }
    }

    return super.preLaunchCheck(configuration, mode, monitor);
  }
Example #3
0
  /**
   * Initialize a <code>ILaunchConfigurationWorkingCopy</code> either by using an existing one (if
   * found), or using a default configuration (for example, the one used for the most recent
   * launch), or by creating a new one based on the <code>project</code> name and the <code>confName
   * </code>.
   *
   * @throws CoreException if getting an working copy from an existing configuration fails
   */
  private static ILaunchConfigurationWorkingCopy createLaunchConfiguration(
      IProject project, String confName, RunInfo runInfo) {
    ILaunchManager launchManager = getLaunchManager();
    ILaunchConfiguration config =
        ConfigurationHelper.findConfiguration(launchManager, project, confName, runInfo);

    ILaunchConfigurationWorkingCopy configWC = null;
    if (null != config) {
      try {
        configWC = config.getWorkingCopy();
      } catch (CoreException cex) {
        TestNGPlugin.log(
            new Status(
                IStatus.ERROR,
                TestNGPlugin.PLUGIN_ID,
                TestNGPluginConstants.LAUNCH_ERROR,
                "Cannot create working copy of existing launcher " + config.getName(),
                cex));
      }
    }
    if (null == configWC) {
      if (confName == null && runInfo != null) {
        confName = runInfo.getClassName() + "." + runInfo.getMethodName();
      }
      configWC = ConfigurationHelper.createBasicConfiguration(launchManager, project, confName);
    }

    return configWC;
  }
  public static List<LaunchConfigData> getProjectLaunchConfigs(final IProject project) {
    List<LaunchConfigData> matches = new LinkedList<>();

    try {
      ILaunchConfiguration[] configs =
          DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations();

      for (ILaunchConfiguration launchConfig : configs) {
        String launchConfigProjectName =
            launchConfig.getAttribute(IDebugConstants.VDM_LAUNCH_CONFIG_PROJECT, "");

        if (launchConfigProjectName != null
            && !launchConfigProjectName.equals("")
            && launchConfigProjectName.equals(project.getName())) {
          String exp = launchConfig.getAttribute(IDebugConstants.VDM_LAUNCH_CONFIG_EXPRESSION, "");
          matches.add(new LaunchConfigData(launchConfig.getName(), exp));
        }
      }
    } catch (CoreException e) {

      CodeGenConsole.GetInstance()
          .printErrorln(
              "Problem looking up launch configurations for project "
                  + project.getName()
                  + ": "
                  + e.getMessage());
      e.printStackTrace();
    }

    return matches;
  }
  protected String computeName() {
    String label = fLabel;

    ILaunchConfiguration config = fLaunch.getLaunchConfiguration();
    if (config != null && !DebugUITools.isPrivate(config)) {
      String type = null;
      try {
        type = config.getType().getName();
      } catch (CoreException e) {
      }
      StringBuilder buffer = new StringBuilder();
      buffer.append(config.getName());
      if (type != null) {
        buffer.append(" ["); // $NON-NLS-1$
        buffer.append(type);
        buffer.append("] "); // $NON-NLS-1$
      }
      buffer.append(label);
      label = buffer.toString();
    }

    if (fLaunch.isTerminated()) {
      return ConsoleMessages.ConsoleMessages_console_terminated + label;
    }

    return label;
  }
  /** Verify that the launch configuration name is valid. */
  private void verifyName() throws CoreException {
    if (configNameText.isVisible()) {
      ILaunchManager mgr = getLaunchManager();
      String currentName = configNameText.getText().trim();

      // If there is no name, complain
      if (currentName.length() < 1) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                DartDebugUIPlugin.PLUGIN_ID,
                0,
                Messages.ManageLaunchesDialog_Name_required_for_launch_configuration,
                null));
      }
      try {
        mgr.isValidLaunchConfigurationName(currentName);
      } catch (IllegalArgumentException iae) {
        throw new CoreException(
            new Status(IStatus.ERROR, DartDebugUIPlugin.PLUGIN_ID, 0, iae.getMessage(), null));
      }
      // Otherwise, if there's already a config with the same name, complain
      if (!launchConfig.getName().equals(currentName)) {
        if (mgr.isExistingLaunchConfigurationName(currentName)) {
          throw new CoreException(
              new Status(
                  IStatus.ERROR,
                  DartDebugUIPlugin.PLUGIN_ID,
                  0,
                  Messages.ManageLaunchesDialog_Launch_configuration_already_exists_with_this_name,
                  null));
        }
      }
    }
  }
  private void launchConfiguration() {
    try {
      ILaunch launch = launchConfig.launch(mode, null);
      if (launch.canTerminate()) {
        while (!launch.isTerminated()) {
          Thread.sleep(100);
        }
      }
    } catch (CoreException e) {
      BPCLIPreferences.logError("Error encountered during launch of " + launchConfig.getName(), e);
    } catch (InterruptedException e) {
      BPCLIPreferences.logError("Could not sleep execution thread", e);
    } finally {
      System.out.println("Execution complete.  Exiting.");
      // Unless running in debug exit after the build
      if (!debug) {
        PlatformUI.getWorkbench()
            .getDisplay()
            .asyncExec(
                new Runnable() {

                  @Override
                  public void run() {
                    PlatformUI.getWorkbench().close();
                  }
                });
      }
    }
  }
  @Override
  protected void createContributionItems(final List<IContributionItem> items) {
    final IWorkbenchWindow window = this.util.getWindow();
    final IFile file = this.util.getFile(window);
    final DocProcessingManager manager =
        this.util.getManager(this.util.getContentType(window, file));
    if (manager == null) {
      return;
    }

    final ImList<ILaunchConfiguration> configs = manager.getAvailableConfigs();
    final Data data = new Data(manager, file);

    int i = 0;
    for (int num = 1; i < configs.size(); i++, num++) {
      final ILaunchConfiguration configuration = configs.get(i);

      final ImageDescriptor icon = manager.getImageDescriptor(configuration);
      String mnemonic = null;
      final StringBuilder label = getStringBuilder();
      if (num > 0 && num <= 10) {
        mnemonic = Integer.toString((num % 10));
        label.append(mnemonic);
        label.append(' ');
      }
      label.append(MessageUtil.escapeForMenu(configuration.getName()));

      final ConfigContribution item =
          createConfigContribution(icon, label, mnemonic, configuration);
      item.data = data;

      items.add(item);
    }
  }
 /**
  * Tests the {@link
  * BuilderCoreUtils#migrateBuilderConfiguration(org.eclipse.core.resources.IProject,
  * org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)} method
  *
  * @throws Exception
  */
 public void testMigrateBuilderConfiguration2() throws Exception {
   ILaunchConfigurationWorkingCopy copy =
       createExternalToolBuilderWorkingCopy(
           getProject(), "testMigra/teBuilderConfi/guration2", null); // $NON-NLS-1$
   ILaunchConfiguration config = BuilderCoreUtils.migrateBuilderConfiguration(getProject(), copy);
   assertNotNull("The un-saved working copy should have been migrated", config); // $NON-NLS-1$
   assertTrue(
       "The name of the migrated configuration should be testMigra.teBuilderConfi.guration2",
       config.getName().equals("testMigra.teBuilderConfi.guration2")); // $NON-NLS-1$ //$NON-NLS-2$
 }
  @Override
  public void launch(
      ILaunchConfiguration config, String mode, ILaunch session, IProgressMonitor monitor)
      throws CoreException {
    List<String> selectedConfiguartionNames =
        config.getAttribute(
            CompositeLauncherTab.SELECTED_CONFIGURATIONS_NAMES_KEY, Collections.emptyList());

    for (ILaunchConfiguration lc :
        DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations())
      launch(lc, mode, monitor, selectedConfiguartionNames.contains(lc.getName()));
  }
  @Override
  public void launchConfigurationAdded(ILaunchConfiguration configuration) {
    ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();

    if (selectedConfig != null && selectedConfig.equals(manager.getMovedFrom(configuration))) {
      // this config was re-named, update the dialog with the new config
      selectedConfig = configuration;
      selectLaunchConfiguration(selectedConfig.getName());
    }

    refreshLaunchesViewer();
  }
  private ILaunchConfiguration getConfigurationNamed(String name) {
    try {
      for (ILaunchConfiguration config :
          DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations()) {
        if (name.equals(config.getName())) {
          return config;
        }
      }
    } catch (CoreException exception) {
      DartUtil.logError(exception);
    }

    return null;
  }
 private static ILaunch findRunning(ILaunch launch) {
   ILaunchConfiguration config = launch.getLaunchConfiguration();
   ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
   ILaunch[] runningLaunches = launchManager.getLaunches();
   ILaunch result = null;
   for (ILaunch runningLaunch : runningLaunches) {
     if (runningLaunch != launch
         && config.getName().equals(getLaunchName(runningLaunch))
         && !runningLaunch.isTerminated()) {
       result = runningLaunch;
     }
   }
   return result;
 }
 @Override
 public void initializeFrom(ILaunchConfiguration configuration) {
   ILaunchManager launchManager = getLaunchManager();
   ILaunchConfiguration[] launchConfigurations;
   try {
     launchConfigurations = launchManager.getLaunchConfigurations();
   } catch (CoreException e) {
     // todo: may be this is the case to throw exception?
     setErrorMessage(e.getMessage());
     return;
   }
   List selectedList = Collections.emptyList();
   try {
     selectedList =
         configuration.getAttribute(SELECTED_CONFIGURATION_LIST, Collections.emptyList());
   } catch (CoreException e) {
     setErrorMessage(e.getMessage());
   }
   availableConfigsCombo.removeAll();
   allConfigNames = new HashSet<String>();
   for (ILaunchConfiguration conf : launchConfigurations) {
     String configurationName = conf.getName();
     if (!configurationName.equals(configuration.getName())
         && !selectedList.contains(configurationName)) {
       availableConfigsCombo.add(configurationName);
     }
     allConfigNames.add(configurationName);
   }
   selectedConfigsList.removeAll();
   for (Object item : selectedList) {
     selectedConfigsList.add((String) item);
     if (!allConfigNames.contains((String) item)) {
       setErrorMessage("Configuration [" + item + "] is undefined");
     }
   }
   updateButtonsState();
 }
 /**
  * Returns the path in which data will be stored for this trace.
  *
  * @return the path in which data will be stored for this trace.
  */
 public IPath getStoragePath() throws CoreException {
   if (this.storagePath != null) {
     return storagePath;
   }
   IPath pluginState = SketchPlugin.getDefault().getStateLocation();
   String configurationName = configuration.getName();
   IPath configurationPath = pluginState.append(configurationName);
   IPath filePath = configurationPath.append(getID());
   File file = new File(filePath.toOSString());
   if (!file.exists()) {
     file.mkdirs();
   }
   storagePath = filePath;
   return storagePath;
 }
  private void abortContinueDialog(final IDebugTarget target) {
    // do not report errors for snippet editor targets
    // that do not support HCR. HCR is simulated by using
    // a new class loader for each evaluation
    // final ILaunch launch = target.getLaunch();
    // if (launch.getAttribute(ScrapbookLauncher.SCRAPBOOK_LAUNCH) != null)
    // {
    // if (!target.supportsHotCodeReplace()) {
    // return;
    // }
    // }
    final Display display = ErlideUIPlugin.getStandardDisplay();
    if (display.isDisposed()) {
      return;
    }

    String name = null;
    try {
      name = target.getName();
    } catch (final DebugException e) {
      name = ""; // never happens, ErlangDebugTarget doesn't throw this...
    }
    final String vmName = name;
    final ILaunchConfiguration config = target.getLaunch().getLaunchConfiguration();
    final String launchName = config != null ? config.getName() : "<unknown>";
    final IStatus status =
        new Status(IStatus.ERROR, ErlangCore.PLUGIN_ID, IStatus.ERROR, "Can't replace code", null);
    final String title = "Code Replace Failed";
    final String message =
        MessageFormat.format(
            "Some code changes cannot be replaced when being debugged.",
            new Object[] {vmName, launchName});
    display.asyncExec(
        new Runnable() {
          @Override
          public void run() {
            if (display.isDisposed()) {
              return;
            }
            final Shell shell = ErlideUIPlugin.getActiveWorkbenchShell();
            final HotCodeReplaceErrorDialog dialog =
                new HotCodeReplaceErrorDialog(shell, title, message, status, target);
            dialog.setBlockOnOpen(false);
            dialog.open();
          }
        });
  }
 /* (non-Javadoc)
  * @see ca.uvic.chisel.javasketch.launching.ITraceClient#attach(org.eclipse.debug.core.ILaunch, org.eclipse.debug.core.ILaunchConfiguration, org.eclipse.core.runtime.IProgressMonitor)
  */
 @Override
 public final void attach(
     ILaunch launch, ILaunchConfiguration configuration, IProgressMonitor monitor)
     throws CoreException {
   this.launch = launch;
   this.configuration = configuration;
   this.attachTime = System.currentTimeMillis();
   this.label = configuration.getName();
   try {
     createProperties();
   } catch (IOException e) {
     throw new CoreException(
         new Status(IStatus.ERROR, SketchPlugin.PLUGIN_ID, "Unable to attach client ", e));
   }
   doAttach(launch, configuration, monitor);
   DebugPlugin.getDefault()
       .fireDebugEventSet(new DebugEvent[] {new DebugEvent(this, DebugEvent.CREATE)});
   launch.addProcess(this);
 }
 private ILaunchConfiguration getLaunchConfiguration(
     final Collection<IErlProject> projects, final String mode) throws CoreException {
   final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
   final List<String> projectNames = getProjectNames(projects);
   String name = ListsUtils.packList(projectNames, "_");
   if (name.length() > 15) {
     name = ListsUtils.packList(StringUtils.removeCommonPrefixes(projectNames), "_");
   }
   // try and find one
   final ILaunchConfiguration[] launchConfigurations = launchManager.getLaunchConfigurations();
   for (final ILaunchConfiguration launchConfiguration : launchConfigurations) {
     if (launchConfiguration.getName().equals(name)) {
       if (mode.equals(ILaunchManager.DEBUG_MODE)) {
         return addInterpretedModules(projects, launchConfiguration);
       }
       return launchConfiguration;
     }
   }
   // try and make one
   final ILaunchConfigurationType launchConfigurationType =
       launchManager.getLaunchConfigurationType(ErlangLaunchDelegate.CONFIGURATION_TYPE);
   ILaunchConfigurationWorkingCopy wc = null;
   wc = launchConfigurationType.newInstance(null, name);
   wc.setAttribute(
       ErlLaunchAttributes.PROJECTS, ListsUtils.packList(projectNames, PROJECT_NAME_SEPARATOR));
   wc.setAttribute(
       ErlLaunchAttributes.RUNTIME_NAME, projects.iterator().next().getRuntimeInfo().getName());
   wc.setAttribute(ErlLaunchAttributes.NODE_NAME, name);
   wc.setAttribute(ErlLaunchAttributes.CONSOLE, true);
   wc.setAttribute(ErlLaunchAttributes.INTERNAL, false);
   wc.setAttribute(ErlLaunchAttributes.LOAD_ALL_NODES, false);
   wc.setAttribute(ErlLaunchAttributes.COOKIE, "erlide");
   wc.setAttribute("org.eclipse.debug.core.environmentVariables", Maps.newHashMap());
   if (mode.equals("debug")) {
     final List<String> moduleNames = getProjectAndModuleNames(projects);
     wc.setAttribute(ErlLaunchAttributes.DEBUG_INTERPRET_MODULES, moduleNames);
   }
   wc.setMappedResources(getProjectResources(projects));
   return wc.doSave();
 }
  /**
   * Computes and returns the current name of this console.
   *
   * @return a name for this console
   */
  protected String computeName() {
    String label = null;
    final IProcess process = getProcess();
    final ILaunchConfiguration config = process.getLaunch().getLaunchConfiguration();

    label = process.getAttribute(IProcess.ATTR_PROCESS_LABEL);
    if (label == null) {
      if (config == null) {
        label = process.getLabel();
      } else {
        // check if PRIVATE config
        if (DebugUITools.isPrivate(config)) {
          label = process.getLabel();
        } else {
          String type = null;
          try {
            type = config.getType().getName();
          } catch (final CoreException e) {
          }
          final StringBuffer buffer = new StringBuffer();
          buffer.append("Remote shell connection to: ");
          buffer.append(config.getName());
          if (type != null) {
            buffer.append(" ["); // $NON-NLS-1$
            buffer.append(type);
            buffer.append("] "); // $NON-NLS-1$
          }
          buffer.append(process.getLabel());
          label = buffer.toString();
        }
      }
    }

    if (process.isTerminated()) {
      return MessageFormat.format("<disconnected> {0}", (Object[]) new String[] {label});
    }
    return label;
  }
  /**
   * @see
   *     org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration,
   *     java.lang.String, org.eclipse.debug.core.ILaunch,
   *     org.eclipse.core.runtime.IProgressMonitor)
   */
  @Override
  public void launch(
      ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {
    SubMonitor submonitor = SubMonitor.convert(monitor, 13);
    try {
      // wait RSE is initialized
      // TODO not sure this is the good way to wait for init everywhere in the code
      RSEUtil.waitForRSEInitialization();

      // get configuration information
      String projectName =
          configuration.getAttribute(LuaRemoteDebugConstant.PROJECT_NAME, ""); // $NON-NLS-1$
      String scriptName =
          configuration.getAttribute(LuaRemoteDebugConstant.SCRIPT_NAME, ""); // $NON-NLS-1$
      IHost host = LuaRemoteLaunchConfigurationUtil.getHost(configuration);
      @SuppressWarnings("rawtypes")
      Map env =
          configuration.getAttribute(
              ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, Collections.EMPTY_MAP);

      // valid configuration information
      String errorMessage =
          LuaRemoteLaunchConfigurationUtil.validateRemoteLaunchConfiguration(
              projectName, scriptName, host);
      if (errorMessage != null)
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, errorMessage));
      submonitor.worked(1);

      // get Project
      IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);

      // get the first found remote file SubSystem
      IRemoteFileSubSystem remoteFileSubSystem = RSEUtil.getRemoteFileSubsystem(host);

      // get the first found Lua SubSystem
      LuaSubSystem luaSubSystem = LuaRSEUtil.getLuaSubSystem(host);

      // try to connect to the target
      try {
        if (submonitor.isCanceled()) return;
        remoteFileSubSystem.connect(submonitor.newChild(1), false);
        // CHECKSTYLE:OFF
      } catch (Exception e) {
        // CHECKSTYLE:ON
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                Activator.PLUGIN_ID,
                Messages.LuaRemoteLaunchConfigurationDelegate_error_connectionfailed,
                e));
      }

      // create script project
      IScriptProject scriptProject = DLTKCore.create(project);

      // compute the remote project workingdir
      if (submonitor.isCanceled()) return;
      String outputDirectory = luaSubSystem.getOutputDirectory();
      String defaultRemoteApplicationFolderPath =
          outputDirectory + remoteFileSubSystem.getSeparator() + configuration.getName();
      String remoteApplicationFolderPath =
          configuration.getAttribute(
              LuaRemoteDebugConstant.OUTPUT_DIRECTORY, defaultRemoteApplicationFolderPath);

      // compute script file source path relative path
      String scriptProjectRelativePath =
          configuration.getAttribute(
              LuaRemoteDebugConstant.SCRIPT_NAME, LuaConstants.DEFAULT_MAIN_FILE);
      IFile scriptFile = project.getFile(scriptProjectRelativePath);
      IModuleSource moduleSource =
          LuaUtils.getModuleSourceFromAbsoluteURI(scriptFile.getLocationURI(), scriptProject);
      if (moduleSource == null)
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                Activator.PLUGIN_ID,
                NLS.bind(
                    Messages
                        .LuaRemoteLaunchConfigurationDelegate_error_unabletofindsourcerelativepath,
                    scriptProjectRelativePath)));
      IPath scriptSourcePathRelativePath = LuaUtils.getSourcePathRelativePath(moduleSource);

      // kill Process if already running
      // could happen if connection is closed and last process launch is not terminate
      Session session = RSEUtil.getCurrentSshSession(host.getConnectorServices());
      SshProcess.killProcess(session, remoteApplicationFolderPath);

      // check an prepare remote folder
      try {
        if (submonitor.isCanceled()) return;
        IRemoteFile remoteApplicationPath =
            remoteFileSubSystem.getRemoteFileObject(outputDirectory, submonitor.newChild(1));
        if (remoteApplicationPath.exists()) {
          if (remoteApplicationPath.isFile()) {
            throw new CoreException(
                new Status(
                    IStatus.ERROR,
                    Activator.PLUGIN_ID,
                    NLS.bind(
                        Messages.LuaRemoteLaunchConfigurationDelegate_error_filealreadyexist,
                        outputDirectory)));
          }
        } else {
          remoteFileSubSystem.createFolder(remoteApplicationPath, submonitor.newChild(1));
        }
        submonitor.setWorkRemaining(9);

        // remoteFile is a folder
        // create(or delete and recreate) the working directory
        if (submonitor.isCanceled()) return;
        IRemoteFile remoteWorkingFolder =
            remoteFileSubSystem.getRemoteFileObject(
                remoteApplicationFolderPath, submonitor.newChild(1));
        if (remoteWorkingFolder.exists()) {
          if (remoteWorkingFolder.isFile()) {
            throw new CoreException(
                new Status(
                    IStatus.ERROR,
                    Activator.PLUGIN_ID,
                    MessageFormat.format(
                        Messages.LuaRemoteLaunchConfigurationDelegate_error_filealreadyexist,
                        remoteApplicationFolderPath)));
          } else {
            remoteFileSubSystem.delete(remoteWorkingFolder, submonitor.newChild(1));
          }
        }
        submonitor.setWorkRemaining(7);

        // create project application
        if (submonitor.isCanceled()) return;
        remoteFileSubSystem.createFolder(remoteWorkingFolder, submonitor.newChild(1));

        // upload sourcecode
        LuaRSEUtil.uploadFiles(
            remoteFileSubSystem,
            scriptProject,
            remoteApplicationFolderPath,
            submonitor.newChild(2));

        // upload Debug module
        if (mode.equals(ILaunchManager.DEBUG_MODE)) {
          SubMonitor debugmonitor = submonitor.newChild(1);
          debugmonitor.setWorkRemaining(DEBUG_FILES.length);

          String localEncoding = Charset.defaultCharset().name();
          String remoteEncoding = remoteFileSubSystem.getRemoteEncoding();

          for (String luaFile : DEBUG_FILES) {
            try {
              Bundle bundle =
                  Platform.getBundle(
                      org.eclipse.koneki.ldt.debug.core.internal.Activator.PLUGIN_ID);
              URL resource = bundle.getResource(luaFile);
              File result = new File(FileLocator.toFileURL(resource).getPath());
              String remotePath =
                  remoteApplicationFolderPath
                      + remoteFileSubSystem.getSeparator()
                      + result.getName();
              remoteFileSubSystem.upload(
                  result.getAbsolutePath(),
                  localEncoding,
                  remotePath,
                  remoteEncoding,
                  submonitor.newChild(1));
            } catch (IOException e) {
              throw new CoreException(
                  new Status(
                      IStatus.ERROR,
                      Activator.PLUGIN_ID,
                      Messages
                          .LuaRemoteLaunchConfigurationDelegate_error_unabletouploaddebuggerfiles,
                      e));
            }
          }
        }
      } catch (SystemMessageException e) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                Activator.PLUGIN_ID,
                NLS.bind(
                    Messages
                        .LuaRemoteLaunchConfigurationDelegate_error_unabletoaccestoremoteapplicationdir,
                    outputDirectory),
                e));
      }

      // set environment var
      Map<String, String> envVars = new HashMap<String, String>();
      String luaPath = luaSubSystem.getLuaPath();

      // if no luapath defined at subsystem level used the default one.
      if (luaPath == null || luaPath.isEmpty()) luaPath = "$LUA_PATH;"; // $NON-NLS-1$

      // add default lua envvar
      StringBuilder luaPathBuilder = new StringBuilder(luaPath);

      // check if lua path don't end with a ";"
      if (!luaPath.matches(".*;\\s*$")) // $NON-NLS-1$
      luaPathBuilder.append(";"); // $NON-NLS-1$

      // add working dir to lua path
      luaPathBuilder.append(remoteApplicationFolderPath);
      luaPathBuilder.append(remoteFileSubSystem.getSeparator());
      luaPathBuilder.append(LuaDebugConstants.LUA_PATTERN);
      // add init pattern for working dir to lua path
      luaPathBuilder.append(remoteApplicationFolderPath);
      luaPathBuilder.append(remoteFileSubSystem.getSeparator());
      luaPathBuilder.append(LuaDebugConstants.WILDCARD_PATTERN);
      luaPathBuilder.append(remoteFileSubSystem.getSeparator());
      luaPathBuilder.append(LuaDebugConstants.LUA_INIT_PATTERN);
      envVars.put(LuaDebugConstants.LUA_PATH, luaPathBuilder.toString());

      String luaCPath = luaSubSystem.getCLuaPath();
      if (luaCPath != null && !luaCPath.isEmpty())
        envVars.put(LuaDebugConstants.LUA_CPATH, luaCPath);

      String ldLibraryPath = luaSubSystem.getLDLibraryPath();
      if (ldLibraryPath != null && !ldLibraryPath.isEmpty())
        envVars.put(LuaDebugConstants.LUA_LDLIBRARYPATH, ldLibraryPath);

      // add launch configuration env vars
      for (Object oEntry : env.entrySet()) {
        @SuppressWarnings("rawtypes")
        Map.Entry entry = (Entry) oEntry;
        envVars.put(entry.getKey().toString(), entry.getValue().toString());
      }

      // add debug information
      String sessionID = null;
      if (mode.equals(ILaunchManager.DEBUG_MODE)) {
        sessionID = DbgpSessionIdGenerator.generate();

        // try to find host ide IP Address only if it's not define by user
        if (!envVars.containsKey(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST)) {
          String bindedAddress =
              NetworkUtil.findBindedAddress(host.getHostName(), submonitor.newChild(1));
          if (bindedAddress == null)
            throw new CoreException(
                new Status(
                    IStatus.ERROR,
                    Activator.PLUGIN_ID,
                    NLS.bind(
                        Messages.LuaRemoteLaunchConfigurationDelegate_error_unable_to_define_ideip,
                        LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST)));

          envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST, bindedAddress);
        }

        // dbgp env vars
        envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_KEY, sessionID);
        envVars.put(
            LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_PORT,
            String.valueOf(DLTKDebugPlugin.getDefault().getDbgpService().getPort()));
        envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_PLATFORM, "unix"); // $NON-NLS-1$
        envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_WORKINGDIR, remoteApplicationFolderPath);
        envVars.put(
            LuaDebugConstants.ENV_VAR_KEY_DBGP_TRANSPORT,
            "debugger.transport.luasocket_sched"); //$NON-NLS-1$
      }

      // create lua execution command
      StringBuilder cmd = new StringBuilder();

      // create command to run
      cmd.append(luaSubSystem.getLuaCommand());
      cmd.append(SshProcess.ARGUMENT_SEPARATOR);

      // insert interpreter args
      String interpreterArgs =
          configuration.getAttribute(LuaRemoteDebugConstant.INTERPRETER_ARGS, ""); // $NON-NLS-1$
      if (!interpreterArgs.isEmpty()) {
        cmd.append(interpreterArgs);
        cmd.append(SshProcess.ARGUMENT_SEPARATOR);
      }

      // FIXME is there a cleaner way to control buffering ?
      // see: http://lua-users.org/lists/lua-l/2011-05/msg00549.html
      String bootstrapCode = "io.stdout:setvbuf('line');"; // $NON-NLS-1$
      if (mode.equals(ILaunchManager.DEBUG_MODE)) {
        // load debugging libraries. The -l parameter cannot be used here because the debugger MUST
        // be the first module to be loaded
        bootstrapCode += " require('" + DEBGUGGER_MODULE + "')();"; // $NON-NLS-1$//$NON-NLS-2$
      }
      cmd.append("-e"); // $NON-NLS-1$
      cmd.append(SshProcess.ARGUMENT_SEPARATOR);
      cmd.append("\"" + bootstrapCode + "\""); // $NON-NLS-1$//$NON-NLS-2$
      cmd.append(SshProcess.ARGUMENT_SEPARATOR);
      cmd.append(SshProcess.escapeShell(scriptSourcePathRelativePath.toPortableString()));
      cmd.append(SshProcess.ARGUMENT_SEPARATOR);

      // insert script args
      String scriptArgs =
          configuration.getAttribute(LuaRemoteDebugConstant.SCRIPT_ARGS, ""); // $NON-NLS-1$
      if (!scriptArgs.isEmpty()) {
        cmd.append(scriptArgs);
        cmd.append(SshProcess.ARGUMENT_SEPARATOR);
      }

      submonitor.setWorkRemaining(1);

      // Create Process
      if (submonitor.isCanceled()) return;

      SshProcess process =
          new SshProcess(session, launch, remoteApplicationFolderPath, cmd.toString(), envVars);

      if (mode.equals(ILaunchManager.DEBUG_MODE)) {
        // Desactivate DBGP Stream redirection
        // TODO manage DBGP Stream redirection (so deactivate process redirection in debug mode)
        launch.setAttribute(
            DLTKDebugLaunchConstants.ATTR_DEBUG_CONSOLE, DLTKDebugLaunchConstants.FALSE);

        // manage break on first line
        if (configuration.getAttribute(LuaRemoteDebugConstant.BREAK_ON_FIRST_LINE, false)) {
          launch.setAttribute(
              DLTKDebugLaunchConstants.ATTR_BREAK_ON_FIRST_LINE, DLTKDebugLaunchConstants.TRUE);
        }

        // create runner
        LuaRemoteDebuggingEngineRunner debugingEngine =
            new LuaRemoteDebuggingEngineRunner(process, sessionID, remoteApplicationFolderPath);
        debugingEngine.run(new InterpreterConfig(), launch, submonitor.newChild(1));
        launch.addProcess(process);
      } else {
        process.start();
        launch.addProcess(process);
      }
    } finally {
      submonitor.done();
    }
  }
 protected String getHostLabel() {
   return configuration.getName();
 }
Example #22
0
  public void launch(
      ILaunchConfiguration config, String mode, final ILaunch launch, IProgressMonitor monitor)
      throws CoreException {
    if (!mode.equals(ILaunchManager.DEBUG_MODE)) {
      // Chromium JavaScript launch is only supported for debugging.
      return;
    }

    String host =
        config.getAttribute(
            LaunchParams.CHROMIUM_DEBUG_HOST,
            PluginVariablesUtil.getValue(PluginVariablesUtil.DEFAULT_HOST));

    int port =
        config.getAttribute(
            LaunchParams.CHROMIUM_DEBUG_PORT,
            PluginVariablesUtil.getValueAsInt(PluginVariablesUtil.DEFAULT_PORT));

    if (host == null && port == -1) {
      throw new RuntimeException("Missing parameters in launch config");
    }

    boolean addNetworkConsole = config.getAttribute(LaunchParams.ADD_NETWORK_CONSOLE, false);

    SourceWrapSupport sourceWrapSupport = createSourceWrapSupportFromConfig(config);

    JavascriptVmEmbedder.ConnectionToRemote remoteServer =
        createConnectionToRemote(host, port, launch, addNetworkConsole);
    try {

      final String projectNameBase = config.getName();

      DestructingGuard destructingGuard = new DestructingGuard();
      try {
        Destructable lauchDestructor =
            new Destructable() {
              public void destruct() {
                if (!launch.hasChildren()) {
                  DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
                }
              }
            };

        destructingGuard.addValue(lauchDestructor);

        WorkspaceBridge.Factory bridgeFactory =
            new VProjectWorkspaceBridge.FactoryImpl(projectNameBase);

        final DebugTargetImpl target =
            new DebugTargetImpl(launch, bridgeFactory, sourceWrapSupport, getPresetSyncDirection());

        Destructable targetDestructor =
            new Destructable() {
              public void destruct() {
                terminateTarget(target);
              }
            };
        destructingGuard.addValue(targetDestructor);

        launch.addDebugTarget(target);

        boolean attached =
            DebugTargetImpl.attach(
                target, remoteServer, destructingGuard, OPENING_VIEW_ATTACH_CALLBACK, monitor);
        if (!attached) {
          // Cancel pressed.
          return;
        }

        launch.addDebugTarget(target);
        monitor.done();

        // All OK
        destructingGuard.discharge();
      } finally {
        destructingGuard.doFinally();
      }

    } finally {
      remoteServer.disposeConnection();
    }
  }
  public TestRunSession(ILaunch launch, IScriptProject project, ITestRunnerClient runnerClient) {
    Assert.isNotNull(launch);
    Assert.isNotNull(runnerClient);

    fLaunch = launch;
    fProject = project;

    ILaunchConfiguration launchConfiguration = launch.getLaunchConfiguration();
    if (launchConfiguration != null) {
      fTestRunName = launchConfiguration.getName();
      fTestingEngine = DLTKTestingConstants.getTestingEngine(launchConfiguration);
      testRunnerUI = fTestingEngine.getTestRunnerUI(project, launchConfiguration);
      categoryEngines = TestCategoryEngineManager.getCategoryEngines(testRunnerUI);
    } else {
      fTestRunName = project.getElementName();
      fTestingEngine = NullTestingEngine.getInstance();
      testRunnerUI = NullTestRunnerUI.getInstance();
      categoryEngines = null;
    }

    fTestRoot = new TestRoot(this);
    fIdToTest = new HashMap<String, TestElement>();
    fCategoryMap = new HashMap<String, TestCategoryElement>();

    fTestRunnerClient = runnerClient;
    fTestRunnerClient.startListening(new TestSessionNotifier());

    final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
    launchManager.addLaunchListener(
        new ILaunchesListener2() {
          public void launchesTerminated(ILaunch[] launches) {
            if (Arrays.asList(launches).contains(fLaunch)) {
              if (fTestRunnerClient != null) {
                fTestRunnerClient.stopWaiting();
              }
              launchManager.removeLaunchListener(this);
              scheduleTestRunTerminated();
            }
          }

          public void launchesRemoved(ILaunch[] launches) {
            if (Arrays.asList(launches).contains(fLaunch)) {
              if (fTestRunnerClient != null) {
                fTestRunnerClient.stopWaiting();
              }
              launchManager.removeLaunchListener(this);
              scheduleTestRunTerminated();
            }
          }

          public void launchesChanged(ILaunch[] launches) {}

          public void launchesAdded(ILaunch[] launches) {}

          private void scheduleTestRunTerminated() {
            if (!fIsRunning) return;
            final Job job = new Job("TestRunSession - notify launch terminated") { // $NON-NLS-1$
                  @Override
                  protected IStatus run(IProgressMonitor monitor) {
                    testRunTerminated();
                    return org.eclipse.core.runtime.Status.OK_STATUS;
                  }
                };
            job.setSystem(true);
            // small delay, giving a chance for the client to notify in a
            // normal way.
            job.schedule(750);
          }
        });

    fSessionListeners = new ListenerList();
    addTestSessionListener(new TestRunListenerAdapter(this));
  }
 private static String getLaunchName(ILaunch launch) {
   ILaunchConfiguration launchConfiguration = launch.getLaunchConfiguration();
   // the launch config might be null (e.g. if deleted) even though there
   // still exists a launch for that config
   return launchConfiguration == null ? null : launchConfiguration.getName();
 }
  /**
   * Create debugging target similar to a remote debugging session would and add them to the launch.
   * This is to support debugging of 'forked mode' run-app and test-app processes. These are
   * processes spun-off by Grails in new JVM.
   *
   * @param port the remote launch will be listening on for forked process to connect to.
   */
  private void launchRemote(
      int port,
      ILaunchConfiguration configuration,
      String mode,
      ILaunch launch,
      IProgressMonitor monitor)
      throws CoreException {
    if (port < 0) {
      return;
    }
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }

    monitor.beginTask(
        NLS.bind(
            LaunchingMessages
                .JavaRemoteApplicationLaunchConfigurationDelegate_Attaching_to__0_____1,
            new String[] {configuration.getName()}),
        3);
    // check for cancellation
    if (monitor.isCanceled()) {
      return;
    }
    try {
      monitor.subTask(
          LaunchingMessages
              .JavaRemoteApplicationLaunchConfigurationDelegate_Verifying_launch_attributes____1);

      String connectorId =
          "org.eclipse.jdt.launching.socketListenConnector"; // getVMConnectorId(configuration);
      IVMConnector connector = JavaRuntime.getVMConnector(connectorId);
      if (connector == null) {
        abort(
            LaunchingMessages
                .JavaRemoteApplicationLaunchConfigurationDelegate_Connector_not_specified_2,
            null,
            IJavaLaunchConfigurationConstants.ERR_CONNECTOR_NOT_AVAILABLE);
      }

      Map<String, String> argMap = new HashMap<String, String>();

      //	        int connectTimeout = Platform.getPreferencesService().getInt(
      //	        		LaunchingPlugin.ID_PLUGIN,
      //	        		JavaRuntime.PREF_CONNECT_TIMEOUT,
      //	        		JavaRuntime.DEF_CONNECT_TIMEOUT,
      //	        		null);
      argMap.put(
          "timeout",
          "120000"); // Give grails run-app command enough time to build the app and kick off a
                     // forked process.
      argMap.put("port", "" + port);

      // check for cancellation
      if (monitor.isCanceled()) {
        return;
      }

      monitor.worked(1);

      // Don't think we need to set source location since the main launch method already does this.

      //
      //	monitor.subTask(LaunchingMessages.JavaRemoteApplicationLaunchConfigurationDelegate_Creating_source_locator____2);
      //			// set the default source locator if required
      //			setDefaultSourceLocator(launch, configuration);
      //			monitor.worked(1);

      // connect to remote VM
      connector.connect(argMap, monitor, launch);

      // check for cancellation
      if (monitor.isCanceled()) {
        IDebugTarget[] debugTargets = launch.getDebugTargets();
        for (int i = 0; i < debugTargets.length; i++) {
          IDebugTarget target = debugTargets[i];
          if (target.canDisconnect()) {
            target.disconnect();
          }
        }
        return;
      }
    } finally {
      monitor.done();
    }
  }