<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.di

import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.{SimpleComponent, SimpleComponent2}
import com.yahoo.container.di.componentgraph.Provider
import com.yahoo.container.di.componentgraph.core.{ComponentGraph, Node}
import org.junit.{After, Before, Test}
import org.junit.Assert._
import org.hamcrest.CoreMatchers._
import com.yahoo.config.test.TestConfig
import com.yahoo.component.AbstractComponent
import ContainerTest._

import scala.collection.JavaConversions
import com.yahoo.config.di.IntConfig

import scala.concurrent.{Await, future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Try
import com.yahoo.container.di.config.RestApiContext
import com.yahoo.container.bundle.MockBundle

import scala.language.postfixOps

/**
 * @author tonytv
 * @author gjoranv
 */
class ContainerTest {
  var dirConfigSource: DirConfigSource = _

  @Before def setup()  {
    dirConfigSource = new DirConfigSource("ContainerTest-")
  }

  @After def cleanup() {
    dirConfigSource.cleanup()
  }

  @Test
  def components_can_be_created_from_config() {
    writeBootstrapConfigs()
    dirConfigSource.writeConfig("test", """stringVal "myString" """)

    val container = newContainer(dirConfigSource)

    val component = createComponentTakingConfig(container.runOnce())
    assertThat(component.config.stringVal(), is("myString"))

    container.shutdownConfigurer()
  }

  @Test
  def components_are_reconfigured_after_config_update_without_bootstrap_configs() {
    writeBootstrapConfigs()
    dirConfigSource.writeConfig("test", """stringVal "original" """)

    val container = newContainer(dirConfigSource)

    val componentGraph = container.runOnce()
    val component = createComponentTakingConfig(componentGraph)

    assertThat(component.config.stringVal(), is("original"))

    // Reconfigure
    dirConfigSource.writeConfig("test", """stringVal "reconfigured" """)
    container.reloadConfig(2)

    val newComponentGraph = container.runOnce(componentGraph)
    val component2 = createComponentTakingConfig(newComponentGraph)
    assertThat(component2.config.stringVal(), is("reconfigured"))

    container.shutdownConfigurer()
  }

  @Test
  def graph_is_updated_after_bootstrap_update() {
    dirConfigSource.writeConfig("test", """stringVal "original" """)
    writeBootstrapConfigs("id1")

    val container = newContainer(dirConfigSource)

    val graph = container.runOnce()
    val component = createComponentTakingConfig(graph)
    assertThat(component.getId.toString, is("id1"))

    writeBootstrapConfigsWithMultipleComponents(Array(
      ("id1", classOf[ComponentTakingConfig]),
      ("id2", classOf[ComponentTakingConfig])))

    container.reloadConfig(2)
    val newGraph = container.runOnce(graph)

    assertThat(ComponentGraph.getNode(newGraph, "id1"), notNullValue(classOf[Node]))
    assertThat(ComponentGraph.getNode(newGraph, "id2"), notNullValue(classOf[Node]))

    container.shutdownConfigurer()
  }

  //@Test TODO
  def deconstructor_is_given_guice_components() {
  }

  @Test
  def osgi_component_is_deconstructed_when_not_reused() {
    writeBootstrapConfigs("id1", classOf[DestructableComponent])

    val container = newContainer(dirConfigSource)

    val oldGraph = container.runOnce()
    val componentToDestruct = oldGraph.getInstance(classOf[DestructableComponent])

    writeBootstrapConfigs("id2", classOf[DestructableComponent])
    container.reloadConfig(2)
    container.runOnce(oldGraph)
    assertTrue(componentToDestruct.deconstructed)
  }

  @Test
  def previous_graph_is_retained_when_new_graph_throws_exception() {
    val simpleComponentEntry = ComponentEntry("simpleComponent", classOf[SimpleComponent])

    writeBootstrapConfigs(Array(simpleComponentEntry))
    val container = newContainer(dirConfigSource)
    var currentGraph = container.runOnce()

    val simpleComponent = currentGraph.getInstance(classOf[SimpleComponent])

    writeBootstrapConfigs("thrower", classOf[ComponentThrowingException])
    dirConfigSource.writeConfig("test", """stringVal "myString" """)
    container.reloadConfig(2)
    try {
      currentGraph = container.runOnce(currentGraph)
      fail("Expected exception")
    } catch {
      case e: Exception => e.printStackTrace()
    }

    val componentTakingConfigEntry = ComponentEntry("componentTakingConfig", classOf[ComponentTakingConfig])
    writeBootstrapConfigs(Array(simpleComponentEntry, componentTakingConfigEntry))
    container.reloadConfig(3)
    currentGraph = container.runOnce(currentGraph)

    assertSame(simpleComponent, currentGraph.getInstance(classOf[SimpleComponent]))
    assertNotNull(currentGraph.getInstance(classOf[ComponentTakingConfig]))
  }

  @Test
  def runOnce_hangs_waiting_for_valid_config_after_invalid_config() {
    dirConfigSource.writeConfig("test", """stringVal "original" """)
    writeBootstrapConfigs("myId", classOf[ComponentTakingConfig])

    val container = newContainer(dirConfigSource)
    var currentGraph = container.runOnce()

    writeBootstrapConfigs("thrower", classOf[ComponentThrowingException])
    container.reloadConfig(2)

    try {
      currentGraph = container.runOnce(currentGraph)
      fail("expected exception")
    } catch {
      case e: Exception =>
    }

    val newGraph = future {
      currentGraph = container.runOnce(currentGraph)
      currentGraph
    }

    Try {
      Await.ready(newGraph, 1 second)
    } foreach { x => fail("Expected waiting for new config.") }


    writeBootstrapConfigs("myId2", classOf[ComponentTakingConfig])
    container.reloadConfig(3)

    assertNotNull(Await.result(newGraph, 5 minutes))
  }


  @Test
  def bundle_info_is_set_on_rest_api_context() {
    val clazz = classOf[RestApiContext]

    writeBootstrapConfigs("restApiContext", clazz)
    dirConfigSource.writeConfig("jersey-bundles", """bundles[0].spec "mock-entry-to-enforce-a-MockBundle" """)
    dirConfigSource.writeConfig("jersey-injection", """inject[0]" """)

    val container = newContainer(dirConfigSource)
    val componentGraph = container.runOnce()
<commit_msg>Use Future instead of deprecated future.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.di

import com.yahoo.component.AbstractComponent
import com.yahoo.config.di.IntConfig
import com.yahoo.config.test.TestConfig
import com.yahoo.container.bundle.MockBundle
import com.yahoo.container.di.ContainerTest._
import com.yahoo.container.di.componentgraph.Provider
import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.{SimpleComponent, SimpleComponent2}
import com.yahoo.container.di.componentgraph.core.{ComponentGraph, Node}
import com.yahoo.container.di.config.RestApiContext
import org.hamcrest.CoreMatchers._
import org.junit.Assert._
import org.junit.{After, Before, Test}

import scala.collection.JavaConversions
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.language.postfixOps
import scala.util.Try

/**
 * @author tonytv
 * @author gjoranv
 */
class ContainerTest {
  var dirConfigSource: DirConfigSource = _

  @Before def setup()  {
    dirConfigSource = new DirConfigSource("ContainerTest-")
  }

  @After def cleanup() {
    dirConfigSource.cleanup()
  }

  @Test
  def components_can_be_created_from_config() {
    writeBootstrapConfigs()
    dirConfigSource.writeConfig("test", """stringVal "myString" """)

    val container = newContainer(dirConfigSource)

    val component = createComponentTakingConfig(container.runOnce())
    assertThat(component.config.stringVal(), is("myString"))

    container.shutdownConfigurer()
  }

  @Test
  def components_are_reconfigured_after_config_update_without_bootstrap_configs() {
    writeBootstrapConfigs()
    dirConfigSource.writeConfig("test", """stringVal "original" """)

    val container = newContainer(dirConfigSource)

    val componentGraph = container.runOnce()
    val component = createComponentTakingConfig(componentGraph)

    assertThat(component.config.stringVal(), is("original"))

    // Reconfigure
    dirConfigSource.writeConfig("test", """stringVal "reconfigured" """)
    container.reloadConfig(2)

    val newComponentGraph = container.runOnce(componentGraph)
    val component2 = createComponentTakingConfig(newComponentGraph)
    assertThat(component2.config.stringVal(), is("reconfigured"))

    container.shutdownConfigurer()
  }

  @Test
  def graph_is_updated_after_bootstrap_update() {
    dirConfigSource.writeConfig("test", """stringVal "original" """)
    writeBootstrapConfigs("id1")

    val container = newContainer(dirConfigSource)

    val graph = container.runOnce()
    val component = createComponentTakingConfig(graph)
    assertThat(component.getId.toString, is("id1"))

    writeBootstrapConfigsWithMultipleComponents(Array(
      ("id1", classOf[ComponentTakingConfig]),
      ("id2", classOf[ComponentTakingConfig])))

    container.reloadConfig(2)
    val newGraph = container.runOnce(graph)

    assertThat(ComponentGraph.getNode(newGraph, "id1"), notNullValue(classOf[Node]))
    assertThat(ComponentGraph.getNode(newGraph, "id2"), notNullValue(classOf[Node]))

    container.shutdownConfigurer()
  }

  //@Test TODO
  def deconstructor_is_given_guice_components() {
  }

  @Test
  def osgi_component_is_deconstructed_when_not_reused() {
    writeBootstrapConfigs("id1", classOf[DestructableComponent])

    val container = newContainer(dirConfigSource)

    val oldGraph = container.runOnce()
    val componentToDestruct = oldGraph.getInstance(classOf[DestructableComponent])

    writeBootstrapConfigs("id2", classOf[DestructableComponent])
    container.reloadConfig(2)
    container.runOnce(oldGraph)
    assertTrue(componentToDestruct.deconstructed)
  }

  @Test
  def previous_graph_is_retained_when_new_graph_throws_exception() {
    val simpleComponentEntry = ComponentEntry("simpleComponent", classOf[SimpleComponent])

    writeBootstrapConfigs(Array(simpleComponentEntry))
    val container = newContainer(dirConfigSource)
    var currentGraph = container.runOnce()

    val simpleComponent = currentGraph.getInstance(classOf[SimpleComponent])

    writeBootstrapConfigs("thrower", classOf[ComponentThrowingException])
    dirConfigSource.writeConfig("test", """stringVal "myString" """)
    container.reloadConfig(2)
    try {
      currentGraph = container.runOnce(currentGraph)
      fail("Expected exception")
    } catch {
      case e: Exception => e.printStackTrace()
    }

    val componentTakingConfigEntry = ComponentEntry("componentTakingConfig", classOf[ComponentTakingConfig])
    writeBootstrapConfigs(Array(simpleComponentEntry, componentTakingConfigEntry))
    container.reloadConfig(3)
    currentGraph = container.runOnce(currentGraph)

    assertSame(simpleComponent, currentGraph.getInstance(classOf[SimpleComponent]))
    assertNotNull(currentGraph.getInstance(classOf[ComponentTakingConfig]))
  }

  @Test
  def runOnce_hangs_waiting_for_valid_config_after_invalid_config() {
    dirConfigSource.writeConfig("test", """stringVal "original" """)
    writeBootstrapConfigs("myId", classOf[ComponentTakingConfig])

    val container = newContainer(dirConfigSource)
    var currentGraph = container.runOnce()

    writeBootstrapConfigs("thrower", classOf[ComponentThrowingException])
    container.reloadConfig(2)

    try {
      currentGraph = container.runOnce(currentGraph)
      fail("expected exception")
    } catch {
      case e: Exception =>
    }

    val newGraph = Future {
      currentGraph = container.runOnce(currentGraph)
      currentGraph
    }

    Try {
      Await.ready(newGraph, 1 second)
    } foreach { x => fail("Expected waiting for new config.") }


    writeBootstrapConfigs("myId2", classOf[ComponentTakingConfig])
    container.reloadConfig(3)

    assertNotNull(Await.result(newGraph, 5 minutes))
  }


  @Test
  def bundle_info_is_set_on_rest_api_context() {
    val clazz = classOf[RestApiContext]

    writeBootstrapConfigs("restApiContext", clazz)
    dirConfigSource.writeConfig("jersey-bundles", """bundles[0].spec "mock-entry-to-enforce-a-MockBundle" """)
    dirConfigSource.writeConfig("jersey-injection", """inject[0]" """)

    val container = newContainer(dirConfigSource)
    val componentGraph = container.runOnce()

{'fraction_non_alphanumeric': 0.10360431883137504, 'fraction_numerical': 0.004604636392505557, 'mean_word_length': 5.178028445316332, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '3873652', 'n_tokens_mistral': 3654, 'n_tokens_neox': 3519, 'n_words': 605}