OSDN Git Service

CsvInput.scala change to The reflection.
[open-pdm-light/PartList.git] / PartsList / PartsList / app / controllers / services / CsvInput.scala
index 54f40ab..18c9950 100644 (file)
@@ -6,30 +6,46 @@ import play.api.libs.Files.TemporaryFile
 import models.services._
 import beans._
 import org.squeryl.PrimitiveTypeMode._
+import scala.reflect.runtime.{universe => ru}
 
 case class CsvInput() {
-  def importCsvFile(atach:FilePart[TemporaryFile]) = {
+  def getTypeTag[T: ru.TypeTag](obj: T) = ru.typeTag[T]
+  
+  def importCsvFile(atach:FilePart[TemporaryFile], clsName: String) = {
       val file = atach.ref.file
       val fis = new FileInputStream(file)
       val src = Source.fromInputStream(fis)
       val itr = src.getLines
       inTransaction {
+        val runtimeMirror =ru.runtimeMirror(Thread.currentThread.getContextClassLoader)
+        val classSymbol = runtimeMirror.staticClass(clsName).toType
+        val cm = Class.forName(clsName).newInstance()
+        val im = runtimeMirror.reflect(cm)
         for(it <- itr) {
+          var i:Int=0
           if(it!="") {
-            for(f<-classOf[PartsListBean].getDeclaredFields())
-            {
-            println("feildName = " +f.getName())
-            println("feilType = " +f.getType().getName())              
+            for(f<-Class.forName(clsName).getDeclaredFields()){
+               classSymbol.declarations
+              val fieldSymbol = classSymbol.declaration(ru.newTermName(f.getName())).asTerm
+              val fm =im.reflectField(fieldSymbol)
+              fm.set(
+                        f.getType().getName() match {
+                               case "long" =>
+                                       it.split(",").apply(i) match{
+                                               case "" => 0
+                                               case _ => it.split(",").apply(i).toInt
+                                       }
+                               case _ =>
+                                       it.split(",").apply(i) match{
+                                               case "" => " "
+                                               case _ => it.split(",").apply(i)
+                                       }
+                     }
+                )
+              i += 1
+              }
+            PartRelationManager().insert(cm, null, 0)
             }
-            val parent = it.split(",").apply(0)
-            val child = it.split(",").apply(1)
-            var quantity = 0L
-            if(it.split(",").apply(2)!="") quantity = it.split(",").apply(2).toInt
-            var relationKey = ""
-            if(it.split(",").apply(3)!="") relationKey = it.split(",").apply(3)
-            val data = PartsListBean(parent, child, quantity, relationKey)
-            PartRelationManager().insert(data, null, 0)
-           }
           }
        }
   }