Skip to content

Instantly share code, notes, and snippets.

@nirleka
Created November 13, 2019 18:00
Show Gist options
  • Save nirleka/445f48a5a5e6ecde16022f390262e51d to your computer and use it in GitHub Desktop.
Save nirleka/445f48a5a5e6ecde16022f390262e51d to your computer and use it in GitHub Desktop.
Intellij Groovy script to copy JDL Entity to clipboard.
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.awt.datatransfer.StringSelection
import java.awt.Toolkit
import java.awt.datatransfer.*
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
typeMapping = [
(~/(?i)int/) : "Integer",
(~/(?i)bigint/) : "Long",
(~/(?i)double|decimal|real/) : "Double",
(~/(?i)float/) : "Float",
(~/(?i)bigdecimal/) : "BigDecimal",
(~/(?i)boolean/) : "Boolean",
(~/(?i)datetime|timestamp/) : "ZonedDateTime",
(~/(?i)date/) : "LocalDate",
(~/(?i)uuid/) : "UUID",
(~/(?i)duration/) : "Duration",
(~/(?i)blob/) : "Blob",
(~/(?i)anyblob/) : "AnyBlob",
(~/(?i)imageblob/) : "ImageBlob",
(~/(?i)textblob/) : "TextBlob",
(~/(?i)instant/) : "Instant",
(~/(?i)/) : "String"
]
jdl = ""
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
SELECTION.filter { it instanceof DasTable }.each { generate(it) }
clipboard.setContents(new StringSelection(jdl), null)
def generate(table) {
def className = javaName(table.getName(), true)
def fields = calcFields(table)
jdl += generateRow(className, fields)
}
def generateRow(className, fields) {
row = "\n";
row += "\n"
row += "entity $className {\n"
fields.each() {
if (it.annos != "") row += " ${it.annos}\n"
row += " ${it.name} ${it.type}\n"
}
row += "}"
row += "\n"
return row;
}
def calcFields(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 : javaName(col.getName(), false),
type : typeStr,
annos: ""]]
}
}
def javaName(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]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment