<commit_before>/**
 * Copyright (C) 2014 SINTEF <<EMAIL>>
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * This code generator targets the Kevoree Framework.
 * Formerly wrapping the Scala code generated from ThingML (by <NAME> <<EMAIL>>),
 * this new compiler now wraps the plain Java code generated from ThingML
 * @author: <NAME> <<EMAIL>>
 */
package org.thingml.javagenerator.kevoree

import java.io._
import java.nio.file.{StandardCopyOption, FileSystems, Files}

import org.sintef.thingml._
import org.thingml.compilers.helpers.JavaHelper
import org.thingml.compilers.main.JavaMainGenerator
import org.thingml.compilers.{JavaCompiler, Context}
import org.thingml.javagenerator.JavaGenerator._
import org.thingml.javagenerator.extension.Context

import scala.collection.JavaConversions._
import scala.io.Source

object Context {

  val ctx: Context = new Context(new JavaCompiler(), "match", "requires", "type", "abstract", "do", "finally", "import", "object", "throw", "case", "else", "for", "lazy", "override", "return", "trait", "catch", "extends", "forSome", "match", "package", "sealed", "try", "while", "class", "false", "if", "new", "private", "super", "true", "final", "null", "protected", "this", "_", ":", "=", "=>", "<-", "<:", "<%", ">:", "#", "@")

  val builder = new java.lang.StringBuilder()

  var thing: Thing = _
  var pack: String = _
  var port_name: String = _
  var file_name: String = _
  var wrapper_name: String = _


  val keywords = scala.List("abstract", "continue", "for", "new", "switch", "assert", "default", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "volatile", "float", "native", "super", "while")

  def protectJavaKeyword(value: String): String = {
    if (keywords.exists(p => p.equals(value))) {
      return "_" + value + "_"
    }
    else {
      return value
    }
  }

  def firstToUpper(value: String): String = {
    return value.capitalize
  }

  def init {
    builder.delete(0, builder.length())
    thing = null
    pack = null
    port_name = null
    file_name = null
    wrapper_name = null
  }
}

object KevoreeGenerator {
  //implicit def kevoreeGeneratorAspect(self: Thing): ThingKevoreeGenerator = ThingKevoreeGenerator(self)

  /*
   * 
   */
  def compileAndRun(cfg: Configuration, model: ThingMLModel, outputFolder : String) {
    val rootDir = if (outputFolder == null)System.getProperty("java.io.tmpdir") + "/ThingML_temp/" + cfg.getName else outputFolder
    val outputDir = rootDir + "/src/main/java/org/thingml/generated/kevoree"

    val outputDirFile = new File(outputDir)
    outputDirFile.mkdirs

    Context.init
    Context.pack = "org.thingml.generated"
    val ctx = new Context(new JavaCompiler())
    val builder = Context.builder

    generateHeader()

    builder append "@ComponentType\n "
    builder append "public class K" + Context.firstToUpper(cfg.getName) + "{//The Kevoree component wraps the whole ThingML configuration " + cfg.getName + "\n"


    builder.append("//Things\n");
    cfg.allInstances().foreach { i =>
      builder.append("private " + Context.firstToUpper(i.getType().getName()) + " " + ctx.getInstanceName(i) + ";\n");
    }

    builder append "//Output ports (dangling ports in the ThingML configuration)\n"
    cfg.danglingPorts().foreach { case (i, ports) =>
      var self = i.getType
      ports.filter { p => !(p.getAnnotations.find { a => a.getName == "internal"}.isDefined)}.filter { p => p.getSends.size > 0}
        .foreach { p =>
        builder append "@Output\n"
        builder append "private org.kevoree.api.Port " + i.getName + "_" + p.getName + "Port_out;\n"
      }
    }

    //forwards incoming Kevoree messages to ThingML
    cfg.danglingPorts().foreach { case (i, ports) =>
      ports.foreach { p =>
        if (p.getReceives.size() > 0) {
          builder append "@Input\n"
          builder append "public void " + i.getName + "_" + p.getName + "Port(String string) {\n"
          builder append "final JsonObject json = JsonObject.readFrom(string);\n"
          builder append "if (json.get(\"port\").asString().equals(\"" + p.getName + "_c\")) {\n" //might be a redundant check
          var id = 0
          p.getReceives.foreach { m =>
            if (id > 0)
              builder append "else "
            builder append "if (json.get(\"message\").asString().equals(\"" + m.getName + "\")) {\n"
            builder append "final Event msg = " + ctx.getInstanceName(i) + ".get" + Context.firstToUpper(m.getName) + "Type().instantiate(" + ctx.getInstanceName(i) + ".get" + Context.firstToUpper(p.getName) + "_port()"
            m.getParameters.foreach { pa =>
              builder append ", (" + pa.getType.annotation("java_type").head + ") json.get(\"" + pa.getName + "\")"
              pa.getType.annotation("java_type").head match {
                case "int" => builder append ".asInt()"
                case "short" => builder append ".asInt()"
                case "long" => builder append ".asLong()"
                case "double" => builder append ".asDouble()"
                case "float" => builder append ".asFloat()"
                case "char" => builder append ".asString().charAt(0)"
                case "String" => builder append ".asString()"
                case "byte" => builder append ".asString().getBytes[0]"
                case "boolean" => builder append ".asBoolean()"
              }
            }
            builder append ");\n"
            builder append ctx.getInstanceName(i) + ".receive(msg, " + ctx.getInstanceName(i) + ".get" + Context.firstToUpper(p.getName) + "_port());\n"
            builder append "}\n"
            id = id + 1
          }
          builder append "}\n"
          builder append "}\n\n"
        }
      }<commit_msg>fix HEADS-project/training#50<commit_after>/**
 * Copyright (C) 2014 SINTEF <<EMAIL>>
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * This code generator targets the Kevoree Framework.
 * Formerly wrapping the Scala code generated from ThingML (by <NAME> <<EMAIL>>),
 * this new compiler now wraps the plain Java code generated from ThingML
 * @author: <NAME> <<EMAIL>>
 */
package org.thingml.javagenerator.kevoree

import java.io._
import java.nio.file.{StandardCopyOption, FileSystems, Files}

import org.sintef.thingml._
import org.thingml.compilers.helpers.JavaHelper
import org.thingml.compilers.main.JavaMainGenerator
import org.thingml.compilers.{JavaCompiler, Context}
import org.thingml.javagenerator.JavaGenerator._
import org.thingml.javagenerator.extension.Context

import scala.collection.JavaConversions._
import scala.io.Source

object Context {

  val ctx: Context = new Context(new JavaCompiler(), "match", "requires", "type", "abstract", "do", "finally", "import", "object", "throw", "case", "else", "for", "lazy", "override", "return", "trait", "catch", "extends", "forSome", "match", "package", "sealed", "try", "while", "class", "false", "if", "new", "private", "super", "true", "final", "null", "protected", "this", "_", ":", "=", "=>", "<-", "<:", "<%", ">:", "#", "@")

  val builder = new java.lang.StringBuilder()

  var thing: Thing = _
  var pack: String = _
  var port_name: String = _
  var file_name: String = _
  var wrapper_name: String = _


  val keywords = scala.List("abstract", "continue", "for", "new", "switch", "assert", "default", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "volatile", "float", "native", "super", "while")

  def protectJavaKeyword(value: String): String = {
    if (keywords.exists(p => p.equals(value))) {
      return "_" + value + "_"
    }
    else {
      return value
    }
  }

  def firstToUpper(value: String): String = {
    return value.capitalize
  }

  def init {
    builder.delete(0, builder.length())
    thing = null
    pack = null
    port_name = null
    file_name = null
    wrapper_name = null
  }
}

object KevoreeGenerator {
  //implicit def kevoreeGeneratorAspect(self: Thing): ThingKevoreeGenerator = ThingKevoreeGenerator(self)

  /*
   * 
   */
  def compileAndRun(cfg: Configuration, model: ThingMLModel, outputFolder : String) {
    val rootDir = if (outputFolder == null)System.getProperty("java.io.tmpdir") + "/ThingML_temp/" + cfg.getName else outputFolder
    val outputDir = rootDir + "/src/main/java/org/thingml/generated/kevoree"

    val outputDirFile = new File(outputDir)
    outputDirFile.mkdirs

    Context.init
    Context.pack = "org.thingml.generated"
    val ctx = new Context(new JavaCompiler())
    val builder = Context.builder

    generateHeader()

    builder append "@ComponentType\n "
    builder append "public class K" + Context.firstToUpper(cfg.getName) + "{//The Kevoree component wraps the whole ThingML configuration " + cfg.getName + "\n"


    builder.append("//Things\n");
    cfg.allInstances().foreach { i =>
      builder.append("private " + Context.firstToUpper(i.getType().getName()) + " " + ctx.getInstanceName(i) + ";\n");
    }

    builder append "//Output ports (dangling ports in the ThingML configuration)\n"
    cfg.danglingPorts().foreach { case (i, ports) =>
      var self = i.getType
      ports.filter { p => !(p.getAnnotations.find { a => a.getName == "internal"}.isDefined)}.filter { p => p.getSends.size > 0}
        .foreach { p =>
        builder append "@Output\n"
        builder append "private org.kevoree.api.Port " + i.getName + "_" + p.getName + "Port_out;\n"
      }
    }

    //forwards incoming Kevoree messages to ThingML
    cfg.danglingPorts().foreach { case (i, ports) =>
      ports.foreach { p =>
        if (p.getReceives.size() > 0) {
          builder append "@Input\n"
          builder append "public void " + i.getName + "_" + p.getName + "Port(String string) {\n"
          builder append "final JsonObject json = JsonObject.readFrom(string);\n"
          builder append "//if (json.get(\"port\").asString().equals(\"" + p.getName + "_c\")) {\n" //might be a redundant check
          var id = 0
          p.getReceives.foreach { m =>
            if (id > 0)
              builder append "else "
            builder append "if (json.get(\"message\").asString().equals(\"" + m.getName + "\")) {\n"
            builder append "final Event msg = " + ctx.getInstanceName(i) + ".get" + Context.firstToUpper(m.getName) + "Type().instantiate(" + ctx.getInstanceName(i) + ".get" + Context.firstToUpper(p.getName) + "_port()"
            m.getParameters.foreach { pa =>
              builder append ", (" + pa.getType.annotation("java_type").head + ") json.get(\"" + pa.getName + "\")"
              pa.getType.annotation("java_type").head match {
                case "int" => builder append ".asInt()"
                case "short" => builder append ".asInt()"
                case "long" => builder append ".asLong()"
                case "double" => builder append ".asDouble()"
                case "float" => builder append ".asFloat()"
                case "char" => builder append ".asString().charAt(0)"
                case "String" => builder append ".asString()"
                case "byte" => builder append ".asString().getBytes[0]"
                case "boolean" => builder append ".asBoolean()"
              }
            }
            builder append ");\n"
            builder append ctx.getInstanceName(i) + ".receive(msg, " + ctx.getInstanceName(i) + ".get" + Context.firstToUpper(p.getName) + "_port());\n"
            builder append "}\n"
            id = id + 1
          }
          builder append "//}\n"
          builder append "}\n\n"
        }
      }
{'fraction_non_alphanumeric': 0.1590631675312786, 'fraction_numerical': 0.0033567287152883735, 'mean_word_length': 3.016237745098039, 'pattern_counts': {'":': 2, '<': 25, '<?xml version=': 0, '>': 69, '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': '6207624', 'n_tokens_mistral': 4047, 'n_tokens_neox': 3891, 'n_words': 1099}