protected synchronized void execute(GeneralCommandLine commandLine)
      throws AuthenticationException {
    try {
      commandLine.getEnvironment().clear();
      commandLine.getEnvironment().putAll(EnvironmentUtil.getEnvironmentProperties());
      myProcess = commandLine.createProcess();

      myErrThread =
          new ReadProcessThread(
              new BufferedReader(
                  new InputStreamReader(
                      myProcess.getErrorStream(),
                      EncodingManager.getInstance().getDefaultCharset()))) {
            protected void textAvailable(String s) {
              myErrorText.append(s);
              myErrorRegistry.registerError(s);
              myContainsError = true;
            }
          };
      final Application application = ApplicationManager.getApplication();
      myStdErrFuture = application.executeOnPooledThread(myErrThread);

      myInputStream = myProcess.getInputStream();
      myOutputStream = myProcess.getOutputStream();

      waitForProcess(application);
    } catch (Exception e) {
      closeInternal();
      throw new AuthenticationException(e.getLocalizedMessage(), e);
    }
  }
示例#2
0
 @Nullable(
     "null means no luck, otherwise it's tuple(guessed encoding, hint about content if was unable to guess, BOM)")
 public static Trinity<Charset, CharsetToolkit.GuessedEncoding, byte[]> guessFromContent(
     @NotNull VirtualFile virtualFile, @NotNull byte[] content, int length) {
   Charset defaultCharset =
       ObjectUtils.notNull(
           EncodingManager.getInstance().getEncoding(virtualFile, true),
           CharsetToolkit.getDefaultSystemCharset());
   CharsetToolkit toolkit = GUESS_UTF ? new CharsetToolkit(content, defaultCharset) : null;
   String detectedFromBytes = null;
   try {
     if (GUESS_UTF) {
       toolkit.setEnforce8Bit(true);
       Charset charset = toolkit.guessFromBOM();
       if (charset != null) {
         detectedFromBytes = AUTO_DETECTED_FROM_BOM;
         byte[] bom =
             ObjectUtils.notNull(CharsetToolkit.getMandatoryBom(charset), CharsetToolkit.UTF8_BOM);
         return Trinity.create(charset, null, bom);
       }
       CharsetToolkit.GuessedEncoding guessed = toolkit.guessFromContent(length);
       if (guessed == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
         detectedFromBytes = "auto-detected from bytes";
         return Trinity.create(
             CharsetToolkit.UTF8_CHARSET, guessed, null); // UTF detected, ignore all directives
       }
       if (guessed == CharsetToolkit.GuessedEncoding.SEVEN_BIT) {
         return Trinity.create(null, guessed, null);
       }
     }
     return null;
   } finally {
     setCharsetWasDetectedFromBytes(virtualFile, detectedFromBytes);
   }
 }
 /** @return File encoding or <code>null</code> if the encoding is unknown. */
 @Nullable
 private static Charset calcEncoding(File file) {
   VirtualFile vf = VcsUtil.getVirtualFile(file);
   return ApplicationManager.getApplication().isDisposed()
       ? null
       : EncodingManager.getInstance().getEncoding(vf, false);
 }
  public static String loadRevisionContentGuessEncoding(
      @NotNull final VcsFileRevision revision,
      @Nullable final VirtualFile file,
      @Nullable final Project project)
      throws VcsException, IOException {
    final byte[] bytes = loadRevisionContent(revision);
    if (file != null) {
      return new String(bytes, file.getCharset());
    }
    EncodingManager e = project != null ? EncodingProjectManager.getInstance(project) : null;
    if (e == null) {
      e = EncodingManager.getInstance();
    }

    return CharsetToolkit.bytesToString(bytes, e.getDefaultCharset());
  }
  @Nullable("returns null if charset set cannot be determined from content")
  private static Charset cachedCharsetFromContent(final VirtualFile virtualFile) {
    if (virtualFile == null) return null;
    final Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
    if (document == null) return null;

    return EncodingManager.getInstance().getCachedCharsetFromContent(document);
  }
  public static Map<String, String> addDefaultEnvironments(Sdk sdk, Map<String, String> envs) {
    Charset defaultCharset = EncodingManager.getInstance().getDefaultCharset();

    final String encoding = defaultCharset != null ? defaultCharset.name() : "utf-8";
    setPythonIOEncoding(setPythonUnbuffered(envs), encoding);

    PythonSdkFlavor.initPythonPath(envs, true, PythonCommandLineState.getAddedPaths(sdk));
    return envs;
  }
  @Override
  public void setUp() throws Exception {
    super.setUp();

    initApplication();
    setUpProject();

    EncodingManager.getInstance(); // adds listeners
    myEditorListenerTracker = new EditorListenerTracker();
    myThreadTracker = new ThreadTracker();
    InjectedLanguageManagerImpl.pushInjectors(getProject());
  }
  @Override
  public void install(@NotNull StatusBar statusBar) {
    super.install(statusBar);
    // should update to reflect encoding-from-content
    EncodingManager.getInstance()
        .addPropertyChangeListener(
            new PropertyChangeListener() {
              @Override
              public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName()
                    .equals(EncodingManagerImpl.PROP_CACHED_ENCODING_CHANGED)) {
                  Document document =
                      evt.getSource() instanceof Document ? (Document) evt.getSource() : null;
                  updateForDocument(document);
                }
              }
            },
            this);
    ApplicationManager.getApplication()
        .getMessageBus()
        .connect(this)
        .subscribe(
            VirtualFileManager.VFS_CHANGES,
            new BulkVirtualFileListenerAdapter(
                new VirtualFileAdapter() {
                  @Override
                  public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
                    if (VirtualFile.PROP_ENCODING.equals(event.getPropertyName())) {
                      updateForFile(event.getFile());
                    }
                  }
                }));

    EditorFactory.getInstance()
        .getEventMulticaster()
        .addDocumentListener(
            new DocumentAdapter() {
              @Override
              public void documentChanged(DocumentEvent e) {
                Document document = e.getDocument();
                updateForDocument(document);
              }
            },
            this);
  }
 @Nullable
 public String convert(final VirtualFilePointer pointer) {
   if (pointer == null) return null;
   final String path = pointer.getPresentableUrl();
   final ByteContent byteContent =
       myLabel.getByteContent(FileUtil.toSystemIndependentName(path));
   if (byteContent == null || byteContent.isDirectory() || byteContent.getBytes() == null) {
     return null;
   }
   final VirtualFile vf = pointer.getFile();
   if (vf == null) {
     return LoadTextUtil.getTextByBinaryPresentation(
             byteContent.getBytes(), EncodingManager.getInstance().getDefaultCharset())
         .toString();
   } else {
     return LoadTextUtil.getTextByBinaryPresentation(byteContent.getBytes(), vf).toString();
   }
 }
 private static void appendEncoding(
     SimpleJavaParameters javaParameters,
     GeneralCommandLine commandLine,
     ParametersList parametersList) {
   // Value of file.encoding and charset of GeneralCommandLine should be in sync in order process's
   // input and output be correctly handled.
   String encoding = parametersList.getPropertyValue("file.encoding");
   if (encoding == null) {
     Charset charset = javaParameters.getCharset();
     if (charset == null) charset = EncodingManager.getInstance().getDefaultCharset();
     commandLine.addParameter("-Dfile.encoding=" + charset.name());
     commandLine.withCharset(charset);
   } else {
     try {
       Charset charset = Charset.forName(encoding);
       commandLine.withCharset(charset);
     } catch (UnsupportedCharsetException ignore) {
     } catch (IllegalCharsetNameException ignore) {
     }
   }
 }
  /**
   * @param project
   * @param parameters
   * @param coreSettings
   * @param runnerSettings
   * @param runConfiguration used to creation fix if maven home not found
   * @return
   * @throws ExecutionException
   */
  public static JavaParameters createJavaParameters(
      @Nullable final Project project,
      @NotNull final MavenRunnerParameters parameters,
      @Nullable MavenGeneralSettings coreSettings,
      @Nullable MavenRunnerSettings runnerSettings,
      @Nullable MavenRunConfiguration runConfiguration)
      throws ExecutionException {
    final JavaParameters params = new JavaParameters();

    ApplicationManager.getApplication().assertReadAccessAllowed();

    if (coreSettings == null) {
      coreSettings =
          project == null
              ? new MavenGeneralSettings()
              : MavenProjectsManager.getInstance(project).getGeneralSettings();
    }
    if (runnerSettings == null) {
      runnerSettings =
          project == null ? new MavenRunnerSettings() : MavenRunner.getInstance(project).getState();
    }

    params.setWorkingDirectory(parameters.getWorkingDirFile());

    params.setJdk(
        getJdk(
            project,
            runnerSettings,
            project != null && MavenRunner.getInstance(project).getState() == runnerSettings));

    final String mavenHome = resolveMavenHome(coreSettings, project, runConfiguration);

    addVMParameters(params.getVMParametersList(), mavenHome, runnerSettings);

    File confFile = MavenUtil.getMavenConfFile(new File(mavenHome));
    if (!confFile.isFile()) {
      throw new ExecutionException(
          "Configuration file is not exists in maven home: " + confFile.getAbsolutePath());
    }

    if (project != null && parameters.isResolveToWorkspace()) {
      try {
        String resolverJar = getArtifactResolverJar(MavenUtil.isMaven3(mavenHome));
        confFile = patchConfFile(confFile, resolverJar);

        File modulesPathsFile = dumpModulesPaths(project);
        params
            .getVMParametersList()
            .addProperty(MavenModuleMap.PATHS_FILE_PROPERTY, modulesPathsFile.getAbsolutePath());
      } catch (IOException e) {
        LOG.error(e);
        throw new ExecutionException("Failed to run maven configuration", e);
      }
    }

    params.getVMParametersList().addProperty("classworlds.conf", confFile.getPath());

    for (String path : getMavenClasspathEntries(mavenHome)) {
      params.getClassPath().add(path);
    }

    params.setMainClass(MAVEN_LAUNCHER_CLASS);
    EncodingManager encodingManager =
        project == null
            ? EncodingProjectManager.getInstance()
            : EncodingProjectManager.getInstance(project);
    params.setCharset(encodingManager.getDefaultCharset());

    addMavenParameters(
        params.getProgramParametersList(), mavenHome, coreSettings, runnerSettings, parameters);

    return params;
  }
  private static CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings buildGlobalSettings() {
    final Map<String, String> data = new HashMap<String, String>();

    for (Map.Entry<String, String> entry : PathMacrosImpl.getGlobalSystemMacros().entrySet()) {
      data.put(entry.getKey(), FileUtil.toSystemIndependentName(entry.getValue()));
    }

    final PathMacros pathVars = PathMacros.getInstance();
    for (String name : pathVars.getAllMacroNames()) {
      final String path = pathVars.getValue(name);
      if (path != null) {
        data.put(name, FileUtil.toSystemIndependentName(path));
      }
    }

    final List<GlobalLibrary> globals = new ArrayList<GlobalLibrary>();

    fillSdks(globals);
    fillGlobalLibraries(globals);

    final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.Builder cmdBuilder =
        CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.newBuilder();

    if (!data.isEmpty()) {
      for (Map.Entry<String, String> entry : data.entrySet()) {
        final String var = entry.getKey();
        final String value = entry.getValue();
        if (var != null && value != null) {
          cmdBuilder.addPathVariable(CmdlineProtoUtil.createPair(var, value));
        }
      }
    }

    if (!globals.isEmpty()) {
      for (GlobalLibrary lib : globals) {
        final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.GlobalLibrary.Builder
            libBuilder =
                CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.GlobalLibrary
                    .newBuilder();
        libBuilder.setName(lib.getName()).addAllPath(lib.getPaths());
        if (lib instanceof SdkLibrary) {
          final SdkLibrary sdk = (SdkLibrary) lib;
          libBuilder.setHomePath(sdk.getHomePath());
          libBuilder.setTypeName(sdk.getTypeName());
          final String additional = sdk.getAdditionalDataXml();
          if (additional != null) {
            libBuilder.setAdditionalDataXml(additional);
          }
          final String version = sdk.getVersion();
          if (version != null) {
            libBuilder.setVersion(version);
          }
        }
        cmdBuilder.addGlobalLibrary(libBuilder.build());
      }
    }

    final String defaultCharset = EncodingManager.getInstance().getDefaultCharsetName();
    if (defaultCharset != null) {
      cmdBuilder.setGlobalEncoding(defaultCharset);
    }

    final String ignoredFilesList = FileTypeManager.getInstance().getIgnoredFilesList();
    cmdBuilder.setIgnoredFilesPatterns(ignoredFilesList);
    return cmdBuilder.build();
  }