<commit_before>/** *****************************************************************************
  * Copyright (c) 2016, 2017 Red Hat Inc. and others.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
  * http://www.eclipse.org/legal/epl-v10.html
  *
  * Contributors:
  * <NAME> (Red Hat Inc.) - initial implementation
  * <NAME> (TypeFox) - extracted LanguageClientImpl
  * <NAME> (TypeFox) - bug 521744
  * ******************************************************************************/
package com.github.gtache.client

import java.io.{File, IOException}
import java.net.URI
import java.util.concurrent._

import com.github.gtache.Utils
import com.github.gtache.editor.EditorEventManager
import com.github.gtache.editor.listeners.{DocumentListenerImpl, EditorMouseListenerImpl, EditorMouseMotionListenerImpl, SelectionListenerImpl}
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import org.eclipse.lsp4j._
import org.eclipse.lsp4j.jsonrpc.ResponseErrorException
import org.eclipse.lsp4j.jsonrpc.messages.{Either, Message, ResponseErrorCode, ResponseMessage}
import org.eclipse.lsp4j.launch.LSPLauncher
import org.eclipse.lsp4j.services.LanguageServer
import org.jetbrains.annotations.Nullable

import scala.collection.mutable

class LanguageServerWrapper(val serverDefinition: LanguageServerDefinition, val commands: Seq[String], val workingDir: String) {

  private val lspStreamProvider: StreamConnectionProvider = serverDefinition.createConnectionProvider(commands, workingDir)
  private val connectedEditors: mutable.Map[String, EditorEventManager] = mutable.HashMap()
  private val LOG: Logger = Logger.getInstance(classOf[LanguageServerWrapper])
  private var languageServer: LanguageServer = _
  private var client: LanguageClientImpl = _
  private var requestManager: RequestManager = _
  private var initializeResult: InitializeResult = _
  private var launcherFuture: Future[_] = _
  private var initializeFuture: CompletableFuture[InitializeResult] = _
  private var capabilitiesAlreadyRequested = false
  private var initializeStartTime = 0L
  private var started: Boolean = false

  /**
    * Returns the EditorEventManager for a given uri
    *
    * @param uri the URI as a string
    * @return the EditorEventManager (or null)
    */
  def getManagerFor(uri: String): EditorEventManager = {
    connectedEditors.get(uri).orNull
  }

  /**
    * Starts the LanguageServer
    */
  @throws[IOException]
  def start(rootFolder: String): Unit = {
    if (!started) {
      try {
        this.lspStreamProvider.start()
        client = serverDefinition.createLanguageClient
        val executorService = Executors.newCachedThreadPool
        val initParams = new InitializeParams
        initParams.setRootUri(new File(rootFolder).toURI.toString)
        //initParams.setRootPath(project.getLocation.toFile.getAbsolutePath)
        /*val launcher = LSPLauncher.createClientLauncher(client, this.lspStreamProvider.getInputStream, this.lspStreamProvider.getOutputStream, executorService, (consumer: MessageConsumer) => (message: Message) => {
        consumer.consume(message)
        logMessage(message)
        this.lspStreamProvider.handleMessage(message, this.languageServer, URI.create(initParams.getRootUri))
      })
      */
        val launcher = LSPLauncher.createClientLauncher(client, this.lspStreamProvider.getInputStream, this.lspStreamProvider.getOutputStream)

        this.languageServer = launcher.getRemoteProxy
        client.connect(languageServer)
        requestManager = new SimpleRequestManager(languageServer, client)
        this.launcherFuture = launcher.startListening
        val name = "Intellij" //$NON-NLS-1$
        val workspaceClientCapabilites = new WorkspaceClientCapabilities
        workspaceClientCapabilites.setApplyEdit(true)
        workspaceClientCapabilites.setExecuteCommand(new ExecuteCommandCapabilities)
        workspaceClientCapabilites.setSymbol(new SymbolCapabilities)
        val textDocumentClientCapabilities = new TextDocumentClientCapabilities
        textDocumentClientCapabilities.setCodeAction(new CodeActionCapabilities)
        textDocumentClientCapabilities.setCodeLens(new CodeLensCapabilities)
        textDocumentClientCapabilities.setCompletion(new CompletionCapabilities(new CompletionItemCapabilities(true)))
        textDocumentClientCapabilities.setDefinition(new DefinitionCapabilities)
        textDocumentClientCapabilities.setDocumentHighlight(new DocumentHighlightCapabilities)
        textDocumentClientCapabilities.setDocumentLink(new DocumentLinkCapabilities)
        textDocumentClientCapabilities.setDocumentSymbol(new DocumentSymbolCapabilities)
        textDocumentClientCapabilities.setFormatting(new FormattingCapabilities)
        textDocumentClientCapabilities.setHover(new HoverCapabilities)
        textDocumentClientCapabilities.setOnTypeFormatting(null)

        textDocumentClientCapabilities.setRangeFormatting(new RangeFormattingCapabilities)
        textDocumentClientCapabilities.setReferences(new ReferencesCapabilities)
        textDocumentClientCapabilities.setRename(new RenameCapabilities)
        textDocumentClientCapabilities.setSignatureHelp(new SignatureHelpCapabilities)
        textDocumentClientCapabilities.setSynchronization(new SynchronizationCapabilities(true, true, true))
        initParams.setCapabilities(new ClientCapabilities(workspaceClientCapabilites, textDocumentClientCapabilities, null))
        initParams.setClientName(name)
        initParams.setInitializationOptions(this.lspStreamProvider.getInitializationOptions(URI.create(initParams.getRootUri)))
        initializeFuture = languageServer.initialize(initParams).thenApply((res: InitializeResult) => {
          initializeResult = res
          LOG.info("Got initializeResult")
          res
        })
        initializeStartTime = System.currentTimeMillis
        started = true
      }
      catch {
        case ex: Exception =><commit_msg>Do not use InitializeParams#setClientName<commit_after>/** *****************************************************************************
  * Copyright (c) 2016, 2017 Red Hat Inc. and others.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
  * http://www.eclipse.org/legal/epl-v10.html
  *
  * Contributors:
  * <NAME> (Red Hat Inc.) - initial implementation
  * <NAME> (TypeFox) - extracted LanguageClientImpl
  * <NAME> (TypeFox) - bug 521744
  * ******************************************************************************/
package com.github.gtache.client

import java.io.{File, IOException}
import java.net.URI
import java.util.concurrent._

import com.github.gtache.Utils
import com.github.gtache.editor.EditorEventManager
import com.github.gtache.editor.listeners.{DocumentListenerImpl, EditorMouseListenerImpl, EditorMouseMotionListenerImpl, SelectionListenerImpl}
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import org.eclipse.lsp4j._
import org.eclipse.lsp4j.jsonrpc.ResponseErrorException
import org.eclipse.lsp4j.jsonrpc.messages.{Either, Message, ResponseErrorCode, ResponseMessage}
import org.eclipse.lsp4j.launch.LSPLauncher
import org.eclipse.lsp4j.services.LanguageServer
import org.jetbrains.annotations.Nullable

import scala.collection.mutable

class LanguageServerWrapper(val serverDefinition: LanguageServerDefinition, val commands: Seq[String], val workingDir: String) {

  private val lspStreamProvider: StreamConnectionProvider = serverDefinition.createConnectionProvider(commands, workingDir)
  private val connectedEditors: mutable.Map[String, EditorEventManager] = mutable.HashMap()
  private val LOG: Logger = Logger.getInstance(classOf[LanguageServerWrapper])
  private var languageServer: LanguageServer = _
  private var client: LanguageClientImpl = _
  private var requestManager: RequestManager = _
  private var initializeResult: InitializeResult = _
  private var launcherFuture: Future[_] = _
  private var initializeFuture: CompletableFuture[InitializeResult] = _
  private var capabilitiesAlreadyRequested = false
  private var initializeStartTime = 0L
  private var started: Boolean = false

  /**
    * Returns the EditorEventManager for a given uri
    *
    * @param uri the URI as a string
    * @return the EditorEventManager (or null)
    */
  def getManagerFor(uri: String): EditorEventManager = {
    connectedEditors.get(uri).orNull
  }

  /**
    * Starts the LanguageServer
    */
  @throws[IOException]
  def start(rootFolder: String): Unit = {
    if (!started) {
      try {
        this.lspStreamProvider.start()
        client = serverDefinition.createLanguageClient
        val executorService = Executors.newCachedThreadPool
        val initParams = new InitializeParams
        initParams.setRootUri(new File(rootFolder).toURI.toString)
        //initParams.setRootPath(project.getLocation.toFile.getAbsolutePath)
        /*val launcher = LSPLauncher.createClientLauncher(client, this.lspStreamProvider.getInputStream, this.lspStreamProvider.getOutputStream, executorService, (consumer: MessageConsumer) => (message: Message) => {
        consumer.consume(message)
        logMessage(message)
        this.lspStreamProvider.handleMessage(message, this.languageServer, URI.create(initParams.getRootUri))
      })
      */
        val launcher = LSPLauncher.createClientLauncher(client, this.lspStreamProvider.getInputStream, this.lspStreamProvider.getOutputStream)

        this.languageServer = launcher.getRemoteProxy
        client.connect(languageServer)
        requestManager = new SimpleRequestManager(languageServer, client)
        this.launcherFuture = launcher.startListening
        val name = "Intellij" //$NON-NLS-1$
        val workspaceClientCapabilites = new WorkspaceClientCapabilities
        workspaceClientCapabilites.setApplyEdit(true)
        workspaceClientCapabilites.setExecuteCommand(new ExecuteCommandCapabilities)
        workspaceClientCapabilites.setSymbol(new SymbolCapabilities)
        val textDocumentClientCapabilities = new TextDocumentClientCapabilities
        textDocumentClientCapabilities.setCodeAction(new CodeActionCapabilities)
        textDocumentClientCapabilities.setCodeLens(new CodeLensCapabilities)
        textDocumentClientCapabilities.setCompletion(new CompletionCapabilities(new CompletionItemCapabilities(true)))
        textDocumentClientCapabilities.setDefinition(new DefinitionCapabilities)
        textDocumentClientCapabilities.setDocumentHighlight(new DocumentHighlightCapabilities)
        textDocumentClientCapabilities.setDocumentLink(new DocumentLinkCapabilities)
        textDocumentClientCapabilities.setDocumentSymbol(new DocumentSymbolCapabilities)
        textDocumentClientCapabilities.setFormatting(new FormattingCapabilities)
        textDocumentClientCapabilities.setHover(new HoverCapabilities)
        textDocumentClientCapabilities.setOnTypeFormatting(null)

        textDocumentClientCapabilities.setRangeFormatting(new RangeFormattingCapabilities)
        textDocumentClientCapabilities.setReferences(new ReferencesCapabilities)
        textDocumentClientCapabilities.setRename(new RenameCapabilities)
        textDocumentClientCapabilities.setSignatureHelp(new SignatureHelpCapabilities)
        textDocumentClientCapabilities.setSynchronization(new SynchronizationCapabilities(true, true, true))
        initParams.setCapabilities(new ClientCapabilities(workspaceClientCapabilites, textDocumentClientCapabilities, null))
        initParams.setInitializationOptions(this.lspStreamProvider.getInitializationOptions(URI.create(initParams.getRootUri)))
        initializeFuture = languageServer.initialize(initParams).thenApply((res: InitializeResult) => {
          initializeResult = res
          LOG.info("Got initializeResult")
          res
        })
        initializeStartTime = System.currentTimeMillis
        started = true
      }
      catch {
        case ex: Exception =>
{'fraction_non_alphanumeric': 0.09511379394730402, 'fraction_numerical': 0.004078636104086793, 'mean_word_length': 4.860420650095603, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2139016', 'n_tokens_mistral': 3128, 'n_tokens_neox': 3055, 'n_words': 614}