Unable to run OOPS groovy with some abstraction

Answered

Hello,

I am unable to run some basic groovy code with abstraction. I have read thru this link "https://blog.jetbrains.com/datagrip/2018/02/13/generate-pojos/" and auto generated pojos and rest controllers from Data Grip. On DataGrip I right click, hit "Scripted Extensions" and select a Groovy file. If the file is written exactly as "Groovy Pojos.groovy" (see in link) then it works. If I want to use some basic abstraction and designs around reusability it fails to work. Cant even get to import classes in Groovy. 

Simple code snippet of what I tried 

class abstract AGenerate {
abstract def getPackageName() ;
abstract def getFileSuffix() ;
abstract def generateClassFiles()
abstract def generate(output, className, fields) ;
def typeMapping = [
(~/(?i)int/) : "Integer",
(~/(?i)bigint/) : "Long",
(~/(?i)float/): "Double", : "Float",
(~/(?i)double|decimal|real/) : "Double",
(~/(?i)datetime|timestamp/) : "java.sql.Timestamp",
(~/(?i)date/) : "java.sql.Date",
(~/(?i)time/) : "java.sql.Time",
(~/(?i)/) : "String"
]

...

package com.squats.autogenerate ;
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generateFolderFromTable(it, dir) }
}
class GenerateEntityClass extends AGenerate {
def getFileSuffix() {
return "Entity.java"
}
def getPackageName() {
return "com.sample;" ;
}
...
Notice I have defined a super class AGenerate and then child classes AGenerateEntityClass, I get a error when try to run AutoGenerate at the import line itself
 
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.squats.autogenerate.GenerateEntityClass
def GenerateEntityClass entityClass = newGenerateEntityClass();

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instance of DasTable && it.getKind() == ObjectKind.TABLE }.each { entityClass.generateFolderFromTable(it, dir) }
}

I get a error 

12:06 AM AutoGenerate.groovy: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script24.groovy: 4: unable to resolve class com.squats.autogenerate.GenerateEntityClass
@ line 4, column 1.
import com.squats.autogenerate.GenerateEntityClass;

What am I missing here? Doesnt this run with OOPS?

3 comments
Comment actions Permalink

could you please share full code of your script?

0
Comment actions Permalink

AGenerate (abstract class)

package com.mycompany.autogenerate ;

import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil


class absract AGenerate {
abstract def getPackageName() ;
abstract def getFileSuffix() ;

abstract def generateClassFiles()

abstract def generate(output, className, fields) ;

def typeMapping = [
(~/(?i)int/) : "Integer",
(~/(?i)bigint/) : "Long",
(~/(?i)float/): "Double", : "Float",
(~/(?i)double|decimal|real/) : "Double",
(~/(?i)datetime|timestamp/) : "java.sql.Timestamp",
(~/(?i)date/) : "java.sql.Date",
(~/(?i)time/) : "java.sql.Time",
(~/(?i)/) : "String"
]

def generateFolderFromTable(table, dir) {
def className = generateJavaFileName(table.getName(), true)
def fields = calcFields(table)
new File(dir, className + getFileSuffix()).withPrintWriter { out -> generate(out, className, fields) }
}

def extractClassFieldsFromTableColumns(table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.getDataType().getSpecification())
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : generateJavaFileName(col.getName(), false),
type : typeStr,
annos: "",
colName: col.getName(),
primary: DasUtil.isPrimary(col),
autoGenerated: DasUtil.isAutoGenerated(col),
foreign: DasUtil.isForeign(col)
]]
}

def generateJavaFileName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}


def String tableColumnUnderscoreToJavaCamelCase(String underscore){
if(!underscore || underscore.isAllWhitespace()){
return ''
}
return underscore.replaceAll(/_\w/){ it[1].toUpperCase() }
}

}

GenerateEntityClass extends AGenerate

package com.mycompany.autogenerate ;

import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

class GenerateEntityClass extends AGenerate {

def getFileSuffix() {
return "Entity.java"
}

def getPackageName {
return "com.sample;" ;
}

def generateClassFiles(out, className, fields, tableName) {

out.println "package $packageName"
out.println ""
out.println ""
out.println "import javax.persistence.*;"
out.println ""
out.println "@Entity"
out.println "@Table(name=\"${tableName}\")"
out.println "public class ${tableColumnUnderscoreToJavaCamelCase(className)}Entity extends BaseEntity {"
out.println ""
fields.each() {
if (it.annos != "") out.println " ${it.annos}"
out.println ""
if (it.primary) out.println " @Id"
if (it.autoGenerated) out.println " @GeneratedValue(strategy = GenerationType.IDENTITY)"
if (it.foreign) {
//TODO: Identify the target/ reference Entity using the FK details
// and specify Entity reference instead of FK column name
// also specify many to one annotation
out.println " @Column(name=\"${it.colName}\")"
out.println " private ${it.type} ${tableColumnUnderscoreToJavaCamelCase(it.name)};"
} else {
out.println " @Column(name=\"${it.colName}\")"
out.println " private ${it.type} ${tableColumnUnderscoreToJavaCamelCase(it.name)};"
}
}
out.println ""
fields.each() {
out.println ""
out.println " public ${it.type} get${tableColumnUnderscoreToJavaCamelCase(it.name.capitalize())}() {"
out.println " return this.${tableColumnUnderscoreToJavaCamelCase(it.name)};"
out.println " }"
out.println ""
out.println " public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
out.println " this.${tableColumnUnderscoreToJavaCamelCase(it.name)} = ${tableColumnUnderscoreToJavaCamelCase(it.name)};"
out.println " }"
}
out.println "}"

}

}

AutoGenerate I call from DataGrip

 

import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind

import com.mycompany.autogenerate.GenerateEntityClass

def GenerateEntityClass entityClass = new GenerateEntityClass();
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { entityClass.generateFolderFromTable(it, dir) }
}
0
Comment actions Permalink

Hello Jsiddharth,
Unfortunately you need to place all classes in one file
I found a typo in your script `class absract` should be `abstract class`
These scripts can be quite complicated. It's better to use an editor that'll help you to find errors e.g. IntelliJ IDEA Community, it's free

0

Please sign in to leave a comment.