Java Code Examples for com.intellij.execution.ExecutionException

The following are top voted examples for showing how to use com.intellij.execution.ExecutionException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: react-native-console   File: TestParseIOSDevices.java   View source code 6 votes vote down vote up
@Test
    public void listDevices() {
        System.out.println(
                System.getProperty("user.home"));
//        System.getProperties().list(System.out);

        GeneralCommandLine commandLine = RNPathUtil.cmdToGeneralCommandLine(IOSDevicesParser.LIST_Simulator_JSON);

        try {
            String json = ExecUtil.execAndGetOutput(commandLine).getStdout();
            System.out.println("json=" + json);
            Simulators result = new Gson().fromJson(json, Simulators.class);
            System.out.println(result.devices.keySet());
            System.out.println(result.devices.get("iOS 10.3")[0]);
        } catch (ExecutionException e) {
            e.printStackTrace();
            NotificationUtils.errorNotification( "xcrun invocation failed. Please check that Xcode is installed." );
        }

    }
 
Example 2
Project: react-native-console   File: TestParseIOSDevices.java   View source code 6 votes vote down vote up
@Test
    public void parseCurrentPathFromRNConsoleJsonFile() {
        //        System.out.println(
//                System.getProperty("user.home"));
//        System.getProperties().list(System.out);

        GeneralCommandLine commandLine = RNPathUtil.cmdToGeneralCommandLine(IOSDevicesParser.LIST_DEVICES);
        try {
            String json = ExecUtil.execAndGetOutput(commandLine).getStdout();
            System.out.println(json);
            Arrays.asList(json.split("\n")).forEach(line -> {
                System.out.println(line);
//                Pattern pattern = Pattern
//                        .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
                boolean device = line.matches("^(.*?) \\((.*?)\\)\\ \\[(.*?)\\]");
                System.out.println("device=" + device);
//                String noSimulator = line.match(/(.*?) \((.*?)\) \[(.*?)\] \((.*?)\)/);
            });

        } catch (ExecutionException e) {
            e.printStackTrace();
            NotificationUtils.errorNotification( "xcrun invocation failed. Please check that Xcode is installed." );
            return;
        }
    }
 
Example 3
Project: intellij-ce-playground   File: ScriptRunnerUtil.java   View source code 6 votes vote down vote up
public static String getProcessOutput(@NotNull final ProcessHandler processHandler,
                                      @NotNull final Condition<Key> outputTypeFilter,
                                      final long timeout)
  throws ExecutionException {
  LOG.assertTrue(!processHandler.isStartNotified());
  final StringBuilder outputBuilder = new StringBuilder();
  processHandler.addProcessListener(new ProcessAdapter() {
    @Override
    public void onTextAvailable(ProcessEvent event, Key outputType) {
      if (outputTypeFilter.value(outputType)) {
        final String text = event.getText();
        outputBuilder.append(text);
        LOG.debug(text);
      }
    }
  });
  processHandler.startNotify();
  if (!processHandler.waitFor(timeout)) {
    throw new ExecutionException(ExecutionBundle.message("script.execution.timeout", String.valueOf(timeout / 1000)));
  }
  return outputBuilder.toString();
}
 
Example 4
Project: intellij-ce-playground   File: WinTerminalExecutor.java   View source code 6 votes vote down vote up
@NotNull
@Override
protected Process createProcess() throws ExecutionException {
  checkRedirectFile();

  List<String> parameters = escapeArguments(buildParameters());
  parameters.add(0, ExecUtil.getWindowsShellName());
  parameters.add(1, "/c");
  parameters.add(">>");
  //noinspection ConstantConditions
  parameters.add(quote(myRedirectFile.getAbsolutePath()));

  Process process = createProcess(parameters);

  return new ProcessWrapper(process) {
    @Override
    public InputStream getInputStream() {
      return myRedirectStream;
    }

    @Override
    public InputStream getErrorStream() {
      return getOriginalProcess().getInputStream();
    }
  };
}
 
Example 5
Project: intellij-ce-playground   File: PyPackageManagerImpl.java   View source code 6 votes vote down vote up
@Nullable
public Set<PyPackage> getDependents(@NotNull PyPackage pkg) throws ExecutionException {
  final List<PyPackage> packages = getPackages(false);
  if (packages != null) {
    final Set<PyPackage> dependents = new HashSet<PyPackage>();
    for (PyPackage p : packages) {
      final List<PyRequirement> requirements = p.getRequirements();
      for (PyRequirement requirement : requirements) {
        if (requirement.getName().equals(pkg.getName())) {
          dependents.add(p);
        }
      }
    }
    return dependents;
  }
  return null;
}
 
Example 6
Project: intellij-ce-playground   File: PyPackageManagementService.java   View source code 6 votes vote down vote up
@Override
public Collection<InstalledPackage> getInstalledPackages() throws IOException {
  List<PyPackage> packages;
  try {
    packages = PyPackageManager.getInstance(mySdk).getPackages(false);
    if (packages != null) {
      Collections.sort(packages, new Comparator<PyPackage>() {
        @Override
        public int compare(@NotNull PyPackage pkg1, @NotNull PyPackage pkg2) {
          return pkg1.getName().compareTo(pkg2.getName());
        }
      });
    }
  }
  catch (ExecutionException e) {
    throw new IOException(e);
  }
  return packages != null ? new ArrayList<InstalledPackage>(packages) : new ArrayList<InstalledPackage>();
}
 
Example 7
Project: intellij-ce-playground   File: PyPackagingTest.java   View source code 6 votes vote down vote up
public void testGetPackages() {
  runPythonTest(new PyPackagingTestTask() {
    @Override
    public void runTestOn(String sdkHome) throws Exception {
      final Sdk sdk = createTempSdk(sdkHome, SdkCreationType.EMPTY_SDK);
      List<PyPackage> packages = null;
      try {
        packages = PyPackageManager.getInstance(sdk).getPackages(false);
      }
      catch (ExecutionException ignored) {
      }
      if (packages != null) {
        assertTrue(packages.size() > 0);
        for (PyPackage pkg : packages) {
          assertTrue(pkg.getName().length() > 0);
        }
      }
    }
  });
}
 
Example 8
Project: intellij-ce-playground   File: MavenResumeAction.java   View source code 6 votes vote down vote up
public static boolean isApplicable(@Nullable Project project, JavaParameters javaParameters, MavenRunConfiguration runConfiguration) {
  if (hasResumeFromParameter(runConfiguration)) { // This runConfiguration was created by other MavenResumeAction.
    MavenRunConfiguration clonedRunConf = runConfiguration.clone();
    List<String> clonedGoals = clonedRunConf.getRunnerParameters().getGoals();
    clonedGoals.remove(clonedGoals.size() - 1);
    clonedGoals.remove(clonedGoals.size() - 1);
    try {
      javaParameters = clonedRunConf.createJavaParameters(project);
    }
    catch (ExecutionException e) {
      return false;
    }
  }

  for (String params : javaParameters.getProgramParametersList().getList()) {
    if (PARAMS_DISABLING_RESUME.contains(params)) {
      return false;
    }
  }

  return true;
}
 
Example 9
Project: intellij-ce-playground   File: CheckSdkOperation.java   View source code 6 votes vote down vote up
private static boolean checkRuns(File executable) {
  try {
    while (!checkCanRunSdkTool(executable)) {
      final boolean[] shouldRetry = {false};
      UIUtil.invokeAndWaitIfNeeded(new Runnable() {
        @Override
        public void run() {
          shouldRetry[0] = retryPrompt();
        }
      });
      if (!shouldRetry[0]) {
        return false;
      }
    }
  }
  catch (ExecutionException e) {
    return false;
  }
  return true;
}
 
Example 10
Project: intellij-ce-playground   File: CommandExecutor.java   View source code 6 votes vote down vote up
public void start() throws SvnBindException {
  synchronized (myLock) {
    checkNotStarted();

    try {
      beforeCreateProcess();
      myProcess = createProcess();
      if (LOG.isDebugEnabled()) {
        LOG.debug(myCommandLine.toString());
      }
      myHandler = createProcessHandler();
      myProcessWriter = new OutputStreamWriter(myHandler.getProcessInput());
      startHandlingStreams();
    }
    catch (ExecutionException e) {
      // TODO: currently startFailed() is not used for some real logic in svn4idea plugin
      listeners().startFailed(e);
      throw new SvnBindException(e);
    }
  }
}
 
Example 11
Project: swingexplorer-idea   File: Runner.java   View source code 6 votes vote down vote up
@Override
public void execute(@NotNull ExecutionEnvironment environment, @Nullable Callback callback, @NotNull RunProfileState state) throws ExecutionException
{
  ExecutionEnvironment fixedEnv = RunContentBuilder.fix(environment, this);

  // IntelliJ-Projekt holen und alle offenen Dokumente speichern
  project = fixedEnv.getProject();
  FileDocumentManager.getInstance().saveAllDocuments();

  // Java-Settings initialisieren
  _initJavaSettings(state);

  // Ausf�hren
  super.execute(environment, new Callback()
  {
    @Override
    public void processStarted(RunContentDescriptor pRunContentDescriptor)
    {
      // Listener initialisieren, damit Benachrichtigungen vom SwingExplorer ankommen
      _initListener();
    }
  }, state);
}
 
Example 12
Project: intellij-ce-playground   File: IpnbParser.java   View source code 6 votes vote down vote up
public static boolean isIpythonNewFormat(@NotNull final VirtualFile virtualFile) {
  final Project project = ProjectUtil.guessProjectForFile(virtualFile);
  if (project != null) {
    final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile);
    if (module != null) {
      final Sdk sdk = PythonSdkType.findPythonSdk(module);
      if (sdk != null) {
        try {
          final PyPackage ipython = PyPackageManager.getInstance(sdk).findPackage("ipython", true);
          if (ipython != null && VersionComparatorUtil.compare(ipython.getVersion(), "3.0") <= 0) {
            return false;
          }
        }
        catch (ExecutionException ignored) {
        }
      }
    }
  }
  return true;
}
 
Example 13
Project: intellij-ce-playground   File: MavenResumeAction.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  Project project = myEnvironment.getProject();
  try {
    MavenRunConfiguration runConfiguration = ((MavenRunConfiguration)myEnvironment.getRunProfile()).clone();

    List<String> goals = runConfiguration.getRunnerParameters().getGoals();

    if (goals.size() > 2 && "-rf".equals(goals.get(goals.size() - 2))) { // This runConfiguration was created by other MavenResumeAction.
      goals.set(goals.size() - 1, myResumeModuleId);
    }
    else {
      goals.add("-rf");
      goals.add(myResumeModuleId);
    }

    runConfiguration.getRunnerParameters().setGoals(goals);

    myRunner.execute(new ExecutionEnvironmentBuilder(myEnvironment).contentToReuse(null).runProfile(runConfiguration).build());
  }
  catch (RunCanceledByUserException ignore) {
  }
  catch (ExecutionException e1) {
    Messages.showErrorDialog(project, e1.getMessage(), ExecutionBundle.message("restart.error.message.title"));
  }
}
 
Example 14
Project: intellij-ce-playground   File: PyRemoteProcessStarter.java   View source code 6 votes vote down vote up
protected PyRemoteProcessHandlerBase doStartRemoteProcess(@NotNull Sdk sdk,
                                                          @NotNull final GeneralCommandLine commandLine,
                                                          @NotNull final PythonRemoteInterpreterManager manager,
                                                          @Nullable final Project project,
                                                          @Nullable PyRemotePathMapper pathMapper)
  throws ExecutionException {
  SdkAdditionalData data = sdk.getSdkAdditionalData();
  assert data instanceof PyRemoteSdkAdditionalDataBase;
  final PyRemoteSdkAdditionalDataBase pyRemoteSdkAdditionalDataBase = (PyRemoteSdkAdditionalDataBase)data;

  final PyRemotePathMapper extendedPathMapper = manager.setupMappings(project, pyRemoteSdkAdditionalDataBase, pathMapper);

  try {
    return PyRemoteProcessStarterManagerUtil
      .getManager(pyRemoteSdkAdditionalDataBase).startRemoteProcess(project, commandLine, manager, pyRemoteSdkAdditionalDataBase,
                                                   extendedPathMapper);
  }
  catch (InterruptedException e) {
    throw new ExecutionException(e);
  }
}
 
Example 15
Project: intellij-ce-playground   File: RemoteExternalSystemCommunicationManager.java   View source code 6 votes vote down vote up
public RemoteExternalSystemCommunicationManager(@NotNull ExternalSystemProgressNotificationManager notificationManager) {
  myProgressManager = (ExternalSystemProgressNotificationManagerImpl)notificationManager;
  mySupport = new RemoteProcessSupport<Object, RemoteExternalSystemFacade, String>(RemoteExternalSystemFacade.class) {
    @Override
    protected void fireModificationCountChanged() {
    }

    @Override
    protected String getName(Object o) {
      return RemoteExternalSystemFacade.class.getName();
    }

    @Override
    protected RunProfileState getRunProfileState(Object o, String configuration, Executor executor) throws ExecutionException {
      return createRunProfileState(configuration);
    }
  };

  ShutDownTracker.getInstance().registerShutdownTask(new Runnable() {
    public void run() {
      shutdown(false);
    }
  });
}
 
Example 16
Project: intellij   File: BlazeAndroidBinaryMobileInstallRunContext.java   View source code 6 votes vote down vote up
@Nullable
@Override
@SuppressWarnings("unchecked")
public DebugConnectorTask getDebuggerTask(
    AndroidDebugger androidDebugger,
    AndroidDebuggerState androidDebuggerState,
    Set<String> packageIds,
    boolean monitorRemoteProcess)
    throws ExecutionException {
  return androidDebugger.getConnectDebuggerTask(
      env,
      null,
      packageIds,
      facet,
      androidDebuggerState,
      runConfiguration.getType().getId(),
      monitorRemoteProcess);
}
 
Example 17
Project: intellij-ce-playground   File: PySkeletonRefresher.java   View source code 6 votes vote down vote up
/**
 * Creates a new object that refreshes skeletons of given SDK.
 *
 * @param sdk           a Python SDK
 * @param skeletonsPath if known; null means 'determine and create as needed'.
 * @param indicator     to report progress of long operations
 */
public PySkeletonRefresher(@Nullable Project project,
                           @Nullable Component ownerComponent,
                           @NotNull Sdk sdk,
                           @Nullable String skeletonsPath,
                           @Nullable ProgressIndicator indicator,
                           @Nullable String folder)
  throws InvalidSdkException {
  myProject = project;
  myIndicator = indicator;
  mySdk = sdk;
  mySkeletonsPath = skeletonsPath;
  final PythonRemoteInterpreterManager remoteInterpreterManager = PythonRemoteInterpreterManager.getInstance();
  if (PySdkUtil.isRemote(sdk) && remoteInterpreterManager != null) {
    try {
      mySkeletonsGenerator = remoteInterpreterManager.createRemoteSkeletonGenerator(myProject, ownerComponent, sdk, getSkeletonsPath());
    }
    catch (ExecutionException e) {
      throw new InvalidSdkException(e.getMessage(), e.getCause());
    }
  }
  else {
    mySkeletonsGenerator = new PySkeletonGenerator(getSkeletonsPath(), mySdk, folder);
  }
}
 
Example 18
Project: intellij-ce-playground   File: GradleManager.java   View source code 6 votes vote down vote up
@Override
public void enhanceRemoteProcessing(@NotNull SimpleJavaParameters parameters) throws ExecutionException {
  final Set<String> additionalEntries = ContainerUtilRt.newHashSet();
  for (GradleProjectResolverExtension extension : RESOLVER_EXTENSIONS.getValue()) {
    ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(extension.getClass()));
    for (Class aClass : extension.getExtraProjectModelClasses()) {
      ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(aClass));
    }
    extension.enhanceRemoteProcessing(parameters);
  }

  final PathsList classPath = parameters.getClassPath();
  for (String entry : additionalEntries) {
    classPath.add(entry);
  }

  parameters.getVMParametersList().addProperty(
    ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY, GradleConstants.SYSTEM_ID.getId());
}
 
Example 19
Project: intellij-ce-playground   File: PythonTestCommandLineStateBase.java   View source code 6 votes vote down vote up
@Override
public ExecutionResult execute(Executor executor, CommandLinePatcher... patchers) throws ExecutionException {
  final ProcessHandler processHandler = startProcess(patchers);
  final ConsoleView console = createAndAttachConsole(myConfiguration.getProject(), processHandler, executor);

  List<AnAction> actions = Lists
    .newArrayList(createActions(console, processHandler));

  DefaultExecutionResult executionResult =
    new DefaultExecutionResult(console, processHandler, actions.toArray(new AnAction[actions.size()]));

  PyRerunFailedTestsAction rerunFailedTestsAction = new PyRerunFailedTestsAction(console);
  if (console instanceof SMTRunnerConsoleView) {
    rerunFailedTestsAction.init(((BaseTestsOutputConsoleView)console).getProperties());
    rerunFailedTestsAction.setModelProvider(new Getter<TestFrameworkRunningModel>() {
    @Override
    public TestFrameworkRunningModel get() {
      return ((SMTRunnerConsoleView)console).getResultsViewer();
    }
  });
  }

  executionResult.setRestartActions(rerunFailedTestsAction, new ToggleAutoTestAction());
  return executionResult;
}
 
Example 20
Project: intellij   File: BlazeIntellijPluginDeployer.java   View source code 6 votes vote down vote up
@Nullable
private static String readPluginIdFromJar(String buildNumber, File jar)
    throws ExecutionException {
  IdeaPluginDescriptor pluginDescriptor = PluginManagerCore.loadDescriptor(jar, "plugin.xml");
  if (pluginDescriptor == null) {
    return null;
  }
  if (PluginManagerCore.isIncompatible(pluginDescriptor, BuildNumber.fromString(buildNumber))) {
    throw new ExecutionException(
        String.format(
            "Plugin SDK version '%s' is incompatible with this plugin "
                + "(since: '%s', until: '%s')",
            buildNumber, pluginDescriptor.getSinceBuild(), pluginDescriptor.getUntilBuild()));
  }
  return pluginDescriptor.getPluginId().getIdString();
}
 
Example 21
Project: react-native-console   File: RNConsoleImpl.java   View source code 5 votes vote down vote up
public void reRun() {
    if(myGeneralCommandLine != null) {
        try {
            processCommandline(myGeneralCommandLine);
        } catch (ExecutionException e) {
            NotificationUtils.showNotification("Unable to run the commandline:" + e.getMessage(),
                    NotificationType.WARNING);
        }
    }
}
 
Example 22
Project: react-native-console   File: RNConsoleImpl.java   View source code 5 votes vote down vote up
/**
 * 执行shell
 *
 * @param shell
 */
public void executeShell(String shell, String workDirectory) {
    GeneralCommandLine commandLine =RNPathUtil.createFullPathCommandLine(shell, workDirectory);
    commandLine.setWorkDirectory(workDirectory);
    myGeneralCommandLine = commandLine;
    try {
        processCommandline(commandLine);
    } catch (ExecutionException e) {
        NotificationUtils.showNotification("Unable to run the commandline:" + e.getMessage(),
                NotificationType.WARNING);
    }
}
 
Example 23
Project: react-native-console   File: RNConsoleImpl.java   View source code 5 votes vote down vote up
/**
 * Execute raw commands without any path or param modify.
 *
 * @param shell
 */
public void executeRawShell(String workDirectory, String[] shell) {
    GeneralCommandLine commandLine =new GeneralCommandLine(shell);
    commandLine.setWorkDirectory(workDirectory);
    myGeneralCommandLine = commandLine;
    try {
        processCommandline(commandLine);
    } catch (ExecutionException e) {
        NotificationUtils.showNotification("Unable to run the commandline:" + e.getMessage(),
                NotificationType.WARNING);
    }
}
 
Example 24
Project: react-native-console   File: RNUtil.java   View source code 5 votes vote down vote up
public static void runGradleCI(Project project, String... params) {
        String path = RNPathUtil.getRNProjectPath(project);
        String gradleLocation = RNPathUtil.getAndroidProjectPath(path);
        if (gradleLocation == null) {
            NotificationUtils.gradleFileNotFound();
        } else {
            GeneralCommandLine commandLine = new GeneralCommandLine();
//    ExecutionEnvironment environment = getEnvironment();
            commandLine.setWorkDirectory(gradleLocation);
            commandLine.setExePath("." + File.separator + "gradlew");
            commandLine.addParameters(params);

//            try {
////            Process process = commandLine.createProcess();
//                OSProcessHandler processHandler = new KillableColoredProcessHandler(commandLine);
//                RunnerUtil.showHelperProcessRunContent("Update AAR", processHandler, project, DefaultRunExecutor.getRunExecutorInstance());
//                // Run
//                processHandler.startNotify();
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//                NotificationUtils.errorNotification("Can't execute command: " + e.getMessage());
//            }

            // commands process
            try {
                processCommandline(project, commandLine);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
 
Example 25
Project: react-native-console   File: RNUtil.java   View source code 5 votes vote down vote up
public static void build(Project project) {
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setWorkDirectory(project.getBasePath());
    commandLine.setExePath("python");
    commandLine.addParameter("freeline.py");
    // debug
    commandLine.addParameter("-d");

    // commands process
    try {
        processCommandline(project, commandLine);
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}
 
Example 26
Project: react-native-console   File: RNUtil.java   View source code 5 votes vote down vote up
private static void processCommandline(final Project project, GeneralCommandLine commandLine) throws ExecutionException {
        final OSProcessHandler processHandler = new OSProcessHandler(commandLine);
        ProcessTerminatedListener.attach(processHandler);
//        processHandler.startNotify();// Don't call this, the command content will not be shown

        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                processConsole(project, processHandler);
            }
        });
    }
 
Example 27
Project: react-native-console   File: FreeRunConfiguration.java   View source code 5 votes vote down vote up
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
    // here just run one command: python freeline.py
    GeneralCommandLine commandLine = new GeneralCommandLine();
    ExecutionEnvironment environment = getEnvironment();
    commandLine.setWorkDirectory(environment.getProject().getBasePath());
    commandLine.setExePath("npm");
    commandLine.addParameters("list");
    return new OSProcessHandler(commandLine);
}
 
Example 28
Project: react-native-console   File: FreeRunConfiguration.java   View source code 5 votes vote down vote up
@Nullable
@Override
protected ConsoleView createConsole(@NotNull Executor executor) throws ExecutionException {
    ConsoleView console = super.createConsole(executor);
    // before run new task,clean log
    if (console != null) {
        console.clear();
    }
    return console;
}
 
Example 29
Project: AppleScript-IDEA   File: AppleScriptScriptCommandLineState.java   View source code 5 votes vote down vote up
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
  String scriptPath = runConfiguration.getScriptPath();
  String scriptParameters = runConfiguration.getScriptParameters();
  String scriptOptions = runConfiguration.getScriptOptions();

  scriptPath = scriptPath == null ? "" : scriptPath;//todo change this (and add validator to run config)
  final List<String> commandString = new ArrayList<>();
  commandString.add("/usr/bin/osascript");
  if (!StringUtil.isEmpty(scriptOptions)) {
    String[] options = scriptOptions.split(" ");
    commandString.addAll(Arrays.asList(options));
  }
  commandString.add(scriptPath);
  if (!StringUtil.isEmpty(scriptParameters)) {
    Pattern regex = Pattern.compile("\"([^\"]*)\"|(\\w+)");
    final ArrayList<String> matchedParams = new ArrayList<>();
    Matcher matcher = regex.matcher(scriptParameters);
    while (matcher.find()) {
      for (int i = 1; i <= matcher.groupCount(); i++) {
        try {
          String p = matcher.group(i);
          if (!StringUtil.isEmpty(p)) matchedParams.add(p);
        } catch (IllegalStateException | IndexOutOfBoundsException e) {
          LOG.warn("Error parsing script parameters: " + e.getMessage());
        }
      }
    }
    commandString.addAll(matchedParams);
  }

  final GeneralCommandLine commandLine = new GeneralCommandLine(commandString);
  if (runConfiguration.isShowAppleEvents()) {
    commandLine.withEnvironment("AEDebugSends", "1");
    commandLine.withEnvironment("AEDebugReceives", "1");
  }
  return new AppleScriptProcessHandler(commandLine);
}
 
Example 30
Project: reasonml-idea-plugin   File: BsCompiler.java   View source code 5 votes vote down vote up
@Nullable
public ProcessHandler recreate() {
    try {
        killIt();
        m_bsb = new KillableColoredProcessHandler(m_commandLine);
        if (m_outputListener != null) {
            m_bsb.addProcessListener(m_outputListener);
        }
        return m_bsb;
    } catch (ExecutionException e) {
        Notifications.Bus.notify(new RmlNotification("Bsb", "Can't run bsb\n" + e.getMessage(), NotificationType.ERROR));
    }

    return null;
}
 
Example 31
Project: LaravelStorm   File: FileMakerDlg.java   View source code 5 votes vote down vote up
@Override
protected void doOKAction() {

    Notification notification = new Notification("LaravelStorm",
            "Success", "temp content", NotificationType.INFORMATION);

    Notification errorNotification = new Notification("LaravelStorm",
            "Error", "Could not create file.", NotificationType.ERROR);

    GeneralCommandLine cmd = new GeneralCommandLine("php", "artisan");
    cmd.setWorkDirectory(project.getBasePath());

    cmd.addParameter(artisanCommand);

    if (additionCommandCheckBox.isSelected())
        cmd.addParameter(optionCmdParameter);

    cmd.addParameter(fileName.getText());

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(cmd.createProcess().getInputStream()));
        String execResult = reader.readLine();
        if (execResult.isEmpty()){
            Notifications.Bus.notify(errorNotification, project);
        }
        else{
            notification.setContent(execResult);
            Notifications.Bus.notify(notification, project);
        }
    } catch (ExecutionException | IOException e) {
        e.printStackTrace();
    }

    super.doOKAction();
}
 
Example 32
Project: teamcity-powershell   File: DetectionRunner.java   View source code 5 votes vote down vote up
/**
 * Runs detection script
 *
 * @param executablePath executable to run script with
 * @param detectionScriptPath file containing detection script
 * @return lines from stdout
 * @throws ExecutionException if there was an error during execution
 */
List<String> runDetectionScript(@NotNull final String executablePath, @NotNull final String detectionScriptPath) throws ExecutionException {
  final GeneralCommandLine cl = new GeneralCommandLine();
  cl.setExePath(executablePath);
  cl.addParameter("-NoProfile");
  cl.addParameter("-File");
  cl.addParameter(detectionScriptPath);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Running detection script using command line: " + cl.getCommandLineString());
  }
  final ProcessOutput execResult = runProcess(cl);
  return execResult.getStdoutLines();
}
 
Example 33
Project: teamcity-powershell   File: DetectionRunner.java   View source code 5 votes vote down vote up
private static ProcessOutput runProcess(@NotNull final GeneralCommandLine cl) throws ExecutionException {
  final CapturingProcessHandler handler = new CapturingProcessHandler(cl.createProcess(), Charset.forName("UTF-8"));
  final ProcessOutput result = handler.runProcess(20000);
  if (result.isTimeout()) {
    throw new ExecutionException("Process execution of [" + cl.getCommandLineString() + "] has timed out");
  }
  final String errorOutput = result.getStderr();
  if (!StringUtil.isEmptyOrSpaces(errorOutput)) {
    throw new ExecutionException(errorOutput);
  }
  return result;
}
 
Example 34
Project: teamcity-powershell   File: CommandLinePowerShellDetector.java   View source code 5 votes vote down vote up
@Nullable
private PowerShellInfo doDetect(@NotNull final String homePath,
                                @NotNull final String executable,
                                @NotNull final String scriptPath) {
  PowerShellInfo result = null;
  final File exeFile = new File(homePath, executable);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Searching for PowerShell at " + exeFile.getAbsolutePath());
  }
  if (exeFile.isFile()) {
    String executablePath = exeFile.getAbsolutePath();
    try {
      final List<String> outputLines = myRunner.runDetectionScript(executablePath, scriptPath);
      if (outputLines.size() == 3) {
        final PowerShellEdition edition = PowerShellEdition.fromString(outputLines.get(1));
        if (edition != null) {
          result = new PowerShellInfo(Boolean.valueOf(outputLines.get(2)) ? PowerShellBitness.x64 : PowerShellBitness.x86, exeFile.getParentFile(), outputLines.get(0), edition, executable);
        } else {
          LOG.warn("Failed to determine PowerShell edition for [" + executablePath + "]");
          LOG.debug(StringUtil.join("\n", outputLines));
        }
      } else {
        LOG.warn("Failed to parse output from PowerShell executable [" + executablePath + "]");
        LOG.debug(StringUtil.join("\n", outputLines));
      }
    } catch (ExecutionException e) {
      LOG.warnAndDebugDetails("Failed to run PowerShell detection script [" + scriptPath + "] with executable [" + executablePath + "]", e);
    }
  } else {
    if (LOG.isDebugEnabled()) {
      LOG.debug("PowerShell at " + exeFile.getAbsolutePath() + " was not found");
    }
  }
  return result;
}
 
Example 35
Project: SmartTomcat   File: AppCommandLineState.java   View source code 5 votes vote down vote up
private void addBinFolder(Path tomcatInstallation, JavaParameters javaParams) throws ExecutionException {
    // Dynamically adds the tomcat jars to the classpath
    Path binFolder = tomcatInstallation.resolve("bin");
    if (!Files.exists(binFolder)) {
        throw new ExecutionException("The Tomcat installation configured doesn't contains a bin folder");
    }
    String[] jars = binFolder.toFile().list((dir, name) -> name.endsWith(".jar"));

    assert jars != null;
    for (String jarFile : jars) {
        javaParams.getClassPath().add(binFolder.resolve(jarFile).toFile().getAbsolutePath());
    }
}
 
Example 36
Project: SmartTomcat   File: AppCommandLineState.java   View source code 5 votes vote down vote up
private void addLibFolder(Path tomcatInstallation, JavaParameters javaParams) throws ExecutionException {
    // add libs folder
    Path libFolder = tomcatInstallation.resolve("lib");
    if (!Files.exists(libFolder)) {
        throw new ExecutionException("The Tomcat installation configured doesn't contains a lib folder");
    }
    String[] jars = libFolder.toFile().list((dir, name) -> name.endsWith(".jar"));

    assert jars != null;
    for (String jarFile : jars) {
        javaParams.getClassPath().add(libFolder.resolve(jarFile).toFile().getAbsolutePath());
    }
}
 
Example 37
Project: hybris-integration-intellij-idea-plugin   File: HybrisJUnitExtension.java   View source code 5 votes vote down vote up
@Override
public <T extends RunConfigurationBase> void updateJavaParameters(
    final T configuration, final JavaParameters params, final RunnerSettings runnerSettings
) throws ExecutionException {
    if (runnerSettings != null || !isApplicableFor(configuration)) {
        return;
    }
    final Project project = configuration.getProject();
    final ParametersList vmParameters = params.getVMParametersList();

    if (!vmParameters.hasParameter("-ea")) {
        vmParameters.add("-ea");
    }
    if (vmParameters.getParameters().stream().noneMatch(param -> param.startsWith("-Dplatformhome="))) {
        final VirtualFile platformRootDirectory = findPlatformRootDirectory(project);

        if (platformRootDirectory != null) {
            vmParameters.add("-Dplatformhome=" + platformRootDirectory.getPath());
        }
    }
    if (!params.getEnv().containsKey(HYBRIS_DATA_DIR_ENV)) {
        final HybrisProjectSettings settings = HybrisProjectSettingsComponent.getInstance(project).getState();

        final String hybrisDataDirPath = FileUtil.toCanonicalPath(
            project.getBasePath() + '/' + settings.getHybrisDirectory() + '/' + HybrisConstants.HYBRIS_DATA_DIRECTORY);

        if (hybrisDataDirPath != null) {
            params.addEnv(HYBRIS_DATA_DIR_ENV, hybrisDataDirPath);
        }
    }
}
 
Example 38
Project: educational-plugin   File: PyStudyDirectoryProjectGenerator.java   View source code 5 votes vote down vote up
public void createAndAddVirtualEnv(Project project, PyNewProjectSettings settings) {
  final ProjectSdksModel model = PyConfigurableInterpreterList.getInstance(project).getModel();
  Course course = StudyTaskManager.getInstance(project).getCourse();
  if (course == null) {
    return;
  }
  final String baseSdk = getBaseSdk(course);

  if (baseSdk != null) {
    final PyPackageManager packageManager = PyPackageManager.getInstance(new PyDetectedSdk(baseSdk));
    try {
      final String path = packageManager.createVirtualEnv(project.getBasePath() + "/.idea/VirtualEnvironment", false);
      AbstractCreateVirtualEnvDialog.setupVirtualEnvSdk(path, true, new AbstractCreateVirtualEnvDialog.VirtualEnvCallback() {
        @Override
        public void virtualEnvCreated(Sdk createdSdk, boolean associateWithProject) {
          settings.setSdk(createdSdk);
          model.addSdk(createdSdk);
          try {
            model.apply();
          }
          catch (ConfigurationException exception) {
            LOG.error("Error adding created virtual env " + exception.getMessage());
          }
          if (associateWithProject) {
            SdkAdditionalData additionalData = createdSdk.getSdkAdditionalData();
            if (additionalData == null) {
              additionalData = new PythonSdkAdditionalData(PythonSdkFlavor.getFlavor(createdSdk.getHomePath()));
              ((ProjectJdkImpl)createdSdk).setSdkAdditionalData(additionalData);
            }
            ((PythonSdkAdditionalData)additionalData).associateWithNewProject();
          }
        }
      });
    }
    catch (ExecutionException e) {
      LOG.warn("Failed to create virtual env " + e.getMessage());
    }
  }
}
 
Example 39
Project: educational-plugin   File: PyStudyTaskChecker.java   View source code 5 votes vote down vote up
@Override
public StudyCheckResult check() {
  VirtualFile taskDir = myTask.getTaskDir(myProject);
  if (taskDir == null) {
    LOG.info("taskDir is null for task " + myTask.getName());
    return new StudyCheckResult(StudyStatus.Unchecked, "Task is broken");
  }
  CountDownLatch latch = new CountDownLatch(1);
  ApplicationManager.getApplication()
    .invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> {
      StudyCheckUtils.flushWindows(myTask, taskDir);
      latch.countDown();
    }));
  final PyStudyTestRunner testRunner = new PyStudyTestRunner(myTask, taskDir);
  try {
    final VirtualFile fileToCheck = getTaskVirtualFile(myTask, taskDir);
    if (fileToCheck != null) {
      //otherwise answer placeholders might have been not flushed yet
      latch.await();
      Process testProcess = testRunner.createCheckProcess(myProject, fileToCheck.getPath());
      StudyTestsOutputParser.TestsOutput output =
        StudyCheckUtils
          .getTestOutput(testProcess, testRunner.getCommandLine().getCommandLineString(), myTask.getLesson().getCourse().isAdaptive());
      return new StudyCheckResult(output.isSuccess() ? StudyStatus.Solved : StudyStatus.Failed, output.getMessage());
    }
  }
  catch (ExecutionException | InterruptedException e) {
    LOG.error(e);
  }
  return new StudyCheckResult(StudyStatus.Unchecked, StudyCheckAction.FAILED_CHECK_LAUNCH);
}
 
Example 40
Project: educational-plugin   File: PyStudyTestRunner.java   View source code 5 votes vote down vote up
Process createCheckProcess(@NotNull final Project project, @NotNull final String executablePath) throws ExecutionException {
  final Sdk sdk = PythonSdkType.findPythonSdk(ModuleManager.getInstance(project).getModules()[0]);
  PyEduPluginConfigurator configurator = new PyEduPluginConfigurator();
  String testsFileName = configurator.getTestFileName();
  if (myTask instanceof TaskWithSubtasks) {
    testsFileName = FileUtil.getNameWithoutExtension(testsFileName);
    int index = ((TaskWithSubtasks)myTask).getActiveSubtaskIndex();
    testsFileName += EduNames.SUBTASK_MARKER + index + "." + FileUtilRt.getExtension(configurator.getTestFileName());
  }
  final File testRunner = new File(myTaskDir.getPath(), testsFileName);
  myCommandLine = new GeneralCommandLine();
  myCommandLine.withWorkDirectory(myTaskDir.getPath());
  final Map<String, String> env = myCommandLine.getEnvironment();

  final VirtualFile courseDir = project.getBaseDir();
  if (courseDir != null) {
    env.put(PYTHONPATH, courseDir.getPath());
  }
  if (sdk != null) {
    String pythonPath = sdk.getHomePath();
    if (pythonPath != null) {
      myCommandLine.setExePath(pythonPath);
      myCommandLine.addParameter(testRunner.getPath());
      myCommandLine.addParameter(FileUtil.toSystemDependentName(executablePath));
      return myCommandLine.createProcess();
    }
  }
  return null;
}