Скрипт Moqui с внешними зависимостями - PullRequest
0 голосов
/ 05 октября 2018

Я пишу небольшой компонент, который должен извлечь данные из таблицы Google BigQuery, чтобы затем сохранить их как участник.

Итак, я создал новый компонент, для которого у меня есть служба с одним действием, которое нужно вызвать.скрипт и скрипт.В компоненте я также добавил build.gradle, чтобы добавить зависимость к google bigquery.

Проблема в том, что когда я пытаюсь импортировать библиотеки bigquery из скрипта, он говорит, что не может их найти.

component / mycomponent / {данные, сущность, экран, скрипт, сервис}

mycomponent / component.xml:

<?xml version="1.0" encoding="UTF-8"?>
<component xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://moqui.org/xsd/moqui-conf-2.1.xsd"
    name="mycomponent" version="${moqui_version}">
</component>

mycomponent / build.gradle:

apply plugin: 'groovy'

sourceCompatibility = '1.8'
def moquiDir = file(projectDir.absolutePath + '/../../..')
def frameworkDir = file(moquiDir.absolutePath + '/framework')

// maybe in the future: repositories { mavenCentral() }
repositories {
    flatDir name: 'localLib', dirs: frameworkDir.absolutePath + '/lib'
    jcenter()
}

dependencies {
    compile project(':framework')
    testCompile project(':framework').configurations.testCompile.allDependencies
    compile 'com.google.cloud:google-cloud-bigquery:1.40.0'
}

// by default the Java plugin runs test on build, change to not do that (only run test if explicit task)
// no longer workds as of gradle 4.8 or possibly earlier, use clear() instead: check.dependsOn.remove(test)
check.dependsOn.clear()

test {
    dependsOn cleanTest
    dependsOn ':runtime:component:mantle-usl:test'

    systemProperty 'moqui.runtime', moquiDir.absolutePath + '/runtime'
    systemProperty 'moqui.conf', 'conf/MoquiDevConf.xml'
    systemProperty 'moqui.init.static', 'true'

    // show standard out and standard error of the test JVM(s) on the console
    testLogging.showStandardStreams = true; testLogging.showExceptions = true

    classpath += files(sourceSets.main.output.classesDirs)
    // filter out classpath entries that don't exist (gradle adds a bunch of these), or ElasticSearch JarHell will blow up
    classpath = classpath.filter { it.exists() }

    beforeTest { descriptor -> logger.lifecycle("Running test: ${descriptor}") }
}

mycomponent / services / myservice.xml:

<services xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://moqui.org/xsd/service-definition-2.1.xsd">
    <service verb="sync" noun="myservice">
        <in-parameters/>
        <out-parameters/>
        <actions>
            <script location="component://mycomponent/script/pullClientesBQ.groovy" />
        </actions>
    </service>
</services>

mycomponent / script / pullClientesBQ.groovy:

import com.google.cloud.bigquery.BigQuery
import com.google.cloud.bigquery.BigQueryOptions
import com.google.cloud.bigquery.FieldValueList
import com.google.cloud.bigquery.QueryJobConfiguration
// Script code follows.

Затем я перехожу в веб-интерфейс Tools, чтобы запустить службуи:

17: 47: 13.788 ОШИБКА 110121908-17 omiaXmlAction Ошибка при запуске скрипта groovy (org.codehaus.groovy.control.MultipleCompilationErrorsException: сбой при запуске: component___intermegaBaseClientes_script_pull_google.gov.gif.google.org.cloud.bigquery.BigQuery @ строка 1, столбец 1. import com.google.cloud.bigquery.BigQuery

Итак, как я (должным образом) могу использовать внешние библиотеки на моих компонентах?сценарии?

спасибо

1 Ответ

0 голосов
/ 06 октября 2018

Пожалуйста, смотрите здесь документацию по структуре компонентов Moqui для описания каталогов и файлов, используемых соглашением в компонентах:

https://www.moqui.org/docs/framework/Tool+and+Config+Overview#extensions-and-add-ons

Там было описание каталога 'lib', как вы получаете файлы JAR на пути к классам в компоненте Moqui.Я просто добавил некоторые дополнительные детали для поддерживаемых файлов, в том числе build.gradle с примечаниями, связанными с этим вопросом.

Короче говоря, реальный вопрос заключается в том, как получить материал в Java classpath, и это делается с помощью «классов».каталоги 'и' lib 'в каталоге компонентов Moqui.В вашем файле build.gradle чего-то не хватает, чтобы скопировать встроенный и зависящий от JAR-файла в каталог 'lib'.Вот пример того, что вы можете добавить в файл build.gradle, чтобы сделать это:

task cleanLib(type: Delete) { delete fileTree(dir: projectDir.absolutePath+'/lib', include: '*') }
clean.dependsOn cleanLib

jar {
    destinationDir = file(projectDir.absolutePath + '/lib')
    baseName = jarBaseName
}
task copyDependencies { doLast {
    copy { from (configurations.runtime - project(':framework').configurations.runtime - project(':framework').jar.archivePath)
        into file(projectDir.absolutePath + '/lib') }
} }
copyDependencies.dependsOn cleanLib
jar.dependsOn copyDependencies

Также неплохо добавить каталог 'lib' в файл .gitignore в каталоге компонентов.поэтому файлы JAR там случайно не добавляются в git.

...