Kotlin Code using org.objectweb.asm library
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.Opcodes.*
fun main(args: Array<String>) {
val classWriter = ClassWriter(ClassWriter.COMPUTE_MAXS)
classWriter.visit(
V1_8,
ACC_PUBLIC,
"com/github/patrick/learnasm/build/HelloWorld",
null,
"java/lang/Object",
null
)
val methodVisitor = classWriter.visitMethod(
ACC_PUBLIC + ACC_STATIC,
"main",
"([Ljava/lang/String;)V",
null,
null
)
methodVisitor.visitFieldInsn(
GETSTATIC,
"java/lang/System",
"out",
"Ljava/io/PrintStream;"
)
methodVisitor.visitLdcInsn(
"Hello World!"
)
methodVisitor.visitMethodInsn(
INVOKEVIRTUAL,
"java/io/PrintStream",
"println",
"(Ljava/lang/String;)V",
false
)
methodVisitor.visitInsn(
RETURN
)
methodVisitor.visitMaxs(
0,
0
)
methodVisitor.visitEnd()
val bytes = classWriter.toByteArray()
val clazz = defineClass(
"com.github.patrick.learnasm.build.HelloWorld",
bytes,
0,
bytes.count()
)
clazz.getDeclaredMethod("main", Array<String>::class.java).invoke(null, null)
}
I am trying to learn asm, and I'm curious whether creating a method with named parameter is possible.
For example in this case, the created class has no parameter name (defaults to var0 in decompiler), and I wish I could save parameter names like "args". Would it be possible?
Found an answer by looking into compiled class (by including debugging information)
The simple way is to just mock the compiled class
All I had to do is put some label on it, and visit local variable with name.
methodVisitor = classWriter.visitMethod(
Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC,
"main",
"([Ljava/lang/String;)V",
null,
null
)
methodVisitor.visitParameterAnnotation(
0,
"Lorg.jetbrains.annotations.NotNull;",
false
)
val start = Label()
methodVisitor.visitLabel(start)
methodVisitor.visitFieldInsn(
Opcodes.GETSTATIC,
"java/lang/System",
"out",
"Ljava/io/PrintStream;"
)
methodVisitor.visitLdcInsn("Hello World!")
methodVisitor.visitMethodInsn(
Opcodes.INVOKEVIRTUAL,
"java/io/PrintStream",
"println",
"(Ljava/lang/String;)V",
false
)
methodVisitor.visitInsn(Opcodes.RETURN)
val end = Label()
methodVisitor.visitLabel(end)
methodVisitor.visitLocalVariable(
"args",
"[Ljava/lang/String;",
null,
start,
end,
0
)
methodVisitor.visitMaxs(0, 0)
methodVisitor.visitEnd()
Related
I have dataframe , wanted to convert into JSON ARRAY Please find the example below
Dataframe
+------------+--------------------+----------+----------------+------------------+--------------
| Name| id|request_id|create_timestamp|deadline_timestamp|
+------------+--------------------+----------+----------------+------------------+--------------
| Freeform|59bbe3ad-f487-44| htvjiwmfe| 1589155200000| 1591272659556
| D23|59bbe3ad-f487-44| htvjiwmfe| 1589155200000| 1591272659556
| Stores|59bbe3ad-f487-44| htvjiwmfe| 1589155200000| 1591272659556
|VacationClub|59bbe3ad-f487-44| htvjiwmfe| 1589155200000| 1591272659556
Wanted in Json Like below:
[
{
"testname":"xyz",
"systemResponse":[
{
"name":"FGH",
"id":"59bbe3ad-f487-44",
"request_id":1590791280,
"create_timestamp":1590799280
},
{
"name":"FGH",
"id":"59bbe3ad-f487-44",
"request_id":1590791280,
"create_timestamp":1590799280,
}
]
}
]
You can define 2 beans
Create Array from the 1st DF as Array of inner Beans
Define a parent bean with testname and requestDetailArray as Array
Please also find code inline comments
object DataToJsonArray {
def main(args: Array[String]): Unit = {
val spark = Constant.getSparkSess
import spark.implicits._
//Load you dataframe
val requestDetailArray = List(
("Freeform", "59bbe3ad-f487-44", "htvjiwmfe", "1589155200000", "1591272659556"),
("D23", "59bbe3ad-f487-44", "htvjiwmfe", "1589155200000", "1591272659556"),
("Stores", "59bbe3ad-f487-44", "htvjiwmfe", "1589155200000", "1591272659556"),
("VacationClub", "59bbe3ad-f487-44", "htvjiwmfe", "1589155200000", "1591272659556")
).toDF
//Map your Dataframe to RequestDetails bean
.map(row => RequestDetails(row.getString(0), row.getString(1), row.getString(2), row.getString(3), row.getString(4)))
//Collect it as Array
.collect()
//Create another data frme with List[BaseClass] and set the (testname,Array[RequestDetails])
List(BaseClass("xyz", requestDetailArray)).toDF()
.write
//Output your Dataframe as JSON
.json("/json/output/path")
}
}
case class RequestDetails(Name: String, id: String, request_id: String, create_timestamp: String, deadline_timestamp: String)
case class BaseClass(testname: String = "xyz", systemResponse: Array[RequestDetails])
Check below code.
import org.apache.spark.sql.functions._
df.withColumn("systemResponse",
array(
struct("id","request_id","create_timestamp","deadline_timestamp").as("data")
)
)
.select("systemResponse")
.toJSON
.select(col("value").as("json_data"))
.show(false)
+-----------------------------------------------------------------------------------------------------------------------------------------------+
|json_data |
+-----------------------------------------------------------------------------------------------------------------------------------------------+
|{"systemResponse":[{"id":"59bbe3ad-f487-44","request_id":"htvjiwmfe","create_timestamp":"1589155200000","deadline_timestamp":"1591272659556"}]}|
|{"systemResponse":[{"id":"59bbe3ad-f487-44","request_id":"htvjiwmfe","create_timestamp":"1589155200000","deadline_timestamp":"1591272659556"}]}|
|{"systemResponse":[{"id":"59bbe3ad-f487-44","request_id":"htvjiwmfe","create_timestamp":"1589155200000","deadline_timestamp":"1591272659556"}]}|
|{"systemResponse":[{"id":"59bbe3ad-f487-44","request_id":"htvjiwmfe","create_timestamp":"1589155200000","deadline_timestamp":"1591272659556"}]}|
+-----------------------------------------------------------------------------------------------------------------------------------------------+
Updated
scala> :paste
// Entering paste mode (ctrl-D to finish)
df.withColumn("systemResponse",
array(
struct("id","request_id","create_timestamp","deadline_timestamp").as("data")
)
)
.withColumn("testname",lit("xyz"))
.select("testname","systemResponse")
.toJSON
.select(col("value").as("json_data"))
.show(false)
// Exiting paste mode, now interpreting.
+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
|json_data |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
|{"testname":"xyz","systemResponse":[{"id":"59bbe3ad-f487-44","request_id":"htvjiwmfe","create_timestamp":"1589155200000","deadline_timestamp":"1591272659556"}]}|
|{"testname":"xyz","systemResponse":[{"id":"59bbe3ad-f487-44","request_id":"htvjiwmfe","create_timestamp":"1589155200000","deadline_timestamp":"1591272659556"}]}|
|{"testname":"xyz","systemResponse":[{"id":"59bbe3ad-f487-44","request_id":"htvjiwmfe","create_timestamp":"1589155200000","deadline_timestamp":"1591272659556"}]}|
|{"testname":"xyz","systemResponse":[{"id":"59bbe3ad-f487-44","request_id":"htvjiwmfe","create_timestamp":"1589155200000","deadline_timestamp":"1591272659556"}]}|
+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
New to CORBA but could establish remote method invoking from a client to server. When using interceptors and try to encrypt parameters for the remote method, it throws below
Failed to initialise ORB: org.omg.CORBA.NO_RESOURCES: vmcid: OMG minor code: 1 completed: No org.omg.CORBA.NO_RESOURCES: vmcid: OMG minor code: 1completed: No at com.sun.corba.se.impl.logging.OMGSystemException.piOperationNotSupported1(Unknown Source)
at com.sun.corba.se.impl.logging.OMGSystemException.piOperationNotSupported1(Unknown Source)
at com.sun.corba.se.impl.interceptors.ClientRequestInfoImpl.arguments(Unknown Source)
at orb.CustomClientInterceptor.send_request(CustomClientInterceptor.java:23)
From Interceptors I'm trying to access arguments and encrypt them like below.
public void send_request( ClientRequestInfo ri )
{
System.out.println( ri.arguments() );
System.out.println( "Arguments.." );
logger( ri, "send_request" );
}
But cannot even access them, it throws above error. Intercepting methods are calling fine. Could you guide me with some code or a link.
Thanks in Advance
I found the answer and if someone hits this in future..
We cannot manipulate parameters in interceptors unless the call to CORBA object is either DII or DSI call. So first you need to make a call in either of these. I did it via DII. code is as follows.
//-ORBInitialPort 1050 -ORBInitialHost localhost
Properties p = new Properties();
p.put("org.omg.PortableInterceptor.ORBInitializerClass.orb.InterceptorORBInitializer", "");
//ORB orb = ORB.init(args, p);
String[] orbArgs = { "-ORBInitialHost", "localhost", "-ORBInitialPort", "1050" };
//NO_NEED ORB orb = ORB.init( orbArgs, null );
orb = ORB.init(orbArgs, p);
//objRef = orb.resolve_initial_references( "NameService" );
//ncRef = NamingContextExtHelper.narrow( objRef );
//DII Additional configs
org.omg.CORBA.Object ncRef = orb.resolve_initial_references ("NameService");
NamingContext nc = NamingContextHelper.narrow (ncRef);
NameComponent nComp = new NameComponent ("ABC", "");
NameComponent [] path = {nComp};
objRef = nc.resolve (path);
Then do the DII call, I have some mixed code here but you will understand what to do
NVList argList = orb.create_list (valueMap.size());
for (Map.Entry<String, String> entry : valueMap.entrySet()) {
Any argument = orb.create_any ();
argument.insert_string (entry.getValue());
argList.add_value (entry.getKey().toLowerCase(), argument, org.omg.CORBA.ARG_IN.value);
}
//Result
Any result = orb.create_any ();
result.insert_string( null );
NamedValue resultVal = orb.create_named_value ("result", result, org.omg.CORBA.ARG_OUT.value);
//Invoking Method
Request thisReq = objRef._create_request (null, methodName, argList, resultVal);
thisReq.invoke ();
//Extract Result
result = thisReq.result().value ();
Now from the interceptors you will need to filter the DII call only and then access the parameters like below.
public void send_request( ClientRequestInfo ri )
{
if(ri.operation().equals( "processPayment" ))
{
System.out.println( "################# CLIENT SIDE ###############" );
int count = 0;
for(Parameter param : ri.arguments())
{
System.out.println( "Arg : "+count );
System.out.println( param.argument.extract_string());
param.argument.insert_string( EncryptionDecryption.encrypt( param.argument.extract_string() ) );
count++;
}
}
System.out.println( "Arguments.." );
logger( ri, "send_request" );
}
stackoverflow!
I managed to inject my dll into the game minecraft(made in java) and i did attach to the main thread so i can get classes and field.
Total code:
#include <Windows.h>
#include <jni.h>
#include <iostream>
#include <string>
#include "MCClass.h"
/*
BOOL WINAPI DllMain(
_In_ HINSTANCE hinstDLL,
_In_ DWORD fdwReason,
_In_ LPVOID lpvReserved
);
*/
typedef jint (*hJNI_GetCreatedJavaVMs )( JavaVM** vmBuf , jsize bufLen , jsize* nVMs );
hJNI_GetCreatedJavaVMs oJNI_GetCreatedJavaVMs;
HMODULE jvmHandle;
FARPROC func_JNI_GetCreatedJavaVMs;
JavaVM *jvm;
JNIEnv *jenv;
jclass Minecraft;
jclass FMLH;
jclass FMLHI;
jclass launchWrapper;
MCClass* mc = new MCClass ( );
using namespace std;
void GetAllMinecraft ( )
{
jfieldID f = jenv->GetFieldID ( Minecraft , "serverName" , "Ljava/lang/String;" );
if ( f != NULL )
{
jstring str = (jstring)jenv->GetObjectField ( Minecraft , f );
mc->serverName = (char*)jenv->GetStringUTFChars( str , 0 );
cout << mc->serverName << endl;
}
else
{
MessageBox ( NULL , "serverName is null", "ERROR" , MB_OK );
}
}
/*
void start ( )
{
MessageBox ( NULL , "Initialization has completed." , "Works" , MB_OK );
FMLH = jenv->FindClass ( "net/minecraftforge/fml/relauncher/FMLLaunchHandler" );
if ( FMLH != nullptr )
{
MessageBox ( NULL , "FMLLaunchHandler found successfully" , "OK" , MB_OK );
jfieldID f = jenv->GetStaticFieldID ( (jclass) FMLH , "INSTANCE" , "Lnet/minecraftforge/fml/relauncher/FMLLaunchHandler;" );
MessageBox ( NULL , "FMLH passed" , "OK" , MB_OK );
if ( f == nullptr )
{
MessageBox ( NULL , "FMLLaunchHandler fieldID couldn't be found successfully" , "OK" , MB_OK );
}
else
{
MessageBox ( NULL , "FMLLaunchHandler fieldID found successfully" , "OK" , MB_OK );
FMLHI = jenv->GetStaticObjectField ( (jclass) FMLH , f );
MessageBox ( NULL , "FMLHI passed" , "OK" , MB_OK );
if ( FMLHI == nullptr )
{
MessageBox ( NULL , "FMLLaunchHandler instance couldn't be found successfully" , "OK" , MB_OK );
}
else
{
MessageBox ( NULL , "FMLHI is not nullptr" , "OK" , MB_OK );
jfieldID f1 = jenv->GetFieldID ( ( jclass ) FMLHI , "classLoader" , "Lnet/minecraft/launchwrapper/LaunchClassLoader;" ); //HERE
MessageBox ( NULL , "f1 passed" , "OK" , MB_OK );
if ( f1 == nullptr )
{
MessageBox ( NULL , "classLoader fieldID couldn't be found successfully" , "OK" , MB_OK );
}
else
{
MessageBox ( NULL , "classLoader fieldID found successfully" , "OK" , MB_OK );
launchWrapper = jenv->GetObjectField ( ( jclass ) FMLHI , f1 );
MessageBox ( NULL , "launchWrapper passed" , "OK" , MB_OK );
if ( launchWrapper == nullptr )
{
MessageBox ( NULL , "classLoader class couldn't be found successfully" , "OK" , MB_OK );
}
else
{
MessageBox ( NULL , "classLoader class found successfully" , "OK" , MB_OK );
jmethodID mmid = jenv->GetMethodID ( ( jclass ) launchWrapper , "findClass" , "(Ljava/lang/String;)Ljava/lang/Class;" );
MessageBox ( NULL , "findClass passed" , "OK" , MB_OK );
if ( mmid != NULL )
{
Minecraft = ( jclass ) jenv->CallNonvirtualObjectMethod ( launchWrapper , ( jclass ) launchWrapper , mmid , "net.minecraft.client.Minecraft" );
MessageBox ( NULL , "Minecraft class found successfully" , "OK" , MB_OK );
// GetAllMinecraft ( );
}
else
{
MessageBox ( NULL , "findClass method ID couldn't be found successfully" , "OK" , MB_OK );
}
}
}
}
}
}
else
{
MessageBox ( NULL , "FMLLaunchHandler couldn't be found successfully" , "OK" , MB_OK );
}
}
*/
const char* GetObjName ( jobject cls )
{
jclass clsClazz = jenv->GetObjectClass ( cls );
jmethodID methodId = jenv->GetMethodID ( clsClazz , "getName" , "()Ljava/lang/String;" );
jstring className = ( jstring ) jenv->CallObjectMethod ( cls , methodId );
return jenv->GetStringUTFChars ( className , NULL );
jenv->DeleteLocalRef ( clsClazz );
}
void start ( )
{
jclass preMC = jenv->FindClass ( "net/minecraftforge/fml/relauncher/FMLLaunchHandler" );
if ( preMC != NULL )
{
/*Section intercept custom findClassStart*/
jfieldID iID = jenv->GetStaticFieldID ( preMC , "INSTANCE" , "Lnet/minecraftforge/fml/relauncher/FMLLaunchHandler;" );
cout << "IID: " << iID << endl;
jobject instance = jenv->GetStaticObjectField ( preMC , iID );
cout << "INSTANCE: " << instance << endl;
jfieldID lID = jenv->GetFieldID ( preMC , "classLoader" , "Lnet/minecraft/launchwrapper/LaunchClassLoader;" );
cout << "LID: " << lID << endl;
jobject classLoader = jenv->GetObjectField ( instance , lID );
cout << "classLoader: " << classLoader << endl;
jmethodID fid = jenv->GetMethodID ( jenv->GetObjectClass(classLoader) , "findClass" , "(Ljava/lang/String;)Ljava/lang/Class;" );
cout << "FID: " << fid << endl;
jobject a = jenv->CallNonvirtualObjectMethod ( classLoader , jenv->GetObjectClass(classLoader), fid , "net/minecraft/client/Minecraft" );
preMC = ( jclass ) a;
cout << "preMC: " << preMC << endl;
/*Section intercept custom findClassEND*/
/*Section getDisplayWidthStart*/
jfieldID mid = jenv->GetStaticFieldID ( jenv->GetObjectClass(preMC) , "theMinecraft" , "Lnet/minecraft/client/Minecraft;" );
cout << "MID: " << mid << endl;
jobject MC = jenv->GetStaticObjectField ( jenv->GetObjectClass(preMC) , mid );
cout << "MC: " << MC << endl;
jfieldID mid2 = jenv->GetFieldID ( jenv->GetObjectClass(MC) , "displayWidth" , "I" );
cout << "MID2: " << mid2 << endl;
int displayWidth = jenv->GetIntField ( MC , mid2 );
cout << "DisplayWidth: " << displayWidth << endl;
/*Section getDisplayWidthEND*/
}
}
void init ( )
{
jvmHandle = GetModuleHandleA ( "jvm.dll" );
func_JNI_GetCreatedJavaVMs = GetProcAddress ( jvmHandle , "JNI_GetCreatedJavaVMs" );
oJNI_GetCreatedJavaVMs = ( hJNI_GetCreatedJavaVMs ) func_JNI_GetCreatedJavaVMs;
jint returnOF = oJNI_GetCreatedJavaVMs ( &jvm , 1 , NULL );
jint returnOf1 = jvm->AttachCurrentThread ( ( void ** ) &jenv , NULL );
if ( jenv != nullptr )
{
start ( );
}
if ( jenv->ExceptionCheck ( ) )
{
jenv->ExceptionDescribe ( );
}
jvm->DetachCurrentThread ( );
}
BOOL WINAPI DllMain ( HINSTANCE hinstDLL , DWORD fdwReason , LPVOID lpvReserved )
{
switch ( fdwReason )
{
case DLL_PROCESS_ATTACH:
init ( );
//case DLL_PROCESS_DETACH:
//case DLL_THREAD_ATTACH:
//case DLL_THREAD_DETACH:
}
}
NOTE: this game uses a custom class launcher, + i use the forge api on it.
I looked at the cout debugs and looks like the cout's stop at :
cout << "FID: " << fid << endl;
After that no more cout's get called. then the game stops responding.
Thank you for reading and hopefully i was descriptive enough.
EDIT: The whole code stops the game minecraft from responding after some time or instantly idk its random.
I use standard injection with extreme injector for now.
This is some information i got from debugging:
IID: 0000000024D1FE80
INSTANCE: 00000000191813F8
LID: 0000000000000032
classLoader: 0000000019181400
FID: 0000000016176C90
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000002d7688e, pid=6048, tid=0x0000000000001648
#
# JRE version: Java(TM) SE Runtime Environment (8.0_92-b14) (build 1.8.0_92-b14)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.92-b14 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# J 3576 C2 net.minecraft.launchwrapper.LaunchClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class; (695 bytes) # 0x0000000002d7688e [0x0000000002d76820+0x6e]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\Users\Balen\Desktop\ForgeMod\eclipse\hs_err_pid6048.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
#
AL lib: (EE) alc_cleanup: 1 device not closed
:runClient FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':runClient'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_92\bin\java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 8 mins 50.128 secs
Edit: This is to better explain everything:
I inject this dll into the game after everything in the game has initialized.
The games uses a custom class loader(LaunchClassLoader) i try to retrieve a instance of that, to do so i get the FMLLaunchHandler there i get a instanceof FMLLaunchHandler then from that instance i get classLoader and from that instance i use the classLoaders findClass to get the class.
Someone told me that i need to get a initialized version of a class to use non static methods or get non static fields.
I use a injector called extreme injector for now and use standard injection which is loadlibrary.
I also do not create my own vm, i attach to the running minecraft vm and get the env from that thru a dll and init function handles the attaching.
Thanks for reading, have nice day.
assume part of my code is like as:-
where doc is List[Document] that contains stu_name and roll_number
sometimes stu_name and roll_name may be null.
I used Try to avoid null Pointer exception in first two lines.
but why I m getting again Null Pointer exception in "val myRow".
val name= Try {Option.apply(doc.getFieldValue("stu_name"))}.getOrElse(null)
val rollNumber ={Option.apply(doc.getFieldValue("roll_number"))}.getOrElse(null)
val myRow = (
doc.getFieldValue("ID").asInstanceOf[Int] //can't be null
name.getOrElse(null).toString, //NullPointerException
rollNumber.getOrElse(null).asInstanceOf[Int] //NullPointerException
)
.....
.....
I m getting following error:
[2016-01-14 22:40:16,896] WARN o.a.s.s.TaskSetManager [] [akka://JobServer/user/context-supervisor/demeter] - Lost task 0.0 in stage 0.0 (TID 0, 10.29.23.136): java.lang.NullPointerException
at com.test.events.Monitoring$$anonfun$geteventTableReplicateDayFunc$1.apply(Monitoring.scala:75)
at com.test.events.Monitoring$$anonfun$geteventTableReplicateDayFunc$1.apply(Monitoring.scala:57)
at com.test.events.Monitoring$$anonfun$27.apply(Monitoring.scala:104)
at com.test.events.Monitoring$$anonfun$27.apply(Monitoring.scala:104)
I tried in console following but did not see any error:
scala> val a = Try (Option.apply("atar")).getOrElse(null)
a: Option[String] = Some(atar)
scala> a.getOrElse(null)
res16: String = atar
scala> val a = Try (Option.apply(null)).getOrElse(null)
a: Option[Null] = None
scala> a.getOrElse(null)
res17: Null = null
This is all wrong. By using getOrElse(null) you are basically removing all advantages to using an Option to begin with. Plus, generating much more complexity than needed.
You need to define what you will do if the values are null. This just keeps them as Options (None on null input):
val myRow = (
doc.getFieldValue("ID").toInt, // Fails if null
Option(doc.getFieldValue("stu_name")), // `None` if null
Option(doc.getFieldValue("roll_number")).map(_.toInt) // `None` if null
)
Or use default values:
val myRow = (
doc.getFieldValue("ID").toInt,
Option(doc.getFieldValue("stu_name")).getOrElse("default"),
Option(doc.getFieldValue("roll_number")).map(_.toInt).getOrElse(0)
)
Now, I'm writing sample for learning scala slick. I'm using some github projs and stackoverflow (Q&A)s. Below my sample code:
import scala.slick.driver.PostgresDriver.simple._
import Database.threadLocalSession
object TestApp extends App{
case class MyTable(id: Option[Int], foo: String, bar: String)
object MyTables extends Table[MyTable]("mytable") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def foo = column[String]("foo", O.NotNull)
def bar = column[String]("bar", O.NotNull)
def * = id.? ~ foo ~ bar <> (MyTable, MyTable.unapply _)
def forInsert = foo ~ bar <>
({ (f, l) => MyTable (None, f, l) }, { ep:MyTable => Some((ep.foo, ep.bar)) })
val findByID = createFinderBy(_.id)
}
implicit val session = Database.forURL("jdbc:postgresql://localhost:5432/myserver",
driver="org.postgresql.Driver",
user="myadmin",
password="myadmin")
session withTransaction {
MyTables.ddl.create
MyTables.foo ~ MyTables.bar).insert("Homer", "Simpson")
MyTables.forInsert.insertAll(
MyTable(None, "Marge", "Bouvier"),
MyTable(None, "Carl", "Carlson"),
MyTable(None, "Lenny", "Leonard")
)
}
}
EXCEPTION:
Exception in thread "main" java.lang.NoClassDefFoundError: scala/Right
at scala.slick.driver.BasicProfile$class.createQueryTemplate(BasicProfile.scala:12)
at scala.slick.driver.PostgresDriver$.createQueryTemplate(PostgresDriver.scala:69)
at scala.slick.ql.Parameters.flatMap(Parameters.scala:9)
at scala.slick.driver.BasicTableComponent$Table.createFinderBy(BasicTableComponent.scala:30)
at TestApp$MyTables$.(TestApp.scala:16)
Create table in postgresql
CREATE TABLE mytable
(
id serial primary key,
foo VARCHAR(40) not null,
bar VARCHAR(40) not null,
);
I'm using this tools and libraries:
Scala IDE - 2.10
Java version - 1.7.0_11
slick_2.10.0-M4-0.10.0-M2.jar
postgresql-9.2-1003-jdbc4.jar
Database - PostgreSQL 8.3
What's Wrong Here? Thanks in advance.