diff --git "a/data/groovy/data.json" "b/data/groovy/data.json" new file mode 100644--- /dev/null +++ "b/data/groovy/data.json" @@ -0,0 +1,100 @@ +{"size":1498,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\npackage org.codenarc.rule.braces\r\n\r\nimport org.codehaus.groovy.ast.stmt.IfStatement\r\nimport org.codenarc.rule.AbstractAstVisitor\r\nimport org.codenarc.rule.AbstractAstVisitorRule\r\nimport org.codenarc.util.AstUtil\r\n\r\n\/**\r\n * Rule that checks that if statements use braces rather than a single statement.\r\n *\r\n * @author Chris Mair\r\n *\/\r\nclass IfStatementBracesRule extends AbstractAstVisitorRule {\r\n String name = 'IfStatementBraces'\r\n int priority = 2\r\n Class astVisitorClass = IfStatementBracesAstVisitor\r\n}\r\n\r\nclass IfStatementBracesAstVisitor extends AbstractAstVisitor {\r\n @Override\r\n void visitIfElse(IfStatement ifStatement) {\r\n if (isFirstVisit(ifStatement) && !AstUtil.isBlock(ifStatement.ifBlock)) {\r\n addViolation(ifStatement, 'The if statement lacks braces')\r\n }\r\n super.visitIfElse(ifStatement)\r\n }\r\n\r\n}\r\n","avg_line_length":34.0454545455,"max_line_length":82,"alphanum_fraction":0.7269692924} +{"size":2227,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/** \n * Copyright (c) 2012, Clinton Health Access Initiative.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\npackage org.chai.memms\n\nimport i18nfields.I18nFields\n\/**\n * @author Jean Kahigiso M.\n *\n *\/\n@i18nfields.I18nFields\nclass Warranty{\n\t\n\tDate startDate\n\tBoolean sameAsSupplier = false\n\tString descriptions\n\tContact contact\n\t\n\tstatic i18nFields = [\"descriptions\"]\n\tstatic embedded = [\"contact\"]\n\t\n\tstatic constraints = {\n\t\timportFrom Contact\n\t\tstartDate nullable:false, validator:{it <= new Date()} \n\t\tdescriptions nullable: true, blank: true\n\t\tcontact nullable: true,validator:{val, obj ->\n\t\t\t if(obj.sameAsSupplier==true) return (val==null)\n\t\t\t}\n\t\tsameAsSupplier nullable: true\n\t\t\n\t}\n\t\n\tstatic mapping = {\n\t\tversion false\n\t}\n}\n","avg_line_length":36.5081967213,"max_line_length":82,"alphanum_fraction":0.741805119} +{"size":562,"ext":"groovy","lang":"Groovy","max_stars_count":4.0,"content":"package org.grails.web.servlet.mvc\n\nimport grails.artefact.Artefact\nimport grails.test.mixin.TestFor\n\nimport org.junit.Test\n\n@TestFor(ControllerInheritanceFooController)\nclass ControllerInheritanceTests {\n \/\/ test for GRAILS-6247\n @Test\n void testCallSuperMethod() {\n controller.bar()\n }\n}\n\n@Artefact('Controller')\nclass ControllerInheritanceFooBaseController {\n\n void bar() {\n println('bar in base class')\n }\n}\n\n@Artefact('Controller')\nclass ControllerInheritanceFooController extends ControllerInheritanceFooBaseController {}\n\n","avg_line_length":20.0714285714,"max_line_length":90,"alphanum_fraction":0.7526690391} +{"size":1619,"ext":"groovy","lang":"Groovy","max_stars_count":40.0,"content":"\/*\n * Copyright 2020 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage dev.nokee.fixtures\n\nimport org.gradle.api.Project\nimport org.gradle.api.Task\nimport org.gradle.api.artifacts.Configuration\n\ntrait ProjectTestFixture {\n\tabstract Project getProjectUnderTest()\n\n\tboolean hasTask(String name) {\n\t\treturn projectUnderTest.tasks.findByName(name) != null\n\t}\n\n\tboolean hasConfiguration(String name) {\n\t\treturn projectUnderTest.configurations.findByName(name) != null\n\t}\n\n\tSet getConfigurations() {\n\t\treturn projectUnderTest.configurations.findAll { !['archives', 'default'].contains(it.name) }\n\t}\n\n\tSet getTasks() {\n\t\treturn projectUnderTest.tasks.findAll { !['help', 'tasks', 'components', 'dependencies', 'dependencyInsight', 'dependentComponents', 'init', 'model', 'outgoingVariants', 'projects', 'properties', 'wrapper', 'buildEnvironment', 'nokeeModel'].contains(it.name) }\n\t}\n\n\tvoid evaluateProject(String because) {\n\t\tprojectUnderTest.evaluate()\n\t}\n\n\tpublic T one(Iterable c) {\n\t\tassert c.size() == 1\n\t\treturn c.iterator().next()\n\t}\n}\n","avg_line_length":32.38,"max_line_length":262,"alphanum_fraction":0.7399629401} +{"size":1329,"ext":"groovy","lang":"Groovy","max_stars_count":4.0,"content":"\/**\n * This class instantiates extended security objects.\n *\/\npackage org.urbancode.ucadf.core.model.ucd.security\n\nimport org.urbancode.ucadf.core.model.ucd.general.UcdObject\n\nimport com.fasterxml.jackson.annotation.JsonAlias\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties\nimport com.fasterxml.jackson.annotation.JsonProperty\n\n@JsonIgnoreProperties(ignoreUnknown = true)\nclass UcdExtendedSecurityTeam extends UcdObject {\n\t\/** The team ID. *\/\n\tString teamId\n\t\n\t\/** The team name. (Known to the UCD APIs as teamLabel. *\/\t\n\t@JsonProperty(\"teamLabel\")\n\tString teamName\n\n\t\/** The security type ID. (Known to the UCD APIs as resourceTypeId. *\/\t\n\t@JsonProperty(\"resourceTypeId\")\n\tString typeId\n\n\t\/** The security type name. (Known to the UCD APIs as resourceTypeName. *\/\t\n\t@JsonProperty(\"resourceTypeName\")\n\tString typeName\n\n\t\/** The security subtype ID. (Known to the UCD APIs as resourceRoleId. *\/\t\n\t@JsonProperty(\"resourceRoleId\")\n\tString subtypeId\n\n\t\/** The security subtype name. (Known to the UCD APIs as resourceRoleLabel. *\/\t\n\t@JsonProperty(\"resourceRoleLabel\")\n\tString subtypeName\n\t\n\t\/\/ Constructors.\t\n\tUcdExtendedSecurityTeam() {\n\t}\n\t\n\tUcdExtendedSecurityTeam(\n\t\tfinal String team,\n\t\tfinal String type,\n\t\tfinal String subtype) {\n\t\t\n\t\tthis.teamName = team\n\t\tthis.typeName = type\n\t\tthis.subtypeName = subtype\n\t}\n}\n","avg_line_length":26.0588235294,"max_line_length":80,"alphanum_fraction":0.754702784} +{"size":3687,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/**\n * Copyright 2013 BancVue, LTD\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.dreamscale.gradle.test\n\nimport org.dreamscale.gradle.GradlePluginMixin\nimport org.dreamscale.gradle.support.CommonTaskFactory\nimport org.gradle.api.Plugin\nimport org.gradle.api.Project\nimport org.gradle.api.tasks.SourceSet\nimport org.gradle.api.tasks.testing.Test\n\n@Mixin(GradlePluginMixin)\nclass TestExtPlugin implements Plugin {\n\n\tstatic final String PLUGIN_NAME = \"org.dreamscale.test-ext\"\n\tstatic final String VERIFICATION_GROUP_NAME = \"Verification\"\n\n\n\tprivate Project project\n\n\t@Override\n\tvoid apply(Project project) {\n\t\tthis.project = project\n\t\tproject.apply(plugin: \"java\")\n\t\tconfigureMainTestAndSharedTest()\n\t\tupdateTestLoggersToWriteStackTracesOnTestFailure()\n\t\tudpateTestLoggersToWriteSkippedTestEvents()\n\t\taddStyledTestOutputTask()\n\t}\n\n\tprivate void configureMainTestAndSharedTest() {\n\t\taddMainTestAndSharedTestConfigurations()\n\t\taddMainTestAndSharedTestSourceSets()\n\t\tupdateSourceSetTestToIncludeConfigurationSharedTest()\n\n\t\tif (project.file(\"src\/mainTest\").exists()) {\n\t\t\taddMainTestJarTasks()\n\t\t}\n\t}\n\n\tprivate void addMainTestAndSharedTestConfigurations() {\n\t\tcreateNamedConfigurationExtendingFrom(\"mainTest\", [\"compile\"], [\"compileOnly\"], [])\n\t\tcreateNamedConfigurationExtendingFrom(\"sharedTest\", [\"compile\", \"mainTestCompile\"], [\"compileOnly\", \"mainTestCompileOnly\"], [\"runtime\"])\n\t}\n\n\tprivate void addMainTestAndSharedTestSourceSets() {\n\t\tproject.sourceSets {\n\t\t\tmainTest {\n\t\t\t\tcompileClasspath = main.output + compileClasspath\n\t\t\t\truntimeClasspath = mainTest.output + main.output + runtimeClasspath\n\t\t\t}\n\t\t}\n\n\t\tproject.sourceSets {\n sharedTest {\n compileClasspath = mainTest.output + main.output + compileClasspath\n runtimeClasspath = sharedTest.output + mainTest.output + main.output + runtimeClasspath\n }\n }\n\t}\n\n\tprivate void addMainTestJarTasks() {\n\t\tSourceSet mainTest = project.sourceSets.mainTest\n\t\tCommonTaskFactory taskFactory = new CommonTaskFactory(project, mainTest)\n\n\t\ttaskFactory.createJarTask()\n\t\ttaskFactory.createSourcesJarTask()\n\t\ttaskFactory.createJavadocJarTask()\n\t}\n\n\tprivate void updateSourceSetTestToIncludeConfigurationSharedTest() {\n\t\tproject.sourceSets {\n\t\t\ttest {\n\t\t\t\tcompileClasspath = sharedTest.output + sharedTest.compileClasspath + compileClasspath\n\t\t\t\truntimeClasspath = test.output + sharedTest.runtimeClasspath + runtimeClasspath\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void updateTestLoggersToWriteStackTracesOnTestFailure() {\n\t\tproject.tasks.withType(Test) { Test test ->\n\t\t\ttest.testLogging.exceptionFormat = \"full\"\n\t\t\ttest.testLogging.stackTraceFilters(\"groovy\")\n\t\t}\n\t}\n\n\tprivate void udpateTestLoggersToWriteSkippedTestEvents() {\n\t\tproject.tasks.withType(Test) { Test test ->\n\t\t\ttest.testLogging.events(\"skipped\")\n\t\t}\n\t}\n\n\tprivate void addStyledTestOutputTask() {\n\t\tStyledTestOutput stoTask = project.tasks.create(\"styledTestOutput\", StyledTestOutput)\n\t\tstoTask.configure {\n\t\t\tgroup = VERIFICATION_GROUP_NAME\n\t\t\tdescription = \"Modifies build to output test results incrementally\"\n\t\t}\n\n\t\tproject.tasks.withType(Test) { Test test ->\n\t\t\ttest.mustRunAfter stoTask\n\t\t}\n\t}\n\n}\n","avg_line_length":30.9831932773,"max_line_length":138,"alphanum_fraction":0.7618660157} +{"size":425,"ext":"groovy","lang":"Groovy","max_stars_count":5.0,"content":"package jsonlenium.ui.util\r\n\r\nimport jsonlenium.annotation.AssertionType\r\n\r\nclass AnnotationUtil {\r\n static void forClasses() {\r\n Class.metaClass.toString() {\r\n def assertion = delegate.annotations.find { it instanceof AssertionType }\r\n if (assertion != null) {\r\n return ((AssertionType)assertion).value().toString()\r\n }\r\n\r\n delegate\r\n }\r\n }\r\n}\r\n","avg_line_length":25.0,"max_line_length":86,"alphanum_fraction":0.5811764706} +{"size":3843,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"package common;\n\nimport org.ofbiz.base.util.UtilValidate;\nimport org.ofbiz.party.contact.ContactMechWorker;\nimport org.ofbiz.entity.util.EntityUtil;\nimport org.ofbiz.base.util.UtilMisc;\nimport org.ofbiz.entity.GenericValue;\nimport org.ofbiz.product.store.ProductStoreWorker;\nimport javolution.util.FastList;\nimport org.ofbiz.base.util.Debug\n\nstoreId = parameters.storeId;\nshoppingCart = session.getAttribute(\"shoppingCart\");\nif (UtilValidate.isEmpty(storeId)) \n{\n if (UtilValidate.isNotEmpty(shoppingCart))\n {\n storeId = shoppingCart.getOrderAttribute(\"STORE_LOCATION\");\n context.shoppingCart = shoppingCart;\n\t\tcontext.shoppingCartStoreId = storeId;\n }\n} \nelse \n{\n context.shoppingCart = session.getAttribute(\"shoppingCart\");\n}\n\nif (UtilValidate.isEmpty(storeId)) \n{\n orderId = parameters.orderId;\n if (UtilValidate.isNotEmpty(orderId)) \n {\n orderAttrPickupStore = delegator.findOne(\"OrderAttribute\", [\"orderId\" : orderId, \"attrName\" : \"STORE_LOCATION\"], true);\n if (UtilValidate.isNotEmpty(orderAttrPickupStore)) \n {\n storeId = orderAttrPickupStore.attrValue;\n\t\t\tcontext.shoppingCartStoreId = storeId;\n }\n }\n}\n\n\n\/\/get a list of all the stores\nproductStore = ProductStoreWorker.getProductStore(request);\nproductStoreId=productStore.getString(\"productStoreId\");\nopenStores = FastList.newInstance();\nallStores = delegator.findByAndCache(\"ProductStoreRole\", UtilMisc.toMap(\"productStoreId\", productStoreId,\"roleTypeId\", \"STORE_LOCATION\"));\nif (UtilValidate.isNotEmpty(allStores))\n{\n\tfor(GenericValue store : allStores)\n\t{\n\t\tstoreParty = store.getRelatedOneCache(\"Party\");\n\t\tif(UtilValidate.isNotEmpty(storeParty.statusId) && \"PARTY_ENABLED\".equals(storeParty.statusId))\n\t\t{\n\t\t\topenStores.add(storeParty);\n\t\t}\n\t}\n}\nif (UtilValidate.isNotEmpty(openStores))\n{\n\tif(openStores.size() == 1)\n\t{\n\t\toneStoreOpen = openStores.getAt(0);\n\t\tstoreId = oneStoreOpen.partyId;\n\t\tcontext.oneStoreOpenStoreId = storeId;\n\t}\n}\n\n\n\nif (UtilValidate.isNotEmpty(storeId)) \n{\n party = delegator.findOne(\"Party\", [partyId : storeId], true);\n if (UtilValidate.isNotEmpty(party))\n {\n partyGroup = party.getRelatedOneCache(\"PartyGroup\");\n if (UtilValidate.isNotEmpty(partyGroup)) \n {\n context.storeInfo = partyGroup;\n }\n\n partyContactMechPurpose = party.getRelatedCache(\"PartyContactMechPurpose\");\n partyContactMechPurpose = EntityUtil.filterByDate(partyContactMechPurpose,true);\n\n partyGeneralLocations = EntityUtil.filterByAnd(partyContactMechPurpose, UtilMisc.toMap(\"contactMechPurposeTypeId\", \"GENERAL_LOCATION\"));\n partyGeneralLocations = EntityUtil.getRelatedCache(\"PartyContactMech\", partyGeneralLocations);\n partyGeneralLocations = EntityUtil.filterByDate(partyGeneralLocations,true);\n partyGeneralLocations = EntityUtil.orderBy(partyGeneralLocations, UtilMisc.toList(\"fromDate DESC\"));\n if (UtilValidate.isNotEmpty(partyGeneralLocations)) \n {\n \tpartyGeneralLocation = EntityUtil.getFirst(partyGeneralLocations);\n \tcontext.storeAddress = partyGeneralLocation.getRelatedOneCache(\"PostalAddress\");\n }\n\n partyPrimaryPhones = EntityUtil.filterByAnd(partyContactMechPurpose, UtilMisc.toMap(\"contactMechPurposeTypeId\", \"PRIMARY_PHONE\"));\n partyPrimaryPhones = EntityUtil.getRelatedCache(\"PartyContactMech\", partyPrimaryPhones);\n partyPrimaryPhones = EntityUtil.filterByDate(partyPrimaryPhones,true);\n partyPrimaryPhones = EntityUtil.orderBy(partyPrimaryPhones, UtilMisc.toList(\"fromDate DESC\"));\n if (UtilValidate.isNotEmpty(partyPrimaryPhones)) \n {\n \tpartyPrimaryPhone = EntityUtil.getFirst(partyPrimaryPhones);\n \tcontext.storePhone = partyPrimaryPhone.getRelatedOneCache(\"TelecomNumber\");\n }\n }\n}\n\n\n\n\n\n\n\n","avg_line_length":34.0088495575,"max_line_length":144,"alphanum_fraction":0.7384855582} +{"size":4128,"ext":"groovy","lang":"Groovy","max_stars_count":50.0,"content":"package org.ods.orchestration\n\nimport org.ods.PipelineScript\nimport org.ods.orchestration.TestStage\nimport org.ods.orchestration.scheduler.LeVADocumentScheduler\nimport org.ods.services.JenkinsService\nimport org.ods.services.ServiceRegistry\nimport org.ods.orchestration.usecase.JUnitTestReportsUseCase\nimport org.ods.orchestration.usecase.JiraUseCase\nimport org.ods.util.IPipelineSteps\nimport org.ods.orchestration.util.MROPipelineUtil\nimport org.ods.util.PipelineSteps\nimport org.ods.orchestration.util.Project\nimport util.SpecHelper\nimport org.ods.util.Logger\nimport org.ods.util.ILogger\n\nimport static util.FixtureHelper.createProject\n\nclass TestStageSpec extends SpecHelper {\n Project project\n TestStage testStage\n IPipelineSteps steps\n PipelineScript script\n MROPipelineUtil util\n JiraUseCase jira\n JUnitTestReportsUseCase junit\n JenkinsService jenkins\n LeVADocumentScheduler levaDocScheduler\n ILogger logger\n\n def phase = MROPipelineUtil.PipelinePhases.TEST\n\n def setup() {\n script = new PipelineScript()\n steps = Mock(PipelineSteps)\n levaDocScheduler = Mock(LeVADocumentScheduler)\n project = Spy(createProject())\n util = Mock(MROPipelineUtil)\n jira = Mock(JiraUseCase)\n junit = Mock(JUnitTestReportsUseCase)\n jenkins = Mock(JenkinsService)\n logger = new Logger(script, !!script.env.DEBUG)\n createService()\n testStage = Spy(new TestStage(script, project, project.repositories, null))\n }\n\n ServiceRegistry createService() {\n def registry = ServiceRegistry.instance\n\n registry.add(PipelineSteps, steps)\n registry.add(LeVADocumentScheduler, levaDocScheduler)\n registry.add(MROPipelineUtil, util)\n registry.add(JiraUseCase, jira)\n registry.add(JUnitTestReportsUseCase, junit)\n registry.add(JenkinsService, jenkins)\n registry.add(Logger, logger)\n\n return registry\n }\n\n def \"succesful execution\"() {\n given:\n junit.parseTestReportFiles(*_) >> [:]\n\n when:\n testStage.run()\n\n then:\n 1 * levaDocScheduler.run(phase, MROPipelineUtil.PipelinePhaseLifecycleStage.POST_START)\n 1 * util.prepareExecutePhaseForReposNamedJob(*_)\n 1 * levaDocScheduler.run(phase, MROPipelineUtil.PipelinePhaseLifecycleStage.PRE_END, [:], _)\n }\n\n def \"in TEST repo only one call per test types to report test results in Jira\"() {\n given:\n steps.env >> [WORKSPACE: \"\", BUILD_ID: 1]\n jenkins.unstashFilesIntoPath(_, _, \"JUnit XML Report\") >> true\n junit.loadTestReportsFromPath(_) >> []\n junit.parseTestReportFiles(_) >> [:]\n\n when:\n testStage.run()\n\n then:\n 1 * testStage.getTestResults(steps, _, Project.TestType.INSTALLATION) >> [testReportFiles: [], testResults: [testsuites:[]]]\n 1 * testStage.getTestResults(steps, _, Project.TestType.INTEGRATION) >> [testReportFiles: [], testResults: [testsuites:[]]]\n 1 * testStage.getTestResults(steps, _, Project.TestType.ACCEPTANCE) >> [testReportFiles: [], testResults: [testsuites:[]]]\n 1 * util.prepareExecutePhaseForReposNamedJob(MROPipelineUtil.PipelinePhases.TEST, project.repositories, _, _) >> { phase_, repos_, preExecuteRepo_, postExecuteRepo_ ->\n postExecuteRepo_.call(steps, [type: MROPipelineUtil.PipelineConfig.REPO_TYPE_ODS_TEST] as Map)\n return []\n }\n 1 * jira.reportTestResultsForProject([Project.TestType.INSTALLATION], _)\n 1 * jira.reportTestResultsForProject([Project.TestType.INTEGRATION], _)\n 1 * jira.reportTestResultsForProject([Project.TestType.ACCEPTANCE], _)\n }\n\n def \"get test results from file\"() {\n given:\n steps.env >> [WORKSPACE : \"\", BUILD_ID : 1]\n jenkins.unstashFilesIntoPath(_, _, \"JUnit XML Report\") >> true\n junit.loadTestReportsFromPath(_) >> []\n junit.parseTestReportFiles(_) >> [:]\n\n when:\n testStage.getTestResults(steps, project.repositories.first(), \"acceptance\")\n\n then:\n 1 * junit.loadTestReportsFromPath(_)\n }\n}\n","avg_line_length":36.8571428571,"max_line_length":175,"alphanum_fraction":0.6964631783} +{"size":21572,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Copyright 2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.gradle.language.swift\n\nimport org.gradle.nativeplatform.fixtures.AbstractInstalledToolChainIntegrationSpec\nimport org.gradle.nativeplatform.fixtures.app.SwiftApp\nimport org.gradle.nativeplatform.fixtures.app.SwiftAppWithLibraries\nimport org.gradle.nativeplatform.fixtures.app.SwiftAppWithLibrary\nimport org.gradle.nativeplatform.fixtures.app.SwiftAppWithLibraryAndOptionalFeature\nimport org.gradle.nativeplatform.fixtures.app.SwiftAppWithOptionalFeature\nimport org.gradle.util.Requires\nimport org.gradle.util.TestPrecondition\n\nimport static org.gradle.util.Matchers.containsText\n\n@Requires(TestPrecondition.SWIFT_SUPPORT)\nclass SwiftExecutableIntegrationTest extends AbstractInstalledToolChainIntegrationSpec {\n def \"skip compile, link and install tasks when no source\"() {\n given:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n \"\"\"\n\n expect:\n succeeds \"assemble\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n \/\/ TODO - should skip the task as NO-SOURCE\n result.assertTasksSkipped(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n }\n\n def \"build fails when compilation fails\"() {\n given:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n \"\"\"\n\n and:\n file(\"src\/main\/swift\/broken.swift\") << \"broken!\"\n\n expect:\n fails \"assemble\"\n failure.assertHasDescription(\"Execution failed for task ':compileDebugSwift'.\")\n failure.assertHasCause(\"A build operation failed.\")\n failure.assertThatCause(containsText(\"Swift compiler failed while compiling swift file(s)\"))\n }\n\n def \"sources are compiled and linked with Swift tools\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n \"\"\"\n\n expect:\n succeeds \"assemble\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n\n executable(\"build\/exe\/main\/debug\/App\").assertExists()\n file(\"build\/modules\/main\/debug\/App.swiftmodule\").assertIsFile()\n installation(\"build\/install\/main\/debug\").exec().out == app.expectedOutput\n }\n\n def \"can build debug and release variant of the executable\"() {\n given:\n def app = new SwiftAppWithOptionalFeature()\n settingsFile << \"rootProject.name = 'app'\"\n app.writeToProject(testDirectory)\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n compileReleaseSwift.compilerArgs = ['-DWITH_FEATURE']\n \"\"\"\n\n expect:\n succeeds \"installRelease\"\n result.assertTasksExecuted(\":compileReleaseSwift\", \":linkRelease\", \":installRelease\")\n\n executable(\"build\/exe\/main\/release\/App\").assertExists()\n executable(\"build\/exe\/main\/release\/App\").exec().out == app.withFeatureEnabled().expectedOutput\n installation(\"build\/install\/main\/release\").exec().out == app.withFeatureEnabled().expectedOutput\n\n succeeds \"installDebug\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\")\n\n file(\"build\/modules\/main\/release\/App.swiftmodule\").assertIsFile()\n executable(\"build\/exe\/main\/debug\/App\").assertExists()\n executable(\"build\/exe\/main\/debug\/App\").exec().out == app.withFeatureDisabled().expectedOutput\n installation(\"build\/install\/main\/debug\").exec().out == app.withFeatureDisabled().expectedOutput\n }\n\n def \"can use executable file as task dependency\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n\n task buildDebug {\n dependsOn executable.debugExecutable.executableFile\n }\n \"\"\"\n\n expect:\n succeeds \"buildDebug\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", ':buildDebug')\n executable(\"build\/exe\/main\/debug\/App\").assertExists()\n }\n\n def \"can use objects as task dependency\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n\n task compileDebug {\n dependsOn executable.debugExecutable.objects\n }\n \"\"\"\n\n expect:\n succeeds \"compileDebug\"\n result.assertTasksExecuted(\":compileDebugSwift\", ':compileDebug')\n executable(\"build\/exe\/main\/debug\/App\").assertDoesNotExist()\n objectFiles(app.main)*.assertExists()\n }\n\n def \"can use installDirectory as task dependency\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n\n task install {\n dependsOn executable.debugExecutable.installDirectory\n }\n \"\"\"\n\n expect:\n succeeds \"install\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", ':installDebug', ':install')\n installation(\"build\/install\/main\/debug\").exec().out == app.expectedOutput\n }\n\n def \"ignores non-Swift source files in source directory\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n file(\"src\/main\/swift\/ignore.cpp\") << 'broken!'\n file(\"src\/main\/swift\/ignore.c\") << 'broken!'\n file(\"src\/main\/swift\/ignore.m\") << 'broken!'\n file(\"src\/main\/swift\/ignore.h\") << 'broken!'\n file(\"src\/main\/swift\/ignore.java\") << 'broken!'\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n \"\"\"\n\n expect:\n succeeds \"assemble\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n\n executable(\"build\/exe\/main\/debug\/App\").assertExists()\n installation(\"build\/install\/main\/debug\").exec().out == app.expectedOutput\n }\n\n def \"build logic can change source layout convention\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToSourceDir(file(\"Sources\"))\n\n file(\"src\/main\/swift\/broken.swift\") << \"ignore me!\"\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n executable {\n source.from 'Sources'\n }\n \"\"\"\n\n expect:\n succeeds \"assemble\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n\n file(\"build\/obj\/main\/debug\").assertIsDir()\n executable(\"build\/exe\/main\/debug\/${app.moduleName}\").assertExists()\n installation(\"build\/install\/main\/debug\").exec().out == app.expectedOutput\n }\n\n def \"build logic can add individual source files\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n app.main.writeToSourceDir(file(\"src\/main.swift\"))\n app.greeter.writeToSourceDir(file(\"src\/one.swift\"))\n app.sum.writeToSourceDir(file(\"src\/two.swift\"))\n file(\"src\/main\/swift\/broken.swift\") << \"ignore me!\"\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n executable {\n source {\n from('src\/main.swift')\n from('src\/one.swift')\n from('src\/two.swift')\n }\n }\n \"\"\"\n\n expect:\n succeeds \"assemble\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n\n file(\"build\/obj\/main\/debug\").assertIsDir()\n executable(\"build\/exe\/main\/debug\/App\").assertExists()\n installation(\"build\/install\/main\/debug\").exec().out == app.expectedOutput\n }\n\n def \"build logic can change buildDir\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n buildDir = 'output'\n \"\"\"\n\n expect:\n succeeds \"assemble\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n\n !file(\"build\").exists()\n file(\"output\/obj\/main\/debug\").assertIsDir()\n executable(\"output\/exe\/main\/debug\/App\").assertExists()\n file(\"output\/modules\/main\/debug\/App.swiftmodule\").assertIsFile()\n installation(\"output\/install\/main\/debug\").exec().out == app.expectedOutput\n }\n\n def \"build logic can define the module name\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n executable.module = 'TestApp'\n \"\"\"\n\n expect:\n succeeds \"assemble\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n\n file(\"build\/obj\/main\/debug\").assertIsDir()\n executable(\"build\/exe\/main\/debug\/TestApp\").assertExists()\n installation(\"build\/install\/main\/debug\").exec().out == app.expectedOutput\n }\n\n def \"build logic can change task output locations\"() {\n given:\n def app = new SwiftApp()\n settingsFile << \"rootProject.name = '${app.projectName}'\"\n app.writeToProject(testDirectory)\n\n and:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n compileDebugSwift.objectFileDir = layout.buildDirectory.dir(\"object-files\")\n compileDebugSwift.moduleFile = layout.buildDirectory.file(\"some-app.swiftmodule\")\n linkDebug.binaryFile = layout.buildDirectory.file(\"exe\/some-app.exe\")\n installDebug.installDirectory = layout.buildDirectory.dir(\"some-app\")\n \"\"\"\n\n expect:\n succeeds \"assemble\"\n result.assertTasksExecuted(\":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n\n file(\"build\/object-files\").assertIsDir()\n file(\"build\/exe\/some-app.exe\").assertIsFile()\n file(\"build\/some-app.swiftmodule\").assertIsFile()\n installation(\"build\/some-app\").exec().out == app.expectedOutput\n }\n\n def \"can compile and link against a library\"() {\n settingsFile << \"include 'app', 'greeter'\"\n def app = new SwiftAppWithLibrary()\n\n given:\n buildFile << \"\"\"\n project(':app') {\n apply plugin: 'swift-executable'\n dependencies {\n implementation project(':greeter')\n }\n }\n project(':greeter') {\n apply plugin: 'swift-library'\n }\n\"\"\"\n app.library.writeToProject(file(\"greeter\"))\n app.executable.writeToProject(file(\"app\"))\n\n expect:\n succeeds \":app:assemble\"\n result.assertTasksExecuted(\":greeter:compileDebugSwift\", \":greeter:linkDebug\", \":app:compileDebugSwift\", \":app:linkDebug\", \":app:installDebug\", \":app:assemble\")\n\n executable(\"app\/build\/exe\/main\/debug\/App\").assertExists()\n sharedLibrary(\"greeter\/build\/lib\/main\/debug\/Greeter\").assertExists()\n installation(\"app\/build\/install\/main\/debug\").exec().out == app.expectedOutput\n sharedLibrary(\"app\/build\/install\/main\/debug\/lib\/Greeter\").assertExists()\n }\n\n def \"can compile and link against library with API dependencies\"() {\n settingsFile << \"include 'app', 'hello', 'log'\"\n def app = new SwiftAppWithLibraries()\n\n given:\n buildFile << \"\"\"\n project(':app') {\n apply plugin: 'swift-executable'\n dependencies {\n implementation project(':hello')\n }\n }\n project(':hello') {\n apply plugin: 'swift-library'\n dependencies {\n api project(':log')\n }\n }\n project(':log') {\n apply plugin: 'swift-library'\n }\n\"\"\"\n app.library.writeToProject(file(\"hello\"))\n app.logLibrary.writeToProject(file(\"log\"))\n app.executable.writeToProject(file(\"app\"))\n\n expect:\n succeeds \":app:assemble\"\n\n result.assertTasksExecuted(\":hello:compileDebugSwift\", \":hello:linkDebug\", \":log:compileDebugSwift\", \":log:linkDebug\", \":app:compileDebugSwift\", \":app:linkDebug\", \":app:installDebug\", \":app:assemble\")\n\n sharedLibrary(\"hello\/build\/lib\/main\/debug\/Hello\").assertExists()\n sharedLibrary(\"log\/build\/lib\/main\/debug\/Log\").assertExists()\n executable(\"app\/build\/exe\/main\/debug\/App\").assertExists()\n installation(\"app\/build\/install\/main\/debug\").exec().out == app.expectedOutput\n sharedLibrary(\"app\/build\/install\/main\/debug\/lib\/Hello\").assertExists()\n sharedLibrary(\"app\/build\/install\/main\/debug\/lib\/Log\").assertExists()\n\n succeeds \":app:installRelease\"\n\n result.assertTasksExecuted(\":hello:compileReleaseSwift\", \":hello:linkRelease\", \":log:compileReleaseSwift\", \":log:linkRelease\", \":app:compileReleaseSwift\", \":app:linkRelease\", \":app:installRelease\")\n\n sharedLibrary(\"hello\/build\/lib\/main\/release\/Hello\").assertExists()\n sharedLibrary(\"log\/build\/lib\/main\/release\/Log\").assertExists()\n executable(\"app\/build\/exe\/main\/release\/App\").assertExists()\n installation(\"app\/build\/install\/main\/release\").exec().out == app.expectedOutput\n }\n\n def \"can compile and link against a library with debug and release variants\"() {\n settingsFile << \"include 'app', 'hello', 'log'\"\n def app = new SwiftAppWithLibraryAndOptionalFeature()\n\n given:\n buildFile << \"\"\"\n project(':app') {\n apply plugin: 'swift-executable'\n dependencies {\n implementation project(':hello')\n }\n compileReleaseSwift.compilerArgs = ['-DWITH_FEATURE']\n }\n project(':hello') {\n apply plugin: 'swift-library'\n library.module = 'Greeter'\n compileReleaseSwift.compilerArgs = ['-DWITH_FEATURE']\n }\n\"\"\"\n app.library.writeToProject(file(\"hello\"))\n app.executable.writeToProject(file(\"app\"))\n\n expect:\n succeeds \":app:linkRelease\"\n\n result.assertTasksExecuted(\":hello:compileReleaseSwift\", \":hello:linkRelease\", \":app:compileReleaseSwift\", \":app:linkRelease\")\n\n sharedLibrary(\"hello\/build\/lib\/main\/release\/Greeter\").assertExists()\n executable(\"app\/build\/exe\/main\/release\/App\").exec().out == app.withFeatureEnabled().expectedOutput\n\n succeeds \":app:linkDebug\"\n\n result.assertTasksExecuted(\":hello:compileDebugSwift\", \":hello:linkDebug\", \":app:compileDebugSwift\", \":app:linkDebug\")\n\n sharedLibrary(\"hello\/build\/lib\/main\/debug\/Greeter\").assertExists()\n executable(\"app\/build\/exe\/main\/debug\/App\").exec().out == app.withFeatureDisabled().expectedOutput\n }\n\n def \"honors changes to library buildDir\"() {\n settingsFile << \"include 'app', 'hello', 'log'\"\n def app = new SwiftAppWithLibraries()\n\n given:\n buildFile << \"\"\"\n project(':app') {\n apply plugin: 'swift-executable'\n dependencies {\n implementation project(':hello')\n }\n }\n project(':hello') {\n apply plugin: 'swift-library'\n dependencies {\n api project(':log')\n }\n }\n project(':log') {\n apply plugin: 'swift-library'\n buildDir = 'out'\n }\n\"\"\"\n app.library.writeToProject(file(\"hello\"))\n app.logLibrary.writeToProject(file(\"log\"))\n app.executable.writeToProject(file(\"app\"))\n\n expect:\n succeeds \":app:assemble\"\n result.assertTasksExecuted(\":hello:compileDebugSwift\", \":hello:linkDebug\", \":log:compileDebugSwift\", \":log:linkDebug\", \":app:compileDebugSwift\", \":app:linkDebug\", \":app:installDebug\", \":app:assemble\")\n\n !file(\"log\/build\").exists()\n sharedLibrary(\"hello\/build\/lib\/main\/debug\/Hello\").assertExists()\n sharedLibrary(\"log\/out\/lib\/main\/debug\/Log\").assertExists()\n executable(\"app\/build\/exe\/main\/debug\/App\").assertExists()\n installation(\"app\/build\/install\/main\/debug\").exec().out == app.expectedOutput\n sharedLibrary(\"app\/build\/install\/main\/debug\/lib\/Hello\").file.assertExists()\n sharedLibrary(\"app\/build\/install\/main\/debug\/lib\/Log\").file.assertExists()\n }\n\n def \"multiple components can share the same source directory\"() {\n settingsFile << \"include 'app', 'hello', 'log'\"\n def app = new SwiftAppWithLibraries()\n\n given:\n buildFile << \"\"\"\n project(':app') {\n apply plugin: 'swift-executable'\n dependencies {\n implementation project(':hello')\n }\n executable {\n source.from '..\/Sources\/${app.main.sourceFile.name}'\n }\n }\n project(':hello') {\n apply plugin: 'swift-library'\n dependencies {\n api project(':log')\n }\n library {\n source.from '..\/Sources\/${app.greeter.sourceFile.name}'\n }\n }\n project(':log') {\n apply plugin: 'swift-library'\n library {\n source.from '..\/Sources\/${app.logger.sourceFile.name}'\n }\n }\n\"\"\"\n app.library.writeToSourceDir(file(\"Sources\"))\n app.logLibrary.writeToSourceDir(file(\"Sources\"))\n app.executable.writeToSourceDir(file(\"Sources\"))\n\n expect:\n succeeds \":app:assemble\"\n result.assertTasksExecuted(\":hello:compileDebugSwift\", \":hello:linkDebug\", \":log:compileDebugSwift\", \":log:linkDebug\", \":app:compileDebugSwift\", \":app:linkDebug\", \":app:installDebug\", \":app:assemble\")\n\n sharedLibrary(\"hello\/build\/lib\/main\/debug\/Hello\").assertExists()\n sharedLibrary(\"log\/build\/lib\/main\/debug\/Log\").assertExists()\n executable(\"app\/build\/exe\/main\/debug\/App\").exec().out == app.expectedOutput\n sharedLibrary(\"app\/build\/install\/main\/debug\/lib\/Hello\").file.assertExists()\n sharedLibrary(\"app\/build\/install\/main\/debug\/lib\/Log\").file.assertExists()\n }\n\n def \"can compile and link against libraries in included builds\"() {\n settingsFile << \"\"\"\n rootProject.name = 'app'\n includeBuild 'hello'\n includeBuild 'log'\n \"\"\"\n file(\"hello\/settings.gradle\") << \"rootProject.name = 'hello'\"\n file(\"log\/settings.gradle\") << \"rootProject.name = 'log'\"\n\n def app = new SwiftAppWithLibraries()\n\n given:\n buildFile << \"\"\"\n apply plugin: 'swift-executable'\n dependencies {\n implementation 'test:hello:1.2'\n }\n \"\"\"\n file(\"hello\/build.gradle\") << \"\"\"\n apply plugin: 'swift-library'\n group = 'test'\n dependencies {\n api 'test:log:1.4'\n }\n \"\"\"\n file(\"log\/build.gradle\") << \"\"\"\n apply plugin: 'swift-library'\n group = 'test'\n \"\"\"\n\n app.library.writeToProject(file(\"hello\"))\n app.logLibrary.writeToProject(file(\"log\"))\n app.executable.writeToProject(testDirectory)\n\n expect:\n succeeds \":assemble\"\n result.assertTasksExecuted(\":hello:compileDebugSwift\", \":hello:linkDebug\", \":log:compileDebugSwift\", \":log:linkDebug\", \":compileDebugSwift\", \":linkDebug\", \":installDebug\", \":assemble\")\n\n sharedLibrary(\"hello\/build\/lib\/main\/debug\/Hello\").assertExists()\n sharedLibrary(\"log\/build\/lib\/main\/debug\/Log\").assertExists()\n executable(\"build\/exe\/main\/debug\/App\").assertExists()\n installation(\"build\/install\/main\/debug\").exec().out == app.expectedOutput\n sharedLibrary(\"build\/install\/main\/debug\/lib\/Hello\").file.assertExists()\n sharedLibrary(\"build\/install\/main\/debug\/lib\/Log\").file.assertExists()\n }\n}\n","avg_line_length":37.7132867133,"max_line_length":208,"alphanum_fraction":0.6036992398} +{"size":9298,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Copyright (c) 2012-2014 nadavc \n * This work is free. You can redistribute it and\/or modify it under the\n * terms of the WTFPL, Version 2, as published by Sam Hocevar.\n * See the COPYING file for more details.\n *\/\n\npackage org.groovykoans.koan07\n\nimport java.util.regex.Matcher\nimport java.util.regex.Pattern\n\n\/**\n * Koan07 - Regular Expressions\n *\n * Resource list:\n * * http:\/\/www.vogella.com\/articles\/JavaRegularExpressions\/article.html\n * * http:\/\/docs.groovy-lang.org\/latest\/html\/documentation\/index.html#all-strings\n * * http:\/\/docs.groovy-lang.org\/latest\/html\/documentation\/index.html#_regular_expression_operators\n * * http:\/\/naleid.com\/blog\/2009\/04\/07\/groovy-161-released-with-new-find-and-findall-regexp-methods-on-string\/\n * * http:\/\/www.ngdc.noaa.gov\/wiki\/index.php\/Regular_Expressions_in_Groovy#The_eXtended_Pattern_Match_Flag_.28x.29\n *\/\nclass Koan07 extends GroovyTestCase {\n\n void test01_SimpleRegularExpression() {\n \/\/ First we must understand regular expressions. There's a nice tutorial at\n \/\/ http:\/\/www.vogella.com\/articles\/JavaRegularExpressions\/article.html\n\n \/\/ Using your knowledge of regular expressions, create a regexp string that gets all the technologies\n \/\/ that begin with 'G' and end with either 'e' or 's'\n def technologies = ['Grails', 'Gradle', '.NET', 'Python', 'Groovy']\n def regexp\n \/\/ ------------ START EDITING HERE ----------------------\n regexp = '^G.*[e|s]$'\n \/\/ ------------ STOP EDITING HERE ----------------------\n def result = technologies.findAll { it ==~ regexp }\n\n assert result == ['Grails', 'Gradle']\n }\n\n void test02_MultilineStrings() {\n \/\/ With Groovy it's possible to declare multiline strings using either ''' or \"\"\" (Multiline GString).\n \/\/ More info at http:\/\/docs.groovy-lang.org\/latest\/html\/documentation\/index.html#_triple_double_quoted_string\n\n String signs = '+, \\\\, and others'\n\n \/\/ Create the string below with Groovy\n String javaString = \"In Java a multiline string\\n\" +\n \"requires using special signs such as \" + signs + \"\\n\" +\n \"and can become difficult to maintain\"\n String groovyString\n \/\/ ------------ START EDITING HERE ----------------------\n groovyString = \"\"\"In Java a multiline string\nrequires using special signs such as ${signs}\nand can become difficult to maintain\"\"\"\n\n\n \/\/ ------------ STOP EDITING HERE ----------------------\n assert groovyString == javaString\n }\n\n void test03_SlashyStrings() {\n \/\/ The other type of String declaration is called Slashy strings. They're especially useful for\n \/\/ regular expressions. Read about them at\n \/\/ http:\/\/docs.groovy-lang.org\/latest\/html\/documentation\/index.html#_slashy_string\n\n \/\/ Suppose we have the following text:\n def text = '''|Item # Sold Leftover\n |Xbox 2000 10\n |Playstation 100 5\n |Wii 5 1000'''.stripMargin()\n\n \/\/ If we wanted to grab the number of leftover items with a regular expression in Java, we would do this:\n int javaSum = 0;\n String javaRegExp = \"(?sm)(.*?)\\\\s+(\\\\d+)\\\\s+(\\\\d+)\"\n Matcher javaMatcher = Pattern.compile(javaRegExp).matcher(text);\n while (javaMatcher.find()) {\n javaSum += Integer.valueOf(javaMatcher.group(3));\n }\n\n \/\/ Slashy strings don't need escape backslashes in regular expressions. Translate the above regexp to\n \/\/ a Slashy string regexp\n def groovyRegExp\n \/\/ ------------ START EDITING HERE ----------------------\n groovyRegExp = \/(?sm)(.*?)\\s+(\\d+)\\s+(\\d+)\/\n\n\n \/\/ ------------ STOP EDITING HERE ----------------------\n def matcher = text =~ groovyRegExp\n def groovySum = matcher.collect { it[3].toInteger() }.sum()\n\n \/\/ ^^ Look how much more concise the Groovy code is! There's even a shorter version ahead...\n assert groovySum == javaSum\n }\n\n void test04_SpecialRegexpOperators() {\n \/\/ Groovy is very useful for text manipulation, and as such regular expressions get 3 special operators:\n \/\/ ~str (tilde) : creates a Pattern object from a string. Equivalent to Pattern.compile(str)\n \/\/ str =~ pattern : creates a Matcher from a regex and a string. Same as Pattern.compile(pattern).matcher(str)\n \/\/ str ==~ pattern : returns a boolean if pattern matches str. Same as Pattern.matches(pattern, str)\n \/\/ More docs at http:\/\/docs.groovy-lang.org\/latest\/html\/documentation\/index.html#_regular_expression_operators\n\n \/\/ This is how a Pattern object is defined in Java for an arbitrary phone number format\n \/\/ (xxx xxxx or xxxxxxx or xxx,xxxx)\n Pattern patternInJava = Pattern.compile(\"\\\\d{3}([,\\\\s])?\\\\d{4}\");\n\n \/\/ Create the same Pattern object in Groovy\n def patternInGroovy\n \/\/ ------------ START EDITING HERE ----------------------\n patternInGroovy = ~\/\\d{3}([,\\s])?\\d{4}\/\n\n\n \/\/ ------------ STOP EDITING HERE ----------------------\n assert patternInGroovy instanceof Pattern\n assertEquals(patternInJava.pattern(), patternInGroovy.pattern())\n\n \/\/ Once you have matches using the Groovy Matcher, you are able to iterate through them using the each() method.\n \/\/ Create a matcher and get the first names from the source text\n def names = 'John Lennon, Paul McCartney, George Harrison, Ringo Starr'\n def firstNamesList = []\n \/\/ ------------ START EDITING HERE ----------------------\n def matcher = names =~ \/(\\w+)\\s(\\w+)\/\n matcher.each { match, first, last ->\n firstNamesList << first\n }\n\n\n \/\/ ------------ STOP EDITING HERE ----------------------\n assert firstNamesList == ['John', 'Paul', 'George', 'Ringo']\n\n \/\/ And finally, using the ==~ operator, check if the the following number is a valid Visa card:\n \/\/ You can get the regular expression for Visas here: http:\/\/www.regular-expressions.info\/creditcard.html\n def number = '4927856234092'\n boolean isNumberValid = false\n \/\/ ------------ START EDITING HERE ----------------------\n isNumberValid = number ==~\"^4[0-9]{12}(?:[0-9]{3})?\\$\"\n\n\n \/\/ ------------ STOP EDITING HERE ----------------------\n assert isNumberValid, 'Visa number should be valid!'\n }\n\n void test05_ReplaceAllWithClosure() {\n \/\/ If your regular expression needs some \"business logic\" for search & replace, you can put it into Closures.\n \/\/ Reference:\n \/\/ http:\/\/naleid.com\/blog\/2009\/04\/07\/groovy-161-released-with-new-find-and-findall-regexp-methods-on-string\/\n\n \/\/ Using your newly acquired knowledge, create a regex that iterates all the words and replaces them using the\n \/\/ supplied dictionary. E.g. 'this town is mad!' -> 'this ciudad is mad!'\n def dictionary = ['town': 'ciudad', 'man': 'hombre', 'life': 'vida']\n def song = '''|In the town where I was born\n |Lived a man who sailed to sea\n |And he told us of his life\n |In the land of submarines'''.stripMargin()\n def result\n \/\/ ------------ START EDITING HERE ----------------------\n result = song.replaceAll(\/\\w+\/) { dictionary[it] ?: it }\n\n\n \/\/ ------------ STOP EDITING HERE ----------------------\n\n def expected = '''|In the ciudad where I was born\n |Lived a hombre who sailed to sea\n |And he told us of his vida\n |In the land of submarines'''.stripMargin()\n\n assert result == expected\n }\n\n void test06_MultilineRegexWithComments() {\n \/\/ Regular expression can become lengthy and hard to read. Groovy solves this by adding a special\n \/\/ \"extended\" (x) flag that ignores newlines and spaces. Read about it here:\n \/\/ http:\/\/www.ngdc.noaa.gov\/wiki\/index.php\/Regular_Expressions_in_Groovy#The_eXtended_Pattern_Match_Flag_.28x.29\n\n \/\/ Let's take the text from the exercise above:\n def text = '''|Item # Sold Leftover\n |Xbox 2000 10\n |Playstation 100 5\n |Wii 5 1000'''.stripMargin()\n\n \/\/ create the same regular expression to sum the total leftovers, but this time document the regex\n String regexp\n \/\/ ------------ START EDITING HERE ----------------------\n regexp = '''(?smx) \n (.*?) #segundo comentario\n \\\\s+ #tercer comentario\n (\\\\d+)\\\\s+(\\\\d+)\n '''\n \/\/ ------------ STOP EDITING HERE ----------------------\n def sum = text.findAll(regexp) { it[3].toInteger() }.sum()\n \/\/ ^^ This is even more concise than the previous example! Choose the one you feel most comfortable with.\n\n assert sum == 1015\n def options = regexp.find(\/\\(\\?[^\\)]*\\)\/)\n assert options.contains('x'), 'A commented regex must use the x flag'\n assert regexp.contains('#'), 'Comments can be inserted using the # character'\n }\n\n\n}\n","avg_line_length":46.2587064677,"max_line_length":120,"alphanum_fraction":0.5807700581} +{"size":6149,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Copyright 2013-2019, Centre for Genomic Regulation (CRG)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage nextflow.container\n\nimport java.nio.file.Paths\n\nimport spock.lang.Specification\n\n\/**\n *\n * @author Paolo Di Tommaso \n *\/\nclass SingularityBuilderTest extends Specification {\n\n def 'should get the exec command line' () {\n\n given:\n def path1 = Paths.get('\/foo\/data\/file1')\n def path2 = Paths.get('\/bar\/data\/file2')\n def path3 = Paths.get('\/bar\/data file')\n\n expect:\n new SingularityBuilder('busybox')\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec busybox'\n\n new SingularityBuilder('busybox')\n .params(engineOptions: '-q -v')\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity -q -v exec busybox'\n\n new SingularityBuilder('busybox')\n .params(runOptions: '--contain --writable')\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec --contain --writable busybox'\n\n new SingularityBuilder('ubuntu')\n .addMount(path1)\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec ubuntu'\n\n new SingularityBuilder('ubuntu')\n .addMount(path1)\n .addMount(path2)\n .params(autoMounts: true)\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec -B \/foo\/data\/file1 -B \/bar\/data\/file2 -B \"$PWD\" ubuntu'\n\n new SingularityBuilder('ubuntu')\n .addMount(path1)\n .addMount(path1)\n .params(autoMounts: true)\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec -B \/foo\/data\/file1 -B \"$PWD\" ubuntu'\n\n new SingularityBuilder('ubuntu')\n .addMount(path1)\n .addMount(path1)\n .params(autoMounts: true)\n .params(readOnlyInputs: true)\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec -B \/foo\/data\/file1:\/foo\/data\/file1:ro -B \"$PWD\" ubuntu'\n\n new SingularityBuilder('ubuntu')\n .addMount(path3)\n .params(autoMounts: true)\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec -B \/bar\/data\\\\ file -B \"$PWD\" ubuntu'\n\n }\n\n def 'should return export variables' () {\n\n expect:\n new SingularityBuilder('busybox')\n .getEnvExports() == ''\n\n new SingularityBuilder('busybox')\n .addEnv('X=1')\n .addEnv(ALPHA:'aaa', BETA: 'bbb')\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" SINGULARITYENV_X=1 SINGULARITYENV_ALPHA=\"aaa\" SINGULARITYENV_BETA=\"bbb\" singularity exec busybox'\n\n new SingularityBuilder('busybox')\n .addEnv('CUDA_VISIBLE_DEVICES')\n .build()\n .runCommand == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" ${CUDA_VISIBLE_DEVICES:+SINGULARITYENV_CUDA_VISIBLE_DEVICES=\"$CUDA_VISIBLE_DEVICES\"} singularity exec busybox'\n\n }\n\n\n def 'should get run command' () {\n\n when:\n def cmd = new SingularityBuilder('ubuntu.img').build().getRunCommand()\n then:\n cmd == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec ubuntu.img'\n\n when:\n cmd = new SingularityBuilder('ubuntu.img').build().getRunCommand('bwa --this --that file.fastq')\n then:\n cmd == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec ubuntu.img bwa --this --that file.fastq'\n\n when:\n cmd = new SingularityBuilder('ubuntu.img').params(entry:'\/bin\/sh').build().getRunCommand('bwa --this --that file.fastq')\n then:\n cmd == 'set +u; env - PATH=\"$PATH\" SINGULARITYENV_TMP=\"$TMP\" SINGULARITYENV_TMPDIR=\"$TMPDIR\" singularity exec ubuntu.img \/bin\/sh -c \"cd $PWD; bwa --this --that file.fastq\"'\n\n\n }\n\n def 'test singularity env'() {\n\n given:\n def builder = [:] as SingularityBuilder\n\n expect:\n builder.makeEnv(ENV).toString() == RESULT\n\n where:\n ENV | RESULT\n 'X=1' | 'SINGULARITYENV_X=1'\n 'BAR' | '${BAR:+SINGULARITYENV_BAR=\"$BAR\"}'\n [VAR_X:1, VAR_Y: 2] | 'SINGULARITYENV_VAR_X=\"1\" SINGULARITYENV_VAR_Y=\"2\"'\n [SINGULARITY_BIND: 'foo', SINGULARITYENV_FOO: 'x', BAR: 'y'] | 'SINGULARITY_BIND=\"foo\" SINGULARITYENV_FOO=\"x\" SINGULARITYENV_BAR=\"y\"'\n 'SINGULARITY_FOO' | '${SINGULARITY_FOO:+SINGULARITY_FOO=\"$SINGULARITY_FOO\"}'\n 'SINGULARITYENV_FOO' | '${SINGULARITYENV_FOO:+SINGULARITYENV_FOO=\"$SINGULARITYENV_FOO\"}'\n 'SINGULARITYENV_X=1' | 'SINGULARITYENV_X=1'\n }\n}\n","avg_line_length":42.4068965517,"max_line_length":227,"alphanum_fraction":0.6033501382} +{"size":2329,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"import datadog.trace.agent.test.AgentTestRunner\nimport datadog.trace.agent.test.utils.ConfigUtils\nimport datadog.trace.instrumentation.trace_annotation.TraceAnnotationsInstrumentation\nimport dd.test.trace.annotation.SayTracedHello\n\nimport java.util.concurrent.Callable\n\nimport static datadog.trace.instrumentation.trace_annotation.TraceAnnotationsInstrumentation.DEFAULT_ANNOTATIONS\n\nclass ConfiguredTraceAnnotationsTest extends AgentTestRunner {\n\n static {\n ConfigUtils.updateConfig {\n System.setProperty(\"dd.trace.annotations\", \"package.Class\\$Name;${OuterClass.InterestingMethod.name}\")\n }\n }\n\n def specCleanup() {\n System.clearProperty(\"dd.trace.annotations\")\n }\n\n def \"test disabled nr annotation\"() {\n setup:\n SayTracedHello.fromCallableWhenDisabled()\n\n expect:\n TEST_WRITER == []\n }\n\n def \"test custom annotation based trace\"() {\n expect:\n new AnnotationTracedCallable().call() == \"Hello!\"\n\n when:\n TEST_WRITER.waitForTraces(1)\n\n then:\n assertTraces(1) {\n trace(0, 1) {\n span(0) {\n resourceName \"AnnotationTracedCallable.call\"\n operationName \"AnnotationTracedCallable.call\"\n }\n }\n }\n }\n\n def \"test configuration #value\"() {\n setup:\n ConfigUtils.updateConfig {\n if (value) {\n System.properties.setProperty(\"dd.trace.annotations\", value)\n } else {\n System.clearProperty(\"dd.trace.annotations\")\n }\n }\n\n expect:\n new TraceAnnotationsInstrumentation().additionalTraceAnnotations == expected.toSet()\n\n where:\n value | expected\n null | DEFAULT_ANNOTATIONS.toList()\n \" \" | []\n \"some.Invalid[]\" | []\n \"some.package.ClassName \" | [\"some.package.ClassName\"]\n \" some.package.Class\\$Name\" | [\"some.package.Class\\$Name\"]\n \" ClassName \" | [\"ClassName\"]\n \"ClassName\" | [\"ClassName\"]\n \"Class\\$1;Class\\$2;\" | [\"Class\\$1\", \"Class\\$2\"]\n \"Duplicate ;Duplicate ;Duplicate; \" | [\"Duplicate\"]\n }\n\n class AnnotationTracedCallable implements Callable {\n @OuterClass.InterestingMethod\n @Override\n String call() throws Exception {\n return \"Hello!\"\n }\n }\n}\n","avg_line_length":28.4024390244,"max_line_length":112,"alphanum_fraction":0.6230141692} +{"size":17055,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\n\noutputPath = 'build'\n\n\/\/ Path where the docToolchain will search for the input files.\n\/\/ This path is appended to the docDir property specified in gradle.properties\n\/\/ or in the command line, and therefore must be relative to it.\n\ninputPath = 'src\/docs'\npdfThemeDir = '.\/src\/docs\/pdfTheme'\n\ninputFiles = [\n \/\/[file: 'doctoolchain_demo.adoc', formats: ['html','pdf']],\n \/\/[file: 'arc42-template.adoc', formats: ['html','pdf']],\n [file: 'manual.adoc', formats: ['html', 'pdf']],\n\t\/** inputFiles **\/\n]\n\n\/\/folders in which asciidoc will find images.\n\/\/these will be copied as resources to .\/images\nimageDirs = [\n 'images\/.',\n '020_tutorial\/images\/.'\n\t\/** imageDirs **\/\n]\n\n\/\/ folders in which asciidoc will find other resources with corrosponding target directory\n\/\/ works with generateHTML (target is prepended with build\/html5\/)\n\/\/ and generateSite (target ist prepended with build\/microsite\/output\/)\nresourceDirs = [\n \/\/[source: 'some\/ohter\/resource', target: 'target\/directory']\n\t\/** resourceDirs **\/\n]\n\n\/\/ these are directories (dirs) and files which Gradle monitors for a change\n\/\/ in order to decide if the docs have to be re-build\ntaskInputsDirs = [\n \"${inputPath}\",\n\/\/ \"${inputPath}\/src\",\n\/\/ \"${inputPath}\/images\",\n ]\n\ntaskInputsFiles = []\n\n\/\/*****************************************************************************************\n\n\/\/Configuration for microsite: generateSite + previewSite\n\nmicrosite = [:]\n\n\/\/ these properties will be set as jBake properties\n\/\/ microsite.foo will be site.foo in jBake and can be used as config.site_foo in a template\n\/\/ see https:\/\/jbake.org\/docs\/2.6.4\/#configuration for how to configure jBake\n\/\/ other properties listed here might be used in the jBake templates and thus are not\n\/\/ documented in the jBake docs but hopefully in the template docs.\nmicrosite.with {\n \/** start:microsite **\/\n\n \/\/ is your microsite deployed with a context path?\n contextPath = ''\n \/\/ used as title in the template\n title='Microsite'\n \/\/ used in the template for absolute uris\n host='https:\/\/localhost'\n \/\/ configure a port on which your preview server will run\n previewPort = 8881\n\n \/\/project theme\n \/\/site folder relative to the docs folder\n siteFolder = '..\/site'\n\n \/\/ the title of the microsite, displayed in the upper left corner\n title = 'Microsite'\n\n \/\/ the location of the landing page in your docs folder\n landingPage = 'landingpage.gsp'\n\n \/\/ the menu of the microsite. A map of [code:'title'] entries to specify the order and title of the entries.\n \/\/ the codes are autogenerated from the folder names or :jbake-menu: attribute entries from the .adoc file headers\n \/\/ use [code:'-'] to exclude a code from the menu\n menu = [about: 'About', manual: 'User Docs', tasks: 'Tasks', tutorial: 'Tutorial', development: 'For Devs', news: 'News', ADRs: '-', ea: '-', excel: '-', ppt: '-', blog: '-']\n\n \/\/ contact eMail\n footerMail = 'info@docs-as-co.de'\n \/\/ twitter account url\n footerTwitter = 'https:\/\/twitter.com\/doctoolchain'\n \/\/ Stackoverflow QA\n footerSO = 'https:\/\/stackoverflow.com\/questions\/tagged\/doctoolchain'\n \/\/ Github Repository\n footerGithub = 'https:\/\/github.com\/doctoolchain\/doctoolchain'\n \/\/ Slack Channel\n footerSlack = ''\n \/\/ general text for the footer\n footerText = 'built with docToolchain<\/a> and jBake<\/a>
theme:
docsy<\/a><\/small>'\n \/\/ site title if no other title is given\n title = 'docToolchain'\n \/\/\n \/\/ the url to create an issue in github\n issueUrl = 'https:\/\/github.com\/docToolchain\/docToolchain\/issues\/new'\n \/\/\n \/\/ the base url for code files in github\n branch = System.getenv(\"DTC_PROJECT_BRANCH\")\n gitRepoUrl = \"https:\/\/github.com\/doctoolchain\/doctoolchain\/edit\/${branch}\/src\/docs\"\n\n \/** end:microsite **\/\n}\n\n\/\/*****************************************************************************************\n\n\/\/Configuration for exportChangelog\n\nexportChangelog = [:]\n\nchangelog.with {\n\n \/\/ Directory of which the exportChangelog task will export the changelog.\n \/\/ It should be relative to the docDir directory provided in the\n \/\/ gradle.properties file.\n dir = 'src\/docs'\n\n \/\/ Command used to fetch the list of changes.\n \/\/ It should be a single command taking a directory as a parameter.\n \/\/ You cannot use multiple commands with pipe between.\n \/\/ This command will be executed in the directory specified by changelogDir\n \/\/ it the environment inherited from the parent process.\n \/\/ This command should produce asciidoc text directly. The exportChangelog\n \/\/ task does not do any post-processing\n \/\/ of the output of that command.\n \/\/\n \/\/ See also https:\/\/git-scm.com\/docs\/pretty-formats\n cmd = 'git log --pretty=format:%x7c%x20%ad%x20%n%x7c%x20%an%x20%n%x7c%x20%s%x20%n --date=short'\n\n}\n\n\/\/*****************************************************************************************\n\n\/\/tag::confluenceConfig[]\n\/\/Configureation for publishToConfluence\n\nconfluence = [:]\n\n\/\/ 'input' is an array of files to upload to Confluence with the ability\n\/\/ to configure a different parent page for each file.\n\/\/\n\/\/ Attributes\n\/\/ - 'file': absolute or relative path to the asciidoc generated html file to be exported\n\/\/ - 'url': absolute URL to an asciidoc generated html file to be exported\n\/\/ - 'ancestorName' (optional): the name of the parent page in Confluence as string;\n\/\/ this attribute has priority over ancestorId, but if page with given name doesn't exist,\n\/\/ ancestorId will be used as a fallback\n\/\/ - 'ancestorId' (optional): the id of the parent page in Confluence as string; leave this empty\n\/\/ if a new parent shall be created in the space\n\/\/ - 'preambleTitle' (optional): the title of the page containing the preamble (everything\n\/\/ before the first second level heading). Default is 'arc42'\n\/\/\n\/\/ The following four keys can also be used in the global section below\n\/\/ - 'spaceKey' (optional): page specific variable for the key of the confluence space to write to\n\/\/ - 'createSubpages' (optional): page specific variable to determine whether \".sect2\" sections shall be split from the current page into subpages\n\/\/ - 'pagePrefix' (optional): page specific variable, the pagePrefix will be a prefix for the page title and it's sub-pages\n\/\/ use this if you only have access to one confluence space but need to store several\n\/\/ pages with the same title - a different pagePrefix will make them unique\n\/\/ - 'pageSuffix' (optional): same usage as prefix but appended to the title and it's subpages\n\/\/ only 'file' or 'url' is allowed. If both are given, 'url' is ignored\nconfluence.with {\n input = [\n [ file: \"build\/html5\/arc42-template-de.html\" ],\n ]\n\n \/\/ endpoint of the confluenceAPI (REST) to be used\n \/\/ to verify the endpoint, add user\/current and pate it into your browser\n \/\/ you should get a json about your own user\n api = 'https:\/\/[yourServer]\/[context]\/rest\/api\/'\n\n \/\/ Additionally, spaceKey, createSubpages, pagePrefix and pageSuffix can be globally defined here. The assignment in the input array has precedence\n\n \/\/ the key of the confluence space to write to\n spaceKey = 'asciidoc'\n\n \/\/ the title of the page containing the preamble (everything the first second level heading). Default is 'arc42'\n preambleTitle = ''\n\n \/\/ variable to determine whether \".sect2\" sections shall be split from the current page into subpages\n createSubpages = false\n\n \/\/ the pagePrefix will be a prefix for each page title\n \/\/ use this if you only have access to one confluence space but need to store several\n \/\/ pages with the same title - a different pagePrefix will make them unique\n pagePrefix = ''\n\n pageSuffix = ''\n\n \/*\n WARNING: It is strongly recommended to store credentials securely instead of commiting plain text values to your git repository!!!\n\n Tool expects credentials that belong to an account which has the right permissions to to create and edit confluence pages in the given space.\n Credentials can be used in a form of:\n - passed parameters when calling script (-PconfluenceUser=myUsername -PconfluencePass=myPassword) which can be fetched as a secrets on CI\/CD or\n - gradle variables set through gradle properties (uses the 'confluenceUser' and 'confluencePass' keys)\n Often, same credentials are used for Jira & Confluence, in which case it is recommended to pass CLI parameters for both entities as\n -Pusername=myUser -Ppassword=myPassword\n - in case using bearer authentication set token value to the bearerToken\n *\/\n\n \/\/optional API-token to be added in case the credentials are needed for user and password exchange.\n \/\/apikey = \"[API-token]\"\n bearerToken = ''\n\n \/\/ HTML Content that will be included with every page published\n \/\/ directly after the TOC. If left empty no additional content will be\n \/\/ added\n \/\/ extraPageContent = 'This is a generated page, do not edit!<\/ac:rich-text-body><\/ac:structured-macro>\n extraPageContent = ''\n\n \/\/ enable or disable attachment uploads for local file references\n enableAttachments = false\n\n \/\/ default attachmentPrefix = attachment - All files to attach will require to be linked inside the document.\n \/\/ attachmentPrefix = \"attachment\"\n\n\n \/\/ Optional proxy configuration, only used to access Confluence\n \/\/ schema supports http and https\n \/\/ proxy = [host: 'my.proxy.com', port: 1234, schema: 'http']\n}\n\/\/end::confluenceConfig[]\n\/\/*****************************************************************************************\n\/\/tag::exportEAConfig[]\n\/\/Configuration for the export script 'exportEA.vbs'.\n\/\/ The following parameters can be used to change the default behaviour of 'exportEA'.\n\/\/ All parameter are optionally.\n\/\/ Parameter 'connection' allows to select a certain database connection by using the ConnectionString as used for\n\/\/ directly connecting to the project database instead of looking for EAP\/EAPX files inside and below the 'src' folder.\n\/\/ Parameter 'packageFilter' is an array of package GUID's to be used for export. All images inside and in all packages below the package represented by its GUID are exported.\n\/\/ A packageGUID, that is not found in the currently opened project, is silently skipped.\n\/\/ PackageGUID of multiple project files can be mixed in case multiple projects have to be opened.\n\nexportEA.with {\n\/\/ OPTIONAL: Set the connection to a certain project or comment it out to use all project files inside the src folder or its child folder.\n\/\/ connection = \"DBType=1;Connect=Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=[THE_DB_NAME_OF_THE_PROJECT];Data Source=[server_hosting_database.com];LazyLoad=1;\"\n\/\/ OPTIONAL: Add one or multiple packageGUIDs to be used for export. All packages are analysed, if no packageFilter is set.\n\/\/ packageFilter = [\n\/\/ \"{A237ECDE-5419-4d47-AECC-B836999E7AE0}\",\n\/\/ \"{B73FA2FB-267D-4bcd-3D37-5014AD8806D6}\"\n\/\/ ]\n\/\/ OPTIONAL: relative path to base 'docDir' to which the diagrams and notes are to be exported\n\/\/ exportPath = \"src\/docs\/\"\n\/\/ OPTIONAL: relative path to base 'docDir', in which Enterprise Architect project files are searched\n\/\/ searchPath = \"src\/docs\/\"\n\n}\n\/\/end::exportEAConfig[]\n\n\/\/tag::htmlSanityCheckConfig[]\nhtmlSanityCheck.with {\n \/\/sourceDir = \"build\/html5\/site\"\n \/\/checkingResultsDir =\n}\n\/\/end::htmlSanityCheckConfig[]\n\n\/\/tag::jiraConfig[]\n\/\/ Configuration for Jira related tasks\njira = [:]\n\njira.with {\n\n \/\/ endpoint of the JiraAPI (REST) to be used\n api = 'https:\/\/your-jira-instance'\n\n \/*\n WARNING: It is strongly recommended to store credentials securely instead of commiting plain text values to your git repository!!!\n\n Tool expects credentials that belong to an account which has the right permissions to read the JIRA issues for a given project.\n Credentials can be used in a form of:\n - passed parameters when calling script (-PjiraUser=myUsername -PjiraPass=myPassword) which can be fetched as a secrets on CI\/CD or\n - gradle variables set through gradle properties (uses the 'jiraUser' and 'jiraPass' keys)\n Often, Jira & Confluence credentials are the same, in which case it is recommended to pass CLI parameters for both entities as\n -Pusername=myUser -Ppassword=myPassword\n *\/\n\n \/\/ the key of the Jira project\n project = 'PROJECTKEY'\n\n \/\/ the format of the received date time values to parse\n dateTimeFormatParse = \"yyyy-MM-dd'T'H:m:s.SSSz\" \/\/ i.e. 2020-07-24'T'9:12:40.999 CEST\n\n \/\/ the format in which the date time should be saved to output\n dateTimeFormatOutput = \"dd.MM.yyyy HH:mm:ss z\" \/\/ i.e. 24.07.2020 09:02:40 CEST\n\n \/\/ the label to restrict search to\n label =\n\n \/\/ Legacy settings for Jira query. This setting is deprecated & support for it will soon be completely removed. Please use JiraRequests settings\n \/\/jql = \"project='%jiraProject%' AND labels='%jiraLabel%' ORDER BY priority DESC, duedate ASC\"\n\n \/\/ Base filename in which Jira query results should be stored\n resultsFilename = 'JiraTicketsContent'\n\n saveAsciidoc = true \/\/ if true, asciidoc file will be created with *.adoc extension\n saveExcel = true \/\/ if true, Excel file will be created with *.xlsx extension\n\n \/\/ Output folder for this task inside main outputPath\n resultsFolder = 'JiraRequests'\n\n \/*\n List of requests to Jira API:\n These are basically JQL expressions bundled with a filename in which results will be saved.\n User can configure custom fields IDs and name those for column header,\n i.e. customfield_10026:'Story Points' for Jira instance that has custom field with that name and will be saved in a coloumn named \"Story Points\"\n *\/\n requests = [\n new JiraRequest(\n filename:\"File1_Done_issues\",\n jql:\"project='%jiraProject%' AND status='Done' ORDER BY duedate ASC\",\n customfields: [customfield_10026:'Story Points']\n ),\n new JiraRequest(\n filename:'CurrentSprint',\n jql:\"project='%jiraProject%' AND Sprint in openSprints() ORDER BY priority DESC, duedate ASC\",\n customfields: [customfield_10026:'Story Points']\n ),\n ]\n}\n\n@groovy.transform.Immutable\nclass JiraRequest {\n String filename \/\/filename (without extension) of the file in which JQL results will be saved. Extension will be determined automatically for Asciidoc or Excel file\n String jql \/\/ Jira Query Language syntax\n Map customfields \/\/ map of customFieldId:displayName values for Jira fields which don't have default names, i.e. customfield_10026:StoryPoints\n}\n\/\/end::jiraConfig[]\n\n\/\/tag::openApiConfig[]\n\/\/ Configuration for OpenAPI related task\nopenApi = [:]\n\n\/\/ 'specFile' is the name of OpenAPI specification yaml file. Tool expects this file inside working dir (as a filename or relative path with filename)\n\/\/ 'infoUrl' and 'infoEmail' are specification metadata about further info related to the API. By default this values would be filled by openapi-generator plugin placeholders\n\/\/\n\nopenApi.with {\n specFile = 'src\/docs\/petstore-v2.0.yaml' \/\/ i.e. 'petstore.yaml', 'src\/doc\/petstore.yaml'\n infoUrl = 'https:\/\/my-api.company.com'\n infoEmail = 'info@company.com'\n}\n\/\/end::openApiConfig[]\n\n\/\/tag::sprintChangelogConfig[]\n\/\/ Sprint changelog configuration generate changelog lists based on tickets in sprints of an Jira instance.\n\/\/ This feature requires at least Jira API & credentials to be properly set in Jira section of this configuration\nsprintChangelog = [:]\nsprintChangelog.with {\n sprintState = 'closed' \/\/ it is possible to define multiple states, i.e. 'closed, active, future'\n ticketStatus = \"Done, Closed\" \/\/ it is possible to define multiple ticket statuses, i.e. \"Done, Closed, 'in Progress'\"\n\n showAssignee = false\n showTicketStatus = false\n showTicketType = true\n sprintBoardId = 12345 \/\/ Jira instance probably have multiple boards; here it can be defined which board should be used\n\n \/\/ Output folder for this task inside main outputPath\n resultsFolder = 'Sprints'\n\n \/\/ if sprintName is not defined or sprint with that name isn't found, release notes will be created on for all sprints that match sprint state configuration\n sprintName = 'PRJ Sprint 1' \/\/ if sprint with a given sprintName is found, release notes will be created just for that sprint\n allSprintsFilename = 'Sprints_Changelogs' \/\/ Extension will be automatically added.\n}\n\/\/end::sprintChangelogConfig[]\n","avg_line_length":46.3451086957,"max_line_length":214,"alphanum_fraction":0.6902961009} +{"size":813,"ext":"groovy","lang":"Groovy","max_stars_count":3.0,"content":"\/*\n * Copyright 2016 Google, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.netflix.spinnaker.clouddriver.appengine.deploy.exception\n\nimport groovy.transform.InheritConstructors\n\n@InheritConstructors\nclass AppEngineIllegalArgumentExeception extends AppEngineOperationException { }\n","avg_line_length":35.347826087,"max_line_length":80,"alphanum_fraction":0.7761377614} +{"size":3921,"ext":"groovy","lang":"Groovy","max_stars_count":1.0,"content":"package org.openkilda.functionaltests.spec.resilience\n\nimport static groovyx.gpars.GParsPool.withPool\nimport static org.openkilda.functionaltests.extension.tags.Tag.HARDWARE\nimport static org.openkilda.testing.Constants.WAIT_OFFSET\n\nimport org.openkilda.functionaltests.HealthCheckSpecification\nimport org.openkilda.functionaltests.extension.failfast.Tidy\nimport org.openkilda.functionaltests.extension.tags.Tags\nimport org.openkilda.functionaltests.helpers.Wrappers\nimport org.openkilda.messaging.Message\nimport org.openkilda.messaging.info.InfoData\nimport org.openkilda.messaging.info.InfoMessage\nimport org.openkilda.messaging.info.event.IslChangeType\nimport org.openkilda.messaging.info.event.PortChangeType\nimport org.openkilda.messaging.info.event.PortInfoData\n\nimport groovy.util.logging.Slf4j\nimport org.apache.kafka.clients.producer.KafkaProducer\nimport org.apache.kafka.clients.producer.ProducerRecord\nimport org.springframework.beans.factory.annotation.Autowired\nimport org.springframework.beans.factory.annotation.Qualifier\nimport org.springframework.beans.factory.annotation.Value\n\n@Slf4j\nclass StormHeavyLoadSpec extends HealthCheckSpecification {\n\n @Value(\"#{kafkaTopicsConfig.getTopoDiscoTopic()}\")\n String topoDiscoTopic\n\n @Autowired\n @Qualifier(\"kafkaProducerProperties\")\n Properties producerProps\n\n def r = new Random()\n\n \/**\n * Test produces multiple port up\/down messages to the topo.disco kafka topic,\n * expecting that Storm will be able to swallow them and continue to operate.\n *\/\n @Tidy\n @Tags(HARDWARE)\n def \"Storm does not fail under heavy load of topo.disco topic\"() {\n when: \"Produce massive amount of messages into topo.disco topic\"\n def messages = 100000 \/\/total sum of messages of all types produced\n def operations = 2 \/\/port up, port down\n def threads = 10\n def producers = (1..threads).collect { new KafkaProducer<>(producerProps) }\n def isl = topology.islsForActiveSwitches[0]\n withPool(threads) {\n messages.intdiv(threads * operations).times {\n def sw = isl.srcSwitch.dpId\n producers.eachParallel {\n it.send(new ProducerRecord(topoDiscoTopic, sw.toString(),\n buildMessage(new PortInfoData(sw, isl.srcPort, null, PortChangeType.DOWN)).toJson()))\n sleep(1)\n it.send(new ProducerRecord(topoDiscoTopic, sw.toString(),\n buildMessage(new PortInfoData(sw, isl.srcPort, null, PortChangeType.UP)).toJson()))\n }\n }\n }\n\n then: \"Still able to create and delete flows while Storm is swallowing the messages\"\n def checkFlowCreation = {\n def flow = flowHelper.randomFlow(topology.islsForActiveSwitches[1].srcSwitch,\n topology.islsForActiveSwitches[1].dstSwitch)\n flowHelper.addFlow(flow)\n flowHelper.deleteFlow(flow.id)\n sleep(500)\n }\n def endProducing = new Thread({ producers.each({ it.close() }) })\n endProducing.start()\n while (endProducing.isAlive()) {\n checkFlowCreation()\n }\n \/\/check couple more times after producers end sending\n 2.times {\n checkFlowCreation()\n }\n\n and: \"Topology is unchanged at the end\"\n northbound.activeSwitches.size() == topology.activeSwitches.size()\n Wrappers.wait(WAIT_OFFSET * 2 + antiflapCooldown) {\n assert northbound.getAllLinks().findAll { it.state == IslChangeType.DISCOVERED }\n .size() == topology.islsForActiveSwitches.size() * 2\n }\n\n cleanup:\n producers.each { it.close() }\n }\n\n private static Message buildMessage(final InfoData data) {\n return new InfoMessage(data, System.currentTimeMillis(), UUID.randomUUID().toString(), null)\n }\n}\n","avg_line_length":40.84375,"max_line_length":113,"alphanum_fraction":0.687834736} +{"size":2517,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n *\/\n\nimport io.opentelemetry.instrumentation.test.AgentTestTrait\nimport io.opentelemetry.instrumentation.test.base.HttpClientTest\nimport org.apache.commons.httpclient.HttpClient\nimport org.apache.commons.httpclient.HttpMethod\nimport org.apache.commons.httpclient.methods.DeleteMethod\nimport org.apache.commons.httpclient.methods.GetMethod\nimport org.apache.commons.httpclient.methods.HeadMethod\nimport org.apache.commons.httpclient.methods.OptionsMethod\nimport org.apache.commons.httpclient.methods.PostMethod\nimport org.apache.commons.httpclient.methods.PutMethod\nimport org.apache.commons.httpclient.methods.TraceMethod\nimport spock.lang.Shared\n\nclass CommonsHttpClientTest extends HttpClientTest implements AgentTestTrait {\n @Shared\n HttpClient client = new HttpClient()\n\n def setupSpec() {\n client.setConnectionTimeout(CONNECT_TIMEOUT_MS)\n }\n\n @Override\n boolean testCausality() {\n return false\n }\n\n @Override\n HttpMethod buildRequest(String method, URI uri, Map headers) {\n def request\n switch (method) {\n case \"GET\":\n request = new GetMethod(uri.toString())\n break\n case \"PUT\":\n request = new PutMethod(uri.toString())\n break\n case \"POST\":\n request = new PostMethod(uri.toString())\n break\n case \"HEAD\":\n request = new HeadMethod(uri.toString())\n break\n case \"DELETE\":\n request = new DeleteMethod(uri.toString())\n break\n case \"OPTIONS\":\n request = new OptionsMethod(uri.toString())\n break\n case \"TRACE\":\n request = new TraceMethod(uri.toString())\n break\n default:\n throw new RuntimeException(\"Unsupported method: \" + method)\n }\n headers.each { request.setRequestHeader(it.key, it.value) }\n return request\n }\n\n @Override\n int sendRequest(HttpMethod request, String method, URI uri, Map headers) {\n try {\n client.executeMethod(request)\n return request.getStatusCode()\n } finally {\n request.releaseConnection()\n }\n }\n\n @Override\n boolean testRedirects() {\n \/\/ Generates 4 spans\n false\n }\n\n @Override\n boolean testReusedRequest() {\n \/\/ apache commons throws an exception if the request is reused without being recycled first\n \/\/ at which point this test is not useful (and requires re-populating uri)\n false\n }\n\n @Override\n boolean testCallback() {\n false\n }\n}\n","avg_line_length":27.3586956522,"max_line_length":95,"alphanum_fraction":0.7036154152} +{"size":13082,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Copyright 2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.gradle.internal.component.external.model\n\nimport com.google.common.collect.ImmutableListMultimap\nimport org.gradle.api.Action\nimport org.gradle.api.artifacts.DependenciesMetadata\nimport org.gradle.api.attributes.Attribute\nimport org.gradle.api.internal.artifacts.DefaultImmutableModuleIdentifierFactory\nimport org.gradle.api.internal.artifacts.DefaultModuleIdentifier\nimport org.gradle.api.internal.artifacts.DefaultModuleVersionIdentifier\nimport org.gradle.api.internal.artifacts.dependencies.DefaultMutableVersionConstraint\nimport org.gradle.api.internal.artifacts.repositories.metadata.IvyMutableModuleMetadataFactory\nimport org.gradle.api.internal.artifacts.repositories.metadata.MavenMutableModuleMetadataFactory\nimport org.gradle.api.internal.artifacts.repositories.resolver.DependencyConstraintMetadataImpl\nimport org.gradle.api.internal.artifacts.repositories.resolver.DirectDependencyMetadataImpl\nimport org.gradle.api.internal.attributes.DefaultAttributesSchema\nimport org.gradle.api.internal.attributes.ImmutableAttributes\nimport org.gradle.api.internal.notations.DependencyMetadataNotationParser\nimport org.gradle.api.specs.Spec\nimport org.gradle.api.specs.Specs\nimport org.gradle.internal.component.external.descriptor.MavenScope\nimport org.gradle.internal.component.external.model.ivy.IvyDependencyDescriptor\nimport org.gradle.internal.component.external.model.maven.MavenDependencyDescriptor\nimport org.gradle.internal.component.external.model.maven.MavenDependencyType\nimport org.gradle.internal.component.model.ComponentAttributeMatcher\nimport org.gradle.internal.component.model.LocalComponentDependencyMetadata\nimport org.gradle.internal.component.model.VariantResolveMetadata\nimport org.gradle.internal.reflect.DirectInstantiator\nimport org.gradle.testing.internal.util.Specification\nimport org.gradle.util.TestUtil\nimport org.gradle.util.internal.SimpleMapInterner\nimport spock.lang.Shared\nimport spock.lang.Unroll\n\nimport static org.gradle.internal.component.external.model.DefaultModuleComponentSelector.newSelector\n\nabstract class AbstractDependencyMetadataRulesTest extends Specification {\n def instantiator = DirectInstantiator.INSTANCE\n def notationParser = DependencyMetadataNotationParser.parser(instantiator, DirectDependencyMetadataImpl, SimpleMapInterner.notThreadSafe())\n def constraintNotationParser = DependencyMetadataNotationParser.parser(instantiator, DependencyConstraintMetadataImpl, SimpleMapInterner.notThreadSafe())\n\n @Shared versionIdentifier = new DefaultModuleVersionIdentifier(\"org.test\", \"producer\", \"1.0\")\n @Shared componentIdentifier = DefaultModuleComponentIdentifier.newId(versionIdentifier)\n @Shared attributes = TestUtil.attributesFactory().of(Attribute.of(\"someAttribute\", String), \"someValue\")\n @Shared schema = new DefaultAttributesSchema(new ComponentAttributeMatcher(), TestUtil.instantiatorFactory(), TestUtil.valueSnapshotter())\n @Shared mavenMetadataFactory = new MavenMutableModuleMetadataFactory(new DefaultImmutableModuleIdentifierFactory(), TestUtil.attributesFactory(), TestUtil.objectInstantiator(), TestUtil.featurePreviews(true))\n @Shared ivyMetadataFactory = new IvyMutableModuleMetadataFactory(new DefaultImmutableModuleIdentifierFactory(), TestUtil.attributesFactory())\n @Shared defaultVariant\n\n protected static VariantMetadataRules.VariantAction variantAction(String variantName, Action action) {\n Spec spec = variantName ? { it.name == variantName } as Spec : Specs.satisfyAll()\n new VariantMetadataRules.VariantAction(spec, action)\n }\n\n abstract boolean addAllDependenciesAsConstraints()\n\n abstract void doAddDependencyMetadataRule(MutableModuleComponentResolveMetadata metadataImplementation, String variantName = null, Action action)\n\n boolean supportedInMetadata(String metadata) {\n !addAllDependenciesAsConstraints() || metadata != \"ivy\" \/\/ivy does not support dependency constraints or optional dependencies\n }\n\n private ivyComponentMetadata(String[] deps) {\n def dependencies\n if (addAllDependenciesAsConstraints()) {\n dependencies = [] \/\/not supported in Ivy metadata\n } else {\n dependencies = deps.collect { name ->\n new IvyDependencyDescriptor(newSelector(DefaultModuleIdentifier.newId(\"org.test\", name), \"1.0\"), ImmutableListMultimap.of(\"default\", \"default\"))\n }\n }\n ivyMetadataFactory.create(componentIdentifier, dependencies)\n }\n private mavenComponentMetadata(String[] deps) {\n def dependencies = deps.collect { name ->\n MavenDependencyType type = addAllDependenciesAsConstraints() ? MavenDependencyType.OPTIONAL_DEPENDENCY : MavenDependencyType.DEPENDENCY\n new MavenDependencyDescriptor(MavenScope.Compile, type, newSelector(DefaultModuleIdentifier.newId(\"org.test\", name), \"1.0\"), null, [])\n }\n mavenMetadataFactory.create(componentIdentifier, dependencies)\n }\n private gradleComponentMetadata(String[] deps) {\n def metadata = mavenMetadataFactory.create(componentIdentifier)\n \/\/gradle metadata is distinguished from maven POM metadata by explicitly defining variants\n defaultVariant = metadata.addVariant(\"default\", attributes)\n deps.each { name ->\n if (addAllDependenciesAsConstraints()) {\n defaultVariant.addDependencyConstraint(\"org.test\", name, new DefaultMutableVersionConstraint(\"1.0\"), null, ImmutableAttributes.EMPTY)\n } else {\n defaultVariant.addDependency(\"org.test\", name, new DefaultMutableVersionConstraint(\"1.0\"), [], null, ImmutableAttributes.EMPTY)\n }\n }\n metadata\n }\n\n @Unroll\n def \"dependency metadata rules are evaluated once and lazily for #metadataType metadata\"() {\n given:\n def rule = Mock(Action)\n\n when:\n doAddDependencyMetadataRule(metadataImplementation, rule)\n def metadata = metadataImplementation.asImmutable()\n\n then:\n 0 * rule.execute(_)\n\n when:\n selectTargetConfigurationMetadata(metadata).dependencies\n\n then:\n 1 * rule.execute(_)\n\n when:\n selectTargetConfigurationMetadata(metadata).dependencies\n selectTargetConfigurationMetadata(metadata).dependencies\n selectTargetConfigurationMetadata(metadata).dependencies\n\n then:\n 0 * rule.execute(_)\n\n where:\n metadataType | metadataImplementation\n \"maven\" | mavenComponentMetadata()\n \"ivy\" | ivyComponentMetadata()\n \"gradle\" | gradleComponentMetadata()\n }\n\n @Unroll\n def \"dependency metadata rules are not evaluated if their variant is not selected for #metadataType metadata\"() {\n given:\n def rule = Mock(Action)\n\n when:\n doAddDependencyMetadataRule(metadataImplementation, \"anotherVariant\", rule)\n selectTargetConfigurationMetadata(metadataImplementation).dependencies\n\n then:\n 0 * rule.execute(_)\n\n where:\n metadataType | metadataImplementation\n \"maven\" | mavenComponentMetadata()\n \"ivy\" | ivyComponentMetadata()\n \"gradle\" | gradleComponentMetadata()\n }\n\n @Unroll\n def \"dependencies of selected variant are accessible in dependency metadata rule for #metadataType metadata\"() {\n given:\n def rule = { dependencies ->\n if (supportedInMetadata(metadataType)) {\n assert dependencies.size() == 2\n assert dependencies[0].name == \"dep1\"\n assert dependencies[1].name == \"dep2\"\n } else {\n assert dependencies.empty\n }\n }\n\n when:\n doAddDependencyMetadataRule(metadataImplementation, rule)\n def dependencies = selectTargetConfigurationMetadata(metadataImplementation).dependencies\n\n then:\n if (supportedInMetadata(metadataType)) {\n assert dependencies.size() == 2\n assert dependencies[0].constraint == addAllDependenciesAsConstraints()\n assert dependencies[1].constraint == addAllDependenciesAsConstraints()\n } else {\n assert dependencies.empty\n }\n\n where:\n metadataType | metadataImplementation\n \"maven\" | mavenComponentMetadata(\"dep1\", \"dep2\")\n \"ivy\" | ivyComponentMetadata(\"dep1\", \"dep2\")\n \"gradle\" | gradleComponentMetadata(\"dep1\", \"dep2\")\n }\n\n @Unroll\n def \"dependencies of selected variant are modifiable in dependency metadata rule for #metadataType metadata\"() {\n given:\n def rule = { dependencies ->\n if (supportedInMetadata(metadataType)) {\n assert dependencies.size() == 1\n dependencies[0].version {\n it.strictly \"2.0\"\n it.reject \"[3.0,)\"\n }\n } else {\n assert dependencies.empty\n }\n }\n\n when:\n doAddDependencyMetadataRule(metadataImplementation, rule)\n def dependencies = selectTargetConfigurationMetadata(metadataImplementation).dependencies\n\n then:\n if (supportedInMetadata(metadataType)) {\n assert dependencies[0].selector.version == \"2.0\"\n assert dependencies[0].selector.versionConstraint.strictVersion == \"2.0\"\n assert dependencies[0].selector.versionConstraint.rejectedVersions[0] == \"[3.0,)\"\n assert dependencies[0].constraint == addAllDependenciesAsConstraints()\n } else {\n assert dependencies.empty\n }\n\n where:\n metadataType | metadataImplementation\n \"maven\" | mavenComponentMetadata(\"toModify\")\n \"ivy\" | ivyComponentMetadata(\"toModify\")\n \"gradle\" | gradleComponentMetadata(\"toModify\")\n }\n\n @Unroll\n def \"dependencies added in dependency metadata rules are added to dependency list for #metadataType metadata\"() {\n given:\n def rule = { dependencies ->\n dependencies.add(\"org.test:added:1.0\")\n }\n\n when:\n doAddDependencyMetadataRule(metadataImplementation, rule)\n def dependencies = selectTargetConfigurationMetadata(metadataImplementation).dependencies\n\n then:\n dependencies.collect { it.selector } == [newSelector(DefaultModuleIdentifier.newId(\"org.test\", \"added\"), \"1.0\") ]\n\n where:\n metadataType | metadataImplementation\n \"maven\" | mavenComponentMetadata()\n \"ivy\" | ivyComponentMetadata()\n \"gradle\" | gradleComponentMetadata()\n }\n\n @Unroll\n def \"dependencies removed in dependency metadata rules are removed from dependency list for #metadataType metadata\"() {\n given:\n def rule = { dependencies ->\n assert dependencies.size() == (supportedInMetadata(metadataType) ? 1 : 0)\n dependencies.removeAll { it.name == \"toRemove\" }\n }\n\n when:\n doAddDependencyMetadataRule(metadataImplementation, rule)\n def dependencies = selectTargetConfigurationMetadata(metadataImplementation).dependencies\n\n then:\n dependencies.empty\n\n where:\n metadataType | metadataImplementation\n \"maven\" | mavenComponentMetadata(\"toRemove\")\n \"ivy\" | ivyComponentMetadata(\"toRemove\")\n \"gradle\" | gradleComponentMetadata(\"toRemove\")\n }\n\n def selectTargetConfigurationMetadata(MutableModuleComponentResolveMetadata targetComponent) {\n selectTargetConfigurationMetadata(targetComponent.asImmutable())\n }\n\n def selectTargetConfigurationMetadata(ModuleComponentResolveMetadata immutable) {\n def componentIdentifier = DefaultModuleComponentIdentifier.newId(DefaultModuleIdentifier.newId(\"org.test\", \"consumer\"), \"1.0\")\n def consumerIdentifier = DefaultModuleVersionIdentifier.newId(componentIdentifier)\n def componentSelector = newSelector(consumerIdentifier.module, new DefaultMutableVersionConstraint(consumerIdentifier.version))\n def consumer = new LocalComponentDependencyMetadata(componentIdentifier, componentSelector, \"default\", attributes, ImmutableAttributes.EMPTY, null, [] as List, [], false, false, true, false, null)\n\n consumer.selectConfigurations(attributes, immutable, schema)[0]\n }\n}\n","avg_line_length":45.5818815331,"max_line_length":212,"alphanum_fraction":0.716022015} +{"size":3936,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"package graphql.execution.preparsed\n\nimport graphql.ErrorType\nimport graphql.ExecutionInput\nimport graphql.GraphQL\nimport graphql.StarWarsSchema\nimport graphql.execution.SimpleExecutionStrategy\nimport graphql.execution.instrumentation.TestingInstrumentation\nimport spock.lang.Specification\n\nclass PreparsedDocumentProviderTest extends Specification {\n\n def 'Preparse of simple serial execution'() {\n given:\n\n def query = \"\"\"\n query HeroNameAndFriendsQuery {\n hero {\n id\n }\n }\n \"\"\"\n\n def expected = [\n \"start:execution\",\n\n \"start:parse\",\n \"end:parse\",\n\n \"start:validation\",\n \"end:validation\",\n\n \"start:data-fetch\",\n\n \"start:field-hero\",\n \"start:fetch-hero\",\n \"end:fetch-hero\",\n\n \"start:field-id\",\n \"start:fetch-id\",\n \"end:fetch-id\",\n \"end:field-id\",\n\n \"end:field-hero\",\n\n \"end:data-fetch\",\n\n \"end:execution\",\n ]\n\n def expectedPreparsed = [\n \"start:execution\",\n\n \"start:data-fetch\",\n\n \"start:field-hero\",\n \"start:fetch-hero\",\n \"end:fetch-hero\",\n\n \"start:field-id\",\n \"start:fetch-id\",\n \"end:fetch-id\",\n \"end:field-id\",\n\n \"end:field-hero\",\n\n \"end:data-fetch\",\n\n \"end:execution\",\n ]\n\n when:\n\n def instrumentation = new TestingInstrumentation()\n def instrumentationPreparsed = new TestingInstrumentation()\n def preparsedCache = new TestingPreparsedDocumentProvider()\n\n def strategy = new SimpleExecutionStrategy()\n def data1 = GraphQL.newGraphQL(StarWarsSchema.starWarsSchema)\n .queryExecutionStrategy(strategy)\n .instrumentation(instrumentation)\n .preparsedDocumentProvider(preparsedCache)\n .build()\n .execute(ExecutionInput.newExecutionInput().query(query).build()).data\n\n def data2 = GraphQL.newGraphQL(StarWarsSchema.starWarsSchema)\n .queryExecutionStrategy(strategy)\n .instrumentation(instrumentationPreparsed)\n .preparsedDocumentProvider(preparsedCache)\n .build()\n .execute(ExecutionInput.newExecutionInput().query(query).build()).data\n\n\n then:\n\n instrumentation.executionList == expected\n instrumentationPreparsed.executionList == expectedPreparsed\n data1 == data2\n }\n\n\n def \"Preparsed query with validation failure\"() {\n given: \"A query on non existing field\"\n\n def query = \"\"\"\n query HeroNameAndFriendsQuery {\n heroXXXX {\n id\n }\n }\n \"\"\"\n\n when: \"Executed the query twice\"\n def preparsedCache = new TestingPreparsedDocumentProvider()\n\n def result1 = GraphQL.newGraphQL(StarWarsSchema.starWarsSchema)\n .preparsedDocumentProvider(preparsedCache)\n .build()\n .execute(ExecutionInput.newExecutionInput().query(query).build())\n\n def result2 = GraphQL.newGraphQL(StarWarsSchema.starWarsSchema)\n .preparsedDocumentProvider(preparsedCache)\n .build()\n .execute(ExecutionInput.newExecutionInput().query(query).build())\n\n then: \"Both the first and the second result should give the same validation error\"\n result1.errors.size() == 1\n result2.errors.size() == 1\n result1.errors == result2.errors\n\n result1.errors[0].errorType == ErrorType.ValidationError\n result1.errors[0].errorType == result2.errors[0].errorType\n }\n}\n","avg_line_length":29.1555555556,"max_line_length":90,"alphanum_fraction":0.5619918699} +{"size":3323,"ext":"groovy","lang":"Groovy","max_stars_count":2.0,"content":"\/*\n* Copyright 2019 Yak.Works - Licensed under the Apache License, Version 2.0 (the \"License\")\n* You may obtain a copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\/\npackage yakworks.jasper\n\nimport groovy.transform.CompileStatic\nimport groovy.util.logging.Slf4j\n\nimport org.grails.web.servlet.mvc.GrailsWebRequest\nimport org.springframework.web.servlet.LocaleResolver\nimport org.springframework.web.servlet.View\n\nimport grails.core.GrailsApplication\nimport yakworks.jasper.spring.JasperView\nimport yakworks.jasper.spring.JasperViewResolver\n\n\/**\n * Retrieves and processes view report for jasper tempalates.\n *\n * @author Joshua Burnett\n *\/\n@CompileStatic\n@Slf4j\nclass JasperViewService {\n\n static transactional = false\n\n GrailsApplication grailsApplication\n LocaleResolver localeResolver\n JasperViewResolver jasperViewResolver\n\n View getView(String viewName, Locale locale = null) {\n locale = locale ?: getLocale()\n \/\/GrailsWebEnvironment.bindRequestIfNull(grailsApplication.mainContext)\n return jasperViewResolver.resolveViewName(viewName, locale)\n }\n\n \/**\n * Calls getView to grab the jasper template and and then passes to render(view,model...)\n *\/\n Writer render(String viewName, Map model, Writer writer = new CharArrayWriter()) {\n \/\/GrailsWebEnvironment.bindRequestIfNull(grailsApplication.mainContext, writer) -- xxx why do we need this ?\n JasperView view = (JasperView) jasperViewResolver.resolveViewName(viewName, getLocale())\n if (!view) {\n throw new IllegalArgumentException(\"The ftl view [${viewName}] could not be found\")\n }\n render(view, model, writer)\n }\n\n \/**\n * processes the jasper report template in the View.\n * sets the plugin thread local if passed in and bind a request if none exists before processing.\n *\n * @param view JasperView that holds the template\n * @param model the hash model the should be passed into the freemarker tempalate\n * @param writer (optional) a writer if you have one. a CharArrayWriter will be created by default.\n * @return the writer that was passed in.\n *\/\n Writer render(JasperView view, Map model, Writer writer = new CharArrayWriter()) {\n\n if (!view) {\n throw new IllegalArgumentException(\"The 'view' argument cannot be null\")\n }\n log.debug(\"primary render called with view : $view \")\n \/\/ Consolidate static and dynamic model attributes.\n Map attributesMap = view.attributesMap\n int mapSize = attributesMap.size() + (model != null ? model.size() : 0)\n Map mergedModel = new HashMap(mapSize)\n mergedModel.putAll(attributesMap)\n if (model) mergedModel.putAll(model)\n \/\/\/GrailsWebEnvironment.bindRequestIfNull(grailsApplication.mainContext, writer) XXX why do we need this ?\n \/\/view render\n return writer\n\n }\n\n \/**\n * returns the local by using the localResolver and the webrequest from RequestContextHolder.getRequestAttributes()\n *\/\n\n Locale getLocale() {\n def locale\n def request = GrailsWebRequest.lookup()?.currentRequest\n locale = localeResolver?.resolveLocale(request)\n if (locale == null) {\n locale = Locale.default\n }\n return locale\n }\n}\n","avg_line_length":36.1195652174,"max_line_length":119,"alphanum_fraction":0.6999699067} +{"size":50481,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\npackage org.elasticsearch.gradle.test\n\nimport org.apache.tools.ant.DefaultLogger\nimport org.apache.tools.ant.taskdefs.condition.Os\nimport org.elasticsearch.gradle.BuildPlugin\nimport org.elasticsearch.gradle.LoggedExec\nimport org.elasticsearch.gradle.Version\nimport org.elasticsearch.gradle.VersionCollection\nimport org.elasticsearch.gradle.VersionProperties\nimport org.elasticsearch.gradle.plugin.PluginBuildPlugin\nimport org.elasticsearch.gradle.plugin.PluginPropertiesExtension\nimport org.gradle.api.AntBuilder\nimport org.gradle.api.DefaultTask\nimport org.gradle.api.GradleException\nimport org.gradle.api.Project\nimport org.gradle.api.Task\nimport org.gradle.api.artifacts.Configuration\nimport org.gradle.api.artifacts.Dependency\nimport org.gradle.api.file.FileCollection\nimport org.gradle.api.logging.Logger\nimport org.gradle.api.tasks.Copy\nimport org.gradle.api.tasks.Delete\nimport org.gradle.api.tasks.Exec\n\nimport java.nio.charset.StandardCharsets\nimport java.nio.file.Paths\nimport java.util.concurrent.TimeUnit\nimport java.util.stream.Collectors\n\/**\n * A helper for creating tasks to build a cluster that is used by a task, and tear down the cluster when the task is finished.\n *\/\nclass ClusterFormationTasks {\n\n \/**\n * Adds dependent tasks to the given task to start and stop a cluster with the given configuration.\n *\n * Returns a list of NodeInfo objects for each node in the cluster.\n *\/\n static List setup(Project project, String prefix, Task runner, ClusterConfiguration config) {\n File sharedDir = new File(project.buildDir, \"cluster\/shared\")\n Object startDependencies = config.dependencies\n \/* First, if we want a clean environment, we remove everything in the\n * shared cluster directory to ensure there are no leftovers in repos\n * or anything in theory this should not be necessary but repositories\n * are only deleted in the cluster-state and not on-disk such that\n * snapshots survive failures \/ test runs and there is no simple way\n * today to fix that. *\/\n if (config.cleanShared) {\n Task cleanup = project.tasks.create(\n name: \"${prefix}#prepareCluster.cleanShared\",\n type: Delete,\n dependsOn: startDependencies) {\n delete sharedDir\n doLast {\n sharedDir.mkdirs()\n }\n }\n startDependencies = cleanup\n }\n List startTasks = []\n List nodes = []\n if (config.numNodes < config.numBwcNodes) {\n throw new GradleException(\"numNodes must be >= numBwcNodes [${config.numNodes} < ${config.numBwcNodes}]\")\n }\n if (config.numBwcNodes > 0 && config.bwcVersion == null) {\n throw new GradleException(\"bwcVersion must not be null if numBwcNodes is > 0\")\n }\n \/\/ this is our current version distribution configuration we use for all kinds of REST tests etc.\n Configuration currentDistro = project.configurations.create(\"${prefix}_elasticsearchDistro\")\n Configuration bwcDistro = project.configurations.create(\"${prefix}_elasticsearchBwcDistro\")\n Configuration bwcPlugins = project.configurations.create(\"${prefix}_elasticsearchBwcPlugins\")\n if (System.getProperty('tests.distribution', 'oss') == 'integ-test-zip') {\n throw new Exception(\"tests.distribution=integ-test-zip is not supported\")\n }\n configureDistributionDependency(project, config.distribution, currentDistro, VersionProperties.elasticsearch)\n boolean hasBwcNodes = config.numBwcNodes > 0\n if (hasBwcNodes) {\n if (config.bwcVersion == null) {\n throw new IllegalArgumentException(\"Must specify bwcVersion when numBwcNodes > 0\")\n }\n \/\/ if we have a cluster that has a BWC cluster we also need to configure a dependency on the BWC version\n \/\/ this version uses the same distribution etc. and only differs in the version we depend on.\n \/\/ from here on everything else works the same as if it's the current version, we fetch the BWC version\n \/\/ from mirrors using gradles built-in mechanism etc.\n\n configureDistributionDependency(project, config.distribution, bwcDistro, config.bwcVersion.toString())\n for (Map.Entry entry : config.plugins.entrySet()) {\n configureBwcPluginDependency(project, entry.getValue(), bwcPlugins, config.bwcVersion)\n }\n bwcDistro.resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS)\n bwcPlugins.resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS)\n }\n for (int i = 0; i < config.numNodes; i++) {\n \/\/ we start N nodes and out of these N nodes there might be M bwc nodes.\n \/\/ for each of those nodes we might have a different configuration\n Configuration distro\n String elasticsearchVersion\n if (i < config.numBwcNodes) {\n elasticsearchVersion = config.bwcVersion.toString()\n if (project.bwcVersions.unreleased.contains(config.bwcVersion)) {\n elasticsearchVersion += \"-SNAPSHOT\"\n }\n distro = bwcDistro\n } else {\n elasticsearchVersion = VersionProperties.elasticsearch\n distro = currentDistro\n }\n NodeInfo node = new NodeInfo(config, i, project, prefix, elasticsearchVersion, sharedDir)\n nodes.add(node)\n Closure writeConfigSetup\n Object dependsOn\n if (node.nodeVersion.onOrAfter(\"6.5.0\")) {\n writeConfigSetup = { Map esConfig ->\n if (config.getAutoSetHostsProvider()) {\n \/\/ Don't force discovery provider if one is set by the test cluster specs already\n if (esConfig.containsKey('discovery.zen.hosts_provider') == false) {\n esConfig['discovery.zen.hosts_provider'] = 'file'\n }\n esConfig['discovery.zen.ping.unicast.hosts'] = []\n }\n boolean supportsInitialMasterNodes = hasBwcNodes == false || config.bwcVersion.onOrAfter(\"7.0.0\")\n if (esConfig['discovery.type'] == null && config.getAutoSetInitialMasterNodes() && supportsInitialMasterNodes) {\n esConfig['cluster.initial_master_nodes'] = nodes.stream().map({ n ->\n if (n.config.settings['node.name'] == null) {\n return \"node-\" + n.nodeNum\n } else {\n return n.config.settings['node.name']\n }\n }).collect(Collectors.toList())\n }\n esConfig\n }\n dependsOn = startDependencies\n } else {\n dependsOn = startTasks.empty ? startDependencies : startTasks.get(0)\n writeConfigSetup = { Map esConfig ->\n String unicastTransportUri = node.config.unicastTransportUri(nodes.get(0), node, project.createAntBuilder())\n if (unicastTransportUri == null) {\n esConfig['discovery.zen.ping.unicast.hosts'] = []\n } else {\n esConfig['discovery.zen.ping.unicast.hosts'] = \"\\\"${unicastTransportUri}\\\"\"\n }\n esConfig\n }\n }\n startTasks.add(configureNode(project, prefix, runner, dependsOn, node, config, distro, writeConfigSetup))\n }\n\n Task wait = configureWaitTask(\"${prefix}#wait\", project, nodes, startTasks, config.nodeStartupWaitSeconds)\n runner.dependsOn(wait)\n\n return nodes\n }\n\n \/** Adds a dependency on the given distribution *\/\n static void configureDistributionDependency(Project project, String distro, Configuration configuration, String elasticsearchVersion) {\n if (distro.equals(\"integ-test-zip\")) {\n \/\/ short circuit integ test so it doesn't complicate the rest of the distribution setup below\n project.dependencies.add(configuration.name,\n \"org.elasticsearch.distribution.integ-test-zip:elasticsearch:${elasticsearchVersion}@zip\")\n return\n }\n \/\/ TEMP HACK\n \/\/ The oss docs CI build overrides the distro on the command line. This hack handles backcompat until CI is updated.\n if (distro.equals('oss-zip')) {\n distro = 'oss'\n }\n if (distro.equals('zip')) {\n distro = 'default'\n }\n \/\/ END TEMP HACK\n if (['oss', 'default'].contains(distro) == false) {\n throw new GradleException(\"Unknown distribution: ${distro} in project ${project.path}\")\n }\n Version version = Version.fromString(elasticsearchVersion)\n String os = getOs()\n String classifier = \"${os}-x86_64\"\n String packaging = os.equals('windows') ? 'zip' : 'tar.gz'\n String artifactName = 'elasticsearch'\n if (distro.equals('oss') && Version.fromString(elasticsearchVersion).onOrAfter('6.3.0')) {\n artifactName += '-oss'\n }\n Object dependency\n String snapshotProject = \"${os}-${os.equals('windows') ? 'zip' : 'tar'}\"\n if (version.before(\"7.0.0\")) {\n snapshotProject = \"zip\"\n }\n if (distro.equals(\"oss\")) {\n snapshotProject = \"oss-\" + snapshotProject\n }\n boolean internalBuild = project.hasProperty('bwcVersions')\n VersionCollection.UnreleasedVersionInfo unreleasedInfo = null\n if (project.hasProperty('bwcVersions')) {\n \/\/ NOTE: leniency is needed for external plugin authors using build-tools. maybe build the version compat info into build-tools?\n unreleasedInfo = project.bwcVersions.unreleasedInfo(version)\n }\n if (unreleasedInfo != null) {\n dependency = project.dependencies.project(\n path: \":distribution:bwc:${unreleasedInfo.gradleProjectName}\", configuration: snapshotProject)\n } else if (internalBuild && elasticsearchVersion.equals(VersionProperties.elasticsearch)) {\n dependency = project.dependencies.project(path: \":distribution:archives:${snapshotProject}\")\n } else {\n if (version.before('7.0.0')) {\n classifier = \"\" \/\/ for bwc, before we had classifiers\n }\n \/\/ group does not matter as it is not used when we pull from the ivy repo that points to the download service\n dependency = \"dnm:${artifactName}:${elasticsearchVersion}${classifier}@${packaging}\"\n }\n project.dependencies.add(configuration.name, dependency)\n }\n\n \/** Adds a dependency on a different version of the given plugin, which will be retrieved using gradle's dependency resolution *\/\n static void configureBwcPluginDependency(Project project, Object plugin, Configuration configuration, Version elasticsearchVersion) {\n if (plugin instanceof Project) {\n Project pluginProject = (Project)plugin\n verifyProjectHasBuildPlugin(configuration.name, elasticsearchVersion, project, pluginProject)\n final String pluginName = findPluginName(pluginProject)\n project.dependencies.add(configuration.name, \"org.elasticsearch.plugin:${pluginName}:${elasticsearchVersion}@zip\")\n } else {\n project.dependencies.add(configuration.name, \"${plugin}@zip\")\n }\n }\n\n \/**\n * Adds dependent tasks to start an elasticsearch cluster before the given task is executed,\n * and stop it after it has finished executing.\n *\n * The setup of the cluster involves the following:\n *
    \n *
  1. Cleanup the extraction directory<\/li>\n *
  2. Extract a fresh copy of elasticsearch<\/li>\n *
  3. Write an elasticsearch.yml config file<\/li>\n *
  4. Copy plugins that will be installed to a temporary dir (which contains spaces)<\/li>\n *
  5. Install plugins<\/li>\n *
  6. Run additional setup commands<\/li>\n *
  7. Start elasticsearch
  8. \n * <\/ol>\n *\n * @return a task which starts the node.\n *\/\n static Task configureNode(Project project, String prefix, Task runner, Object dependsOn, NodeInfo node, ClusterConfiguration config,\n Configuration distribution, Closure writeConfig) {\n\n \/\/ tasks are chained so their execution order is maintained\n Task setup = project.tasks.create(name: taskName(prefix, node, 'clean'), type: Delete, dependsOn: dependsOn) {\n delete node.homeDir\n delete node.cwd\n }\n setup = project.tasks.create(name: taskName(prefix, node, 'createCwd'), type: DefaultTask, dependsOn: setup) {\n doLast {\n node.cwd.mkdirs()\n }\n outputs.dir node.cwd\n }\n setup = configureCheckPreviousTask(taskName(prefix, node, 'checkPrevious'), project, setup, node)\n setup = configureStopTask(taskName(prefix, node, 'stopPrevious'), project, setup, node)\n setup = configureExtractTask(taskName(prefix, node, 'extract'), project, setup, node, distribution)\n setup = configureWriteConfigTask(taskName(prefix, node, 'configure'), project, setup, node, writeConfig)\n setup = configureCreateKeystoreTask(taskName(prefix, node, 'createKeystore'), project, setup, node)\n setup = configureAddKeystoreSettingTasks(prefix, project, setup, node)\n setup = configureAddKeystoreFileTasks(prefix, project, setup, node)\n\n if (node.config.plugins.isEmpty() == false) {\n if (node.nodeVersion == Version.fromString(VersionProperties.elasticsearch)) {\n setup = configureCopyPluginsTask(taskName(prefix, node, 'copyPlugins'), project, setup, node, prefix)\n } else {\n setup = configureCopyBwcPluginsTask(taskName(prefix, node, 'copyBwcPlugins'), project, setup, node, prefix)\n }\n }\n\n \/\/ install modules\n for (Project module : node.config.modules) {\n String actionName = pluginTaskName('install', module.name, 'Module')\n setup = configureInstallModuleTask(taskName(prefix, node, actionName), project, setup, node, module)\n }\n\n \/\/ install plugins\n for (String pluginName : node.config.plugins.keySet()) {\n String actionName = pluginTaskName('install', pluginName, 'Plugin')\n setup = configureInstallPluginTask(taskName(prefix, node, actionName), project, setup, node, pluginName, prefix)\n }\n\n \/\/ sets up any extra config files that need to be copied over to the ES instance;\n \/\/ its run after plugins have been installed, as the extra config files may belong to plugins\n setup = configureExtraConfigFilesTask(taskName(prefix, node, 'extraConfig'), project, setup, node)\n\n \/\/ extra setup commands\n for (Map.Entry command : node.config.setupCommands.entrySet()) {\n \/\/ the first argument is the actual script name, relative to home\n Object[] args = command.getValue().clone()\n final Object commandPath\n if (Os.isFamily(Os.FAMILY_WINDOWS)) {\n \/*\n * We have to delay building the string as the path will not exist during configuration which will fail on Windows due to\n * getting the short name requiring the path to already exist. Note that we have to capture the value of arg[0] now\n * otherwise we would stack overflow later since arg[0] is replaced below.\n *\/\n String argsZero = args[0]\n commandPath = \"${-> Paths.get(NodeInfo.getShortPathName(node.homeDir.toString())).resolve(argsZero.toString()).toString()}\"\n } else {\n commandPath = node.homeDir.toPath().resolve(args[0].toString()).toString()\n }\n args[0] = commandPath\n setup = configureExecTask(taskName(prefix, node, command.getKey()), project, setup, node, args)\n }\n\n Task start = configureStartTask(taskName(prefix, node, 'start'), project, setup, node)\n\n if (node.config.daemonize) {\n Task stop = configureStopTask(taskName(prefix, node, 'stop'), project, [], node)\n \/\/ if we are running in the background, make sure to stop the server when the task completes\n runner.finalizedBy(stop)\n start.finalizedBy(stop)\n for (Object dependency : config.dependencies) {\n if (dependency instanceof Fixture) {\n def depStop = ((Fixture)dependency).stopTask\n runner.finalizedBy(depStop)\n start.finalizedBy(depStop)\n }\n }\n }\n return start\n }\n\n \/** Adds a task to extract the elasticsearch distribution *\/\n static Task configureExtractTask(String name, Project project, Task setup, NodeInfo node, Configuration configuration) {\n List extractDependsOn = [configuration, setup]\n \/* configuration.singleFile will be an external artifact if this is being run by a plugin not living in the\n elasticsearch source tree. If this is a plugin built in the elasticsearch source tree or this is a distro in\n the elasticsearch source tree then this should be the version of elasticsearch built by the source tree.\n If it isn't then Bad Things(TM) will happen. *\/\n Task extract = project.tasks.create(name: name, type: Copy, dependsOn: extractDependsOn) {\n if (getOs().equals(\"windows\")) {\n from {\n project.zipTree(configuration.singleFile)\n }\n } else {\n \/\/ macos and linux use tar\n from {\n project.tarTree(project.resources.gzip(configuration.singleFile))\n }\n }\n into node.baseDir\n }\n\n return extract\n }\n\n \/** Adds a task to write elasticsearch.yml for the given node configuration *\/\n static Task configureWriteConfigTask(String name, Project project, Task setup, NodeInfo node, Closure configFilter) {\n Map esConfig = [\n 'cluster.name' : node.clusterName,\n 'node.name' : \"node-\" + node.nodeNum,\n 'pidfile' : node.pidFile,\n 'path.repo' : \"${node.sharedDir}\/repo\",\n 'path.shared_data' : \"${node.sharedDir}\/\",\n \/\/ Define a node attribute so we can test that it exists\n 'node.attr.testattr' : 'test',\n \/\/ Don't wait for state, just start up quickly. This will also allow new and old nodes in the BWC case to become the master\n 'discovery.initial_state_timeout' : '0s'\n ]\n int minimumMasterNodes = node.config.minimumMasterNodes.call()\n if (node.nodeVersion.before(\"7.0.0\") && minimumMasterNodes > 0) {\n esConfig['discovery.zen.minimum_master_nodes'] = minimumMasterNodes\n }\n if (node.nodeVersion.before(\"7.0.0\") && esConfig.containsKey('discovery.zen.master_election.wait_for_joins_timeout') == false) {\n \/\/ If a node decides to become master based on partial information from the pinging, don't let it hang for 30 seconds to correct\n \/\/ its mistake. Instead, only wait 5s to do another round of pinging.\n \/\/ This is necessary since we use 30s as the default timeout in REST requests waiting for cluster formation\n \/\/ so we need to bail quicker than the default 30s for the cluster to form in time.\n esConfig['discovery.zen.master_election.wait_for_joins_timeout'] = '5s'\n }\n esConfig['node.max_local_storage_nodes'] = node.config.numNodes\n esConfig['http.port'] = node.config.httpPort\n esConfig['transport.tcp.port'] = node.config.transportPort\n \/\/ Default the watermarks to absurdly low to prevent the tests from failing on nodes without enough disk space\n esConfig['cluster.routing.allocation.disk.watermark.low'] = '1b'\n esConfig['cluster.routing.allocation.disk.watermark.high'] = '1b'\n if (node.nodeVersion.major >= 6) {\n esConfig['cluster.routing.allocation.disk.watermark.flood_stage'] = '1b'\n }\n \/\/ increase script compilation limit since tests can rapid-fire script compilations\n esConfig['script.max_compilations_rate'] = '2048\/1m'\n \/\/ Temporarily disable the real memory usage circuit breaker. It depends on real memory usage which we have no full control\n \/\/ over and the REST client will not retry on circuit breaking exceptions yet (see #31986 for details). Once the REST client\n \/\/ can retry on circuit breaking exceptions, we can revert again to the default configuration.\n if (node.nodeVersion.major >= 7) {\n esConfig['indices.breaker.total.use_real_memory'] = false\n }\n for (Map.Entry setting : node.config.settings) {\n if (setting.value == null) {\n esConfig.remove(setting.key)\n } else {\n esConfig.put(setting.key, setting.value)\n }\n }\n\n Task writeConfig = project.tasks.create(name: name, type: DefaultTask, dependsOn: setup)\n writeConfig.doFirst {\n esConfig = configFilter.call(esConfig)\n File configFile = new File(node.pathConf, 'elasticsearch.yml')\n logger.info(\"Configuring ${configFile}\")\n configFile.setText(esConfig.collect { key, value -> \"${key}: ${value}\" }.join('\\n'), 'UTF-8')\n }\n }\n\n \/** Adds a task to create keystore *\/\n static Task configureCreateKeystoreTask(String name, Project project, Task setup, NodeInfo node) {\n if (node.config.keystoreSettings.isEmpty() && node.config.keystoreFiles.isEmpty()) {\n return setup\n } else {\n \/*\n * We have to delay building the string as the path will not exist during configuration which will fail on Windows due to\n * getting the short name requiring the path to already exist.\n *\/\n final Object esKeystoreUtil = \"${-> node.binPath().resolve('elasticsearch-keystore').toString()}\"\n return configureExecTask(name, project, setup, node, esKeystoreUtil, 'create')\n }\n }\n\n \/** Adds tasks to add settings to the keystore *\/\n static Task configureAddKeystoreSettingTasks(String parent, Project project, Task setup, NodeInfo node) {\n Map kvs = node.config.keystoreSettings\n Task parentTask = setup\n \/*\n * We have to delay building the string as the path will not exist during configuration which will fail on Windows due to getting\n * the short name requiring the path to already exist.\n *\/\n final Object esKeystoreUtil = \"${-> node.binPath().resolve('elasticsearch-keystore').toString()}\"\n for (Map.Entry entry in kvs) {\n String key = entry.getKey()\n String name = taskName(parent, node, 'addToKeystore#' + key)\n Task t = configureExecTask(name, project, parentTask, node, esKeystoreUtil, 'add', key, '-x')\n String settingsValue = entry.getValue() \/\/ eval this early otherwise it will not use the right value\n t.doFirst {\n standardInput = new ByteArrayInputStream(settingsValue.getBytes(StandardCharsets.UTF_8))\n }\n parentTask = t\n }\n return parentTask\n }\n\n \/** Adds tasks to add files to the keystore *\/\n static Task configureAddKeystoreFileTasks(String parent, Project project, Task setup, NodeInfo node) {\n Map kvs = node.config.keystoreFiles\n if (kvs.isEmpty()) {\n return setup\n }\n Task parentTask = setup\n \/*\n * We have to delay building the string as the path will not exist during configuration which will fail on Windows due to getting\n * the short name requiring the path to already exist.\n *\/\n final Object esKeystoreUtil = \"${-> node.binPath().resolve('elasticsearch-keystore').toString()}\"\n for (Map.Entry entry in kvs) {\n String key = entry.getKey()\n String name = taskName(parent, node, 'addToKeystore#' + key)\n String srcFileName = entry.getValue()\n Task t = configureExecTask(name, project, parentTask, node, esKeystoreUtil, 'add-file', key, srcFileName)\n t.doFirst {\n File srcFile = project.file(srcFileName)\n if (srcFile.isDirectory()) {\n throw new GradleException(\"Source for keystoreFile must be a file: ${srcFile}\")\n }\n if (srcFile.exists() == false) {\n throw new GradleException(\"Source file for keystoreFile does not exist: ${srcFile}\")\n }\n }\n parentTask = t\n }\n return parentTask\n }\n\n static Task configureExtraConfigFilesTask(String name, Project project, Task setup, NodeInfo node) {\n if (node.config.extraConfigFiles.isEmpty()) {\n return setup\n }\n Copy copyConfig = project.tasks.create(name: name, type: Copy, dependsOn: setup)\n File configDir = new File(node.homeDir, 'config')\n copyConfig.into(configDir) \/\/ copy must always have a general dest dir, even though we don't use it\n for (Map.Entry extraConfigFile : node.config.extraConfigFiles.entrySet()) {\n Object extraConfigFileValue = extraConfigFile.getValue()\n copyConfig.doFirst {\n \/\/ make sure the copy won't be a no-op or act on a directory\n File srcConfigFile = project.file(extraConfigFileValue)\n if (srcConfigFile.isDirectory()) {\n throw new GradleException(\"Source for extraConfigFile must be a file: ${srcConfigFile}\")\n }\n if (srcConfigFile.exists() == false) {\n throw new GradleException(\"Source file for extraConfigFile does not exist: ${srcConfigFile}\")\n }\n }\n File destConfigFile = new File(node.homeDir, 'config\/' + extraConfigFile.getKey())\n \/\/ wrap source file in closure to delay resolution to execution time\n copyConfig.from({ extraConfigFileValue }) {\n \/\/ this must be in a closure so it is only applied to the single file specified in from above\n into(configDir.toPath().relativize(destConfigFile.canonicalFile.parentFile.toPath()).toFile())\n rename { destConfigFile.name }\n }\n }\n return copyConfig\n }\n\n \/**\n * Adds a task to copy plugins to a temp dir, which they will later be installed from.\n *\n * For each plugin, if the plugin has rest spec apis in its tests, those api files are also copied\n * to the test resources for this project.\n *\/\n static Task configureCopyPluginsTask(String name, Project project, Task setup, NodeInfo node, String prefix) {\n Copy copyPlugins = project.tasks.create(name: name, type: Copy, dependsOn: setup)\n\n List pluginFiles = []\n for (Map.Entry plugin : node.config.plugins.entrySet()) {\n\n String configurationName = pluginConfigurationName(prefix, plugin.key)\n Configuration configuration = project.configurations.findByName(configurationName)\n if (configuration == null) {\n configuration = project.configurations.create(configurationName)\n }\n\n if (plugin.getValue() instanceof Project) {\n Project pluginProject = plugin.getValue()\n verifyProjectHasBuildPlugin(name, node.nodeVersion, project, pluginProject)\n\n project.dependencies.add(configurationName, project.dependencies.project(path: pluginProject.path, configuration: 'zip'))\n setup.dependsOn(pluginProject.tasks.bundlePlugin)\n\n \/\/ also allow rest tests to use the rest spec from the plugin\n String copyRestSpecTaskName = pluginTaskName('copy', plugin.getKey(), 'PluginRestSpec')\n Copy copyRestSpec = project.tasks.findByName(copyRestSpecTaskName)\n for (File resourceDir : pluginProject.sourceSets.test.resources.srcDirs) {\n File restApiDir = new File(resourceDir, 'rest-api-spec\/api')\n if (restApiDir.exists() == false) continue\n if (copyRestSpec == null) {\n copyRestSpec = project.tasks.create(name: copyRestSpecTaskName, type: Copy)\n copyPlugins.dependsOn(copyRestSpec)\n copyRestSpec.into(project.sourceSets.test.output.resourcesDir)\n }\n copyRestSpec.from(resourceDir).include('rest-api-spec\/api\/**')\n }\n } else {\n project.dependencies.add(configurationName, \"${plugin.getValue()}@zip\")\n }\n\n\n\n pluginFiles.add(configuration)\n }\n\n copyPlugins.into(node.pluginsTmpDir)\n copyPlugins.from(pluginFiles)\n return copyPlugins\n }\n\n private static String pluginConfigurationName(final String prefix, final String name) {\n return \"_plugin_${prefix}_${name}\".replace(':', '_')\n }\n\n private static String pluginBwcConfigurationName(final String prefix, final String name) {\n return \"_plugin_bwc_${prefix}_${name}\".replace(':', '_')\n }\n\n \/** Configures task to copy a plugin based on a zip file resolved using dependencies for an older version *\/\n static Task configureCopyBwcPluginsTask(String name, Project project, Task setup, NodeInfo node, String prefix) {\n Configuration bwcPlugins = project.configurations.getByName(\"${prefix}_elasticsearchBwcPlugins\")\n for (Map.Entry plugin : node.config.plugins.entrySet()) {\n String configurationName = pluginBwcConfigurationName(prefix, plugin.key)\n Configuration configuration = project.configurations.findByName(configurationName)\n if (configuration == null) {\n configuration = project.configurations.create(configurationName)\n }\n\n if (plugin.getValue() instanceof Project) {\n Project pluginProject = plugin.getValue()\n verifyProjectHasBuildPlugin(name, node.nodeVersion, project, pluginProject)\n\n final String depName = findPluginName(pluginProject)\n\n Dependency dep = bwcPlugins.dependencies.find {\n it.name == depName\n }\n configuration.dependencies.add(dep)\n } else {\n project.dependencies.add(configurationName, \"${plugin.getValue()}@zip\")\n }\n }\n\n Copy copyPlugins = project.tasks.create(name: name, type: Copy, dependsOn: setup) {\n from bwcPlugins\n into node.pluginsTmpDir\n }\n return copyPlugins\n }\n\n static Task configureInstallModuleTask(String name, Project project, Task setup, NodeInfo node, Project module) {\n if (node.config.distribution != 'integ-test-zip') {\n project.logger.info(\"Not installing modules for $name, ${node.config.distribution} already has them\")\n return setup\n }\n if (module.plugins.hasPlugin(PluginBuildPlugin) == false) {\n throw new GradleException(\"Task ${name} cannot include module ${module.path} which is not an esplugin\")\n }\n Copy installModule = project.tasks.create(name, Copy.class)\n installModule.dependsOn(setup)\n installModule.dependsOn(module.tasks.bundlePlugin)\n installModule.into(new File(node.homeDir, \"modules\/${module.name}\"))\n installModule.from({ project.zipTree(module.tasks.bundlePlugin.outputs.files.singleFile) })\n return installModule\n }\n\n static Task configureInstallPluginTask(String name, Project project, Task setup, NodeInfo node, String pluginName, String prefix) {\n FileCollection pluginZip;\n if (node.nodeVersion != Version.fromString(VersionProperties.elasticsearch)) {\n pluginZip = project.configurations.getByName(pluginBwcConfigurationName(prefix, pluginName))\n } else {\n pluginZip = project.configurations.getByName(pluginConfigurationName(prefix, pluginName))\n }\n \/\/ delay reading the file location until execution time by wrapping in a closure within a GString\n final Object file = \"${-> new File(node.pluginsTmpDir, pluginZip.singleFile.getName()).toURI().toURL().toString()}\"\n \/*\n * We have to delay building the string as the path will not exist during configuration which will fail on Windows due to getting\n * the short name requiring the path to already exist.\n *\/\n final Object esPluginUtil = \"${-> node.binPath().resolve('elasticsearch-plugin').toString()}\"\n final Object[] args = [esPluginUtil, 'install', '--batch', file]\n return configureExecTask(name, project, setup, node, args)\n }\n\n \/** Wrapper for command line argument: surrounds comma with double quotes **\/\n private static class EscapeCommaWrapper {\n\n Object arg\n\n public String toString() {\n String s = arg.toString()\n\n \/\/\/ Surround strings that contains a comma with double quotes\n if (s.indexOf(',') != -1) {\n return \"\\\"${s}\\\"\"\n }\n return s\n }\n }\n\n \/** Adds a task to execute a command to help setup the cluster *\/\n static Task configureExecTask(String name, Project project, Task setup, NodeInfo node, Object[] execArgs) {\n return project.tasks.create(name: name, type: LoggedExec, dependsOn: setup) { Exec exec ->\n exec.workingDir node.cwd\n exec.environment 'JAVA_HOME', node.getJavaHome()\n if (Os.isFamily(Os.FAMILY_WINDOWS)) {\n exec.executable 'cmd'\n exec.args '\/C', 'call'\n \/\/ On Windows the comma character is considered a parameter separator:\n \/\/ argument are wrapped in an ExecArgWrapper that escapes commas\n exec.args execArgs.collect { a -> new EscapeCommaWrapper(arg: a) }\n } else {\n exec.commandLine execArgs\n }\n }\n }\n\n \/** Adds a task to start an elasticsearch node with the given configuration *\/\n static Task configureStartTask(String name, Project project, Task setup, NodeInfo node) {\n \/\/ this closure is converted into ant nodes by groovy's AntBuilder\n Closure antRunner = { AntBuilder ant ->\n ant.exec(executable: node.executable, spawn: node.config.daemonize, dir: node.cwd, taskname: 'elasticsearch') {\n node.env.each { key, value -> env(key: key, value: value) }\n node.args.each { arg(value: it) }\n }\n }\n\n \/\/ this closure is the actual code to run elasticsearch\n Closure elasticsearchRunner = {\n \/\/ Due to how ant exec works with the spawn option, we lose all stdout\/stderr from the\n \/\/ process executed. To work around this, when spawning, we wrap the elasticsearch start\n \/\/ command inside another shell script, which simply internally redirects the output\n \/\/ of the real elasticsearch script. This allows ant to keep the streams open with the\n \/\/ dummy process, but us to have the output available if there is an error in the\n \/\/ elasticsearch start script\n if (node.config.daemonize) {\n node.writeWrapperScript()\n }\n\n node.getCommandString().eachLine { line -> logger.info(line) }\n\n if (logger.isInfoEnabled() || node.config.daemonize == false) {\n runAntCommand(project, antRunner, System.out, System.err)\n } else {\n \/\/ buffer the output, we may not need to print it\n PrintStream captureStream = new PrintStream(node.buffer, true, \"UTF-8\")\n runAntCommand(project, antRunner, captureStream, captureStream)\n }\n }\n\n Task start = project.tasks.create(name: name, type: DefaultTask, dependsOn: setup)\n if (node.javaVersion != null) {\n BuildPlugin.requireJavaHome(start, node.javaVersion)\n }\n start.doLast(elasticsearchRunner)\n start.doFirst {\n \/\/ Configure ES JAVA OPTS - adds system properties, assertion flags, remote debug etc\n List esJavaOpts = [node.env.get('ES_JAVA_OPTS', '')]\n String collectedSystemProperties = node.config.systemProperties.collect { key, value -> \"-D${key}=${value}\" }.join(\" \")\n esJavaOpts.add(collectedSystemProperties)\n esJavaOpts.add(node.config.jvmArgs)\n if (Boolean.parseBoolean(System.getProperty('tests.asserts', 'true'))) {\n \/\/ put the enable assertions options before other options to allow\n \/\/ flexibility to disable assertions for specific packages or classes\n \/\/ in the cluster-specific options\n esJavaOpts.add(\"-ea\")\n esJavaOpts.add(\"-esa\")\n }\n \/\/ we must add debug options inside the closure so the config is read at execution time, as\n \/\/ gradle task options are not processed until the end of the configuration phase\n if (node.config.debug) {\n println 'Running elasticsearch in debug mode, suspending until connected on port 8000'\n esJavaOpts.add('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8000')\n }\n node.env['ES_JAVA_OPTS'] = esJavaOpts.join(\" \")\n\n \/\/\n project.logger.info(\"Starting node in ${node.clusterName} distribution: ${node.config.distribution}\")\n }\n return start\n }\n\n static Task configureWaitTask(String name, Project project, List nodes, List startTasks, int waitSeconds) {\n Task wait = project.tasks.create(name: name, dependsOn: startTasks)\n wait.doLast {\n\n Collection unicastHosts = new HashSet<>()\n nodes.forEach { node ->\n unicastHosts.addAll(node.config.otherUnicastHostAddresses.call())\n String unicastHost = node.config.unicastTransportUri(node, null, project.createAntBuilder())\n if (unicastHost != null) {\n unicastHosts.add(unicastHost)\n }\n }\n String unicastHostsTxt = String.join(\"\\n\", unicastHosts)\n nodes.forEach { node ->\n node.pathConf.toPath().resolve(\"unicast_hosts.txt\").setText(unicastHostsTxt)\n }\n\n ant.waitfor(maxwait: \"${waitSeconds}\", maxwaitunit: 'second', checkevery: '500', checkeveryunit: 'millisecond', timeoutproperty: \"failed${name}\") {\n or {\n for (NodeInfo node : nodes) {\n resourceexists {\n file(file: node.failedMarker.toString())\n }\n }\n and {\n for (NodeInfo node : nodes) {\n resourceexists {\n file(file: node.pidFile.toString())\n }\n resourceexists {\n file(file: node.httpPortsFile.toString())\n }\n resourceexists {\n file(file: node.transportPortsFile.toString())\n }\n }\n }\n }\n }\n if (ant.properties.containsKey(\"failed${name}\".toString())) {\n waitFailed(project, nodes, logger, \"Failed to start elasticsearch: timed out after ${waitSeconds} seconds\")\n }\n\n boolean anyNodeFailed = false\n for (NodeInfo node : nodes) {\n if (node.failedMarker.exists()) {\n logger.error(\"Failed to start elasticsearch: ${node.failedMarker.toString()} exists\")\n anyNodeFailed = true\n }\n }\n if (anyNodeFailed) {\n waitFailed(project, nodes, logger, 'Failed to start elasticsearch')\n }\n\n \/\/ make sure all files exist otherwise we haven't fully started up\n boolean missingFile = false\n for (NodeInfo node : nodes) {\n missingFile |= node.pidFile.exists() == false\n missingFile |= node.httpPortsFile.exists() == false\n missingFile |= node.transportPortsFile.exists() == false\n }\n if (missingFile) {\n waitFailed(project, nodes, logger, 'Elasticsearch did not complete startup in time allotted')\n }\n\n \/\/ go through each node checking the wait condition\n for (NodeInfo node : nodes) {\n \/\/ first bind node info to the closure, then pass to the ant runner so we can get good logging\n Closure antRunner = node.config.waitCondition.curry(node)\n\n boolean success\n if (logger.isInfoEnabled()) {\n success = runAntCommand(project, antRunner, System.out, System.err)\n } else {\n PrintStream captureStream = new PrintStream(node.buffer, true, \"UTF-8\")\n success = runAntCommand(project, antRunner, captureStream, captureStream)\n }\n\n if (success == false) {\n waitFailed(project, nodes, logger, 'Elasticsearch cluster failed to pass wait condition')\n }\n }\n }\n return wait\n }\n\n static void waitFailed(Project project, List nodes, Logger logger, String msg) {\n for (NodeInfo node : nodes) {\n if (logger.isInfoEnabled() == false) {\n \/\/ We already log the command at info level. No need to do it twice.\n node.getCommandString().eachLine { line -> logger.error(line) }\n }\n logger.error(\"Node ${node.nodeNum} output:\")\n logger.error(\"|-----------------------------------------\")\n logger.error(\"| failure marker exists: ${node.failedMarker.exists()}\")\n logger.error(\"| pid file exists: ${node.pidFile.exists()}\")\n logger.error(\"| http ports file exists: ${node.httpPortsFile.exists()}\")\n logger.error(\"| transport ports file exists: ${node.transportPortsFile.exists()}\")\n \/\/ the waitfor failed, so dump any output we got (if info logging this goes directly to stdout)\n logger.error(\"|\\n| [ant output]\")\n node.buffer.toString('UTF-8').eachLine { line -> logger.error(\"| ${line}\") }\n \/\/ also dump the log file for the startup script (which will include ES logging output to stdout)\n if (node.startLog.exists()) {\n logger.error(\"|\\n| [log]\")\n node.startLog.eachLine { line -> logger.error(\"| ${line}\") }\n }\n if (node.pidFile.exists() && node.failedMarker.exists() == false &&\n (node.httpPortsFile.exists() == false || node.transportPortsFile.exists() == false)) {\n logger.error(\"|\\n| [jstack]\")\n String pid = node.pidFile.getText('UTF-8')\n ByteArrayOutputStream output = new ByteArrayOutputStream()\n project.exec {\n commandLine = [\"${project.runtimeJavaHome}\/bin\/jstack\", pid]\n standardOutput = output\n }\n output.toString('UTF-8').eachLine { line -> logger.error(\"| ${line}\") }\n }\n logger.error(\"|-----------------------------------------\")\n }\n throw new GradleException(msg)\n }\n\n \/** Adds a task to check if the process with the given pidfile is actually elasticsearch *\/\n static Task configureCheckPreviousTask(String name, Project project, Object depends, NodeInfo node) {\n return project.tasks.create(name: name, type: Exec, dependsOn: depends) {\n onlyIf { node.pidFile.exists() }\n \/\/ the pid file won't actually be read until execution time, since the read is wrapped within an inner closure of the GString\n ext.pid = \"${ -> node.pidFile.getText('UTF-8').trim()}\"\n File jps\n if (Os.isFamily(Os.FAMILY_WINDOWS)) {\n jps = getJpsExecutableByName(project, \"jps.exe\")\n } else {\n jps = getJpsExecutableByName(project, \"jps\")\n }\n if (!jps.exists()) {\n throw new GradleException(\"jps executable not found; ensure that you're running Gradle with the JDK rather than the JRE\")\n }\n commandLine jps, '-l'\n standardOutput = new ByteArrayOutputStream()\n doLast {\n String out = standardOutput.toString()\n if (out.contains(\"${ext.pid} org.elasticsearch.bootstrap.Elasticsearch\") == false) {\n logger.error('jps -l')\n logger.error(out)\n logger.error(\"pid file: ${node.pidFile}\")\n logger.error(\"pid: ${ext.pid}\")\n throw new GradleException(\"jps -l did not report any process with org.elasticsearch.bootstrap.Elasticsearch\\n\" +\n \"Did you run gradle clean? Maybe an old pid file is still lying around.\")\n } else {\n logger.info(out)\n }\n }\n }\n }\n\n private static File getJpsExecutableByName(Project project, String jpsExecutableName) {\n return Paths.get(project.runtimeJavaHome.toString(), \"bin\/\" + jpsExecutableName).toFile()\n }\n\n \/** Adds a task to kill an elasticsearch node with the given pidfile *\/\n static Task configureStopTask(String name, Project project, Object depends, NodeInfo node) {\n return project.tasks.create(name: name, type: LoggedExec, dependsOn: depends) {\n onlyIf { node.pidFile.exists() }\n \/\/ the pid file won't actually be read until execution time, since the read is wrapped within an inner closure of the GString\n ext.pid = \"${ -> node.pidFile.getText('UTF-8').trim()}\"\n doFirst {\n logger.info(\"Shutting down external node with pid ${pid}\")\n }\n if (Os.isFamily(Os.FAMILY_WINDOWS)) {\n executable 'Taskkill'\n args '\/PID', pid, '\/F'\n } else {\n executable 'kill'\n args '-9', pid\n }\n doLast {\n project.delete(node.pidFile)\n }\n }\n }\n\n \/** Returns a unique task name for this task and node configuration *\/\n static String taskName(String prefix, NodeInfo node, String action) {\n if (node.config.numNodes > 1) {\n return \"${prefix}#node${node.nodeNum}.${action}\"\n } else {\n return \"${prefix}#${action}\"\n }\n }\n\n public static String pluginTaskName(String action, String name, String suffix) {\n \/\/ replace every dash followed by a character with just the uppercase character\n String camelName = name.replaceAll(\/-(\\w)\/) { _, c -> c.toUpperCase(Locale.ROOT) }\n return action + camelName[0].toUpperCase(Locale.ROOT) + camelName.substring(1) + suffix\n }\n\n \/** Runs an ant command, sending output to the given out and error streams *\/\n static Object runAntCommand(Project project, Closure command, PrintStream outputStream, PrintStream errorStream) {\n DefaultLogger listener = new DefaultLogger(\n errorPrintStream: errorStream,\n outputPrintStream: outputStream,\n messageOutputLevel: org.apache.tools.ant.Project.MSG_INFO)\n\n AntBuilder ant = project.createAntBuilder()\n ant.project.addBuildListener(listener)\n Object retVal = command(ant)\n ant.project.removeBuildListener(listener)\n return retVal\n }\n\n static void verifyProjectHasBuildPlugin(String name, Version version, Project project, Project pluginProject) {\n if (pluginProject.plugins.hasPlugin(PluginBuildPlugin) == false) {\n throw new GradleException(\"Task [${name}] cannot add plugin [${pluginProject.path}] with version [${version}] to project's \" +\n \"[${project.path}] dependencies: the plugin is not an esplugin\")\n }\n }\n\n \/** Find the plugin name in the given project. *\/\n static String findPluginName(Project pluginProject) {\n PluginPropertiesExtension extension = pluginProject.extensions.findByName('esplugin')\n return extension.name\n }\n\n \/** Find the current OS *\/\n static String getOs() {\n String os = \"linux\"\n if (Os.FAMILY_WINDOWS) {\n os = \"windows\"\n } else if (Os.FAMILY_MAC) {\n os = \"darwin\"\n }\n return os\n }\n}\n","avg_line_length":51.5112244898,"max_line_length":159,"alphanum_fraction":0.6128246271} +{"size":2646,"ext":"groovy","lang":"Groovy","max_stars_count":6.0,"content":"package groovy.bugs\n\n\/**\n * @version $Revision$\n *\/\n \nclass SuperMethod2Bug extends GroovyTestCase {\n \n void testBug() {\n \tdef base = new SuperBase()\n \tdef value = base.doSomething()\n \tassert value == \"TestBase\"\n \t\n \t\n \tbase = new SuperDerived()\n \tvalue = base.doSomething()\n \tassert value == \"TestDerivedTestBase\"\n }\n\n void testBug2() {\n \tdef base = new SuperBase()\n \tdef value = base.foo(2)\n \tassert value == \"TestBase2\"\n \t\n \t\n \tbase = new SuperDerived()\n \tvalue = base.foo(3)\n \tassert value == \"TestDerived3TestBase3\"\n }\n\n void testBug3() {\n \tdef base = new SuperBase()\n \tdef value = base.foo(2,3)\n \tassert value == \"foo(x,y)Base2,3\"\n \t\n \t\n \tbase = new SuperDerived()\n \tvalue = base.foo(3,4)\n \tassert value == \"foo(x,y)Derived3,4foo(x,y)Base3,4\"\n }\n\n void testBug4() {\n \tdef base = new SuperBase(\"Cheese\")\n \tdef value = base.name\n \tassert value == \"Cheese\"\n \t\n \t\n \tbase = new SuperDerived(\"Cheese\")\n \tvalue = base.name\n \tassert value == \"CheeseDerived\"\n }\n \n void testCallsToSuperMethodsReturningPrimitives(){\n def base = new SuperBase(\"super cheese\")\n assert base.longMethod() == 1\n assert base.intMethod() == 1\n assert base.boolMethod() == true\n \n base = new SuperDerived(\"derived super cheese\")\n assert base.longMethod() == 1\n assert base.intMethod() == 1\n assert base.boolMethod() == true \n }\n}\n\nclass SuperBase {\n String name\n\n SuperBase() {\n }\n \n SuperBase(String name) {\n this.name = name\n }\n \n def doSomething() {\n \t\"TestBase\"\n }\n\n def foo(param) {\n \t\"TestBase\" + param\n }\n \n def foo(x, y) {\n \t\"foo(x,y)Base\" + x + \",\" + y\n }\n \n boolean boolMethod(){true}\n long longMethod(){1l}\n int intMethod(){1i}\n}\n\nclass SuperDerived extends SuperBase {\n \n\tdef calls = 0\n\t\n\tSuperDerived() {\n\t}\n\t\n\tSuperDerived(String name) {\n\t super(name + \"Derived\")\n\t}\n\t\n def doSomething() {\n \t\/** @todo ++calls causes bug *\/\n \t\/\/calls++\n \t\/*\n \tcalls = calls + 1\n \tassert calls < 3\n \t*\/\n \t\n \t\"TestDerived\" + super.doSomething()\n }\n\t\n def foo(param) {\n \t\"TestDerived\" + param + super.foo(param)\n }\n\t\n def foo(x, y) {\n \t\"foo(x,y)Derived\" + x + \",\" + y + super.foo(x, y)\n }\n \n \/\/ we want to ensure that a call with super, which is directly added into \n \/\/ bytecode without calling MetaClass does correct boxing\n boolean booMethod(){super.boolMethod()}\n int intMethod(){super.intMethod()}\n long longMethod(){super.longMethod()}\n}\n\n","avg_line_length":20.3538461538,"max_line_length":78,"alphanum_fraction":0.559334845} +{"size":3179,"ext":"groovy","lang":"Groovy","max_stars_count":1.0,"content":"\/*\n * Copyright (c) 2015. Ronald D. Kurr kurr@jvmguy.com\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.kurron.example.rest\n\nimport static org.kurron.example.rest.feedback.ExampleFeedbackContext.MISSING_CORRELATION_ID\nimport static org.kurron.example.rest.feedback.ExampleFeedbackContext.PRECONDITION_FAILED\nimport org.kurron.feedback.AbstractFeedbackAware\nimport org.kurron.feedback.exceptions.PreconditionFailedError\nimport javax.servlet.http.HttpServletRequest\nimport javax.servlet.http.HttpServletResponse\nimport org.slf4j.MDC\nimport org.springframework.beans.factory.annotation.Autowired\nimport org.springframework.stereotype.Component\nimport org.springframework.web.servlet.HandlerInterceptor\nimport org.springframework.web.servlet.ModelAndView\nimport org.kurron.example.rest.inbound.CustomHttpHeaders\n\n\/**\n * Intercepts each REST request and extracts the X-Correlation-Id header, which is added to the MDC logging context. If no header is\n * found, an error is thrown.\n *\/\n@Component\nclass CorrelationIdHandlerInterceptor extends AbstractFeedbackAware implements HandlerInterceptor {\n\n \/**\n * Provides currently active property values.\n *\/\n private final ApplicationProperties configuration\n\n \/**\n * Correlation id key into the mapped diagnostic context.\n *\/\n public static final String CORRELATION_ID = 'correlation-id'\n\n @Autowired\n CorrelationIdHandlerInterceptor( final ApplicationProperties aConfiguration ) {\n configuration = aConfiguration\n }\n\n @Override\n boolean preHandle( final HttpServletRequest request, final HttpServletResponse response, final Object handler ) throws Exception {\n def correlationId = request.getHeader( CustomHttpHeaders.X_CORRELATION_ID )\n if ( !correlationId ) {\n if ( configuration.requireCorrelationId ) {\n feedbackProvider.sendFeedback( PRECONDITION_FAILED, CustomHttpHeaders.X_CORRELATION_ID )\n throw new PreconditionFailedError( PRECONDITION_FAILED, CustomHttpHeaders.X_CORRELATION_ID )\n } else {\n correlationId = UUID.randomUUID().toString()\n feedbackProvider.sendFeedback( MISSING_CORRELATION_ID, correlationId )\n }\n }\n MDC.put( CORRELATION_ID, correlationId )\n true\n }\n\n @Override\n void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView ) throws Exception {\n MDC.remove( CORRELATION_ID )\n }\n\n @Override\n void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) throws Exception { }\n}\n\n","avg_line_length":40.7564102564,"max_line_length":141,"alphanum_fraction":0.7565272098} +{"size":2673,"ext":"groovy","lang":"Groovy","max_stars_count":3.0,"content":"\/*\n * SPDX-License-Identifier: Apache-2.0\n *\n * Copyright 2019-2022 Andres Almiray.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.kordamp.gradle.plugin.oci.tasks.printers\n\nimport com.oracle.bmc.core.model.EgressSecurityRule\nimport com.oracle.bmc.core.model.IngressSecurityRule\nimport com.oracle.bmc.core.model.SecurityList\nimport groovy.transform.CompileStatic\nimport org.kordamp.gradle.plugin.oci.tasks.interfaces.ValuePrinter\n\n\/**\n * @author Andres Almiray\n * @since 0.1.0\n *\/\n@CompileStatic\nclass SecurityListPrinter {\n static void printSecurityList(ValuePrinter printer, SecurityList securityList, int offset) {\n printer.printKeyValue('ID', securityList.id, offset + 1)\n printer.printKeyValue('Compartment ID', securityList.compartmentId, offset + 1)\n printer.printKeyValue('VCN ID', securityList.vcnId, offset + 1)\n printer.printKeyValue('Time Created', securityList.timeCreated, offset + 1)\n printer.printKeyValue('Lifecycle State', printer.state(securityList.lifecycleState.name()), offset + 1)\n printer.printMap('Defined Tags', securityList.definedTags, offset + 1)\n printer.printMap('Freeform Tags', securityList.freeformTags, offset + 1)\n if (!securityList.ingressSecurityRules.empty) {\n int index = 0\n println((' ' * (offset + 1)) + 'Ingress Security Rules:')\n securityList.ingressSecurityRules.each { IngressSecurityRule rule ->\n println((' ' * (offset + 2)) + \"Ingress Security Rule ${(index++).toString().padLeft(3, '0')}: \")\n IngressSecurityRulePrinter.printIngressSecurityRule(printer, rule, offset + 2)\n }\n }\n if (!securityList.egressSecurityRules.empty) {\n int index = 0\n println((' ' * (offset + 1)) + 'Egress Security Rules:')\n securityList.egressSecurityRules.each { EgressSecurityRule rule ->\n println((' ' * (offset + 2)) + \"Egress Security Rule ${(index++).toString().padLeft(3, '0')}: \")\n EgressSecurityRulePrinter.printEgressSecurityRule(printer, rule, offset + 2)\n }\n }\n }\n}\n","avg_line_length":46.0862068966,"max_line_length":116,"alphanum_fraction":0.6812570146} +{"size":1718,"ext":"groovy","lang":"Groovy","max_stars_count":816.0,"content":"\/*\n * Copyright 2015 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage modules\n\nimport geb.module.DateTimeLocalInput\nimport geb.test.GebSpecWithCallbackServer\n\nimport java.time.LocalDateTime\n\nclass DateTimeLocalInputSnippetSpec extends GebSpecWithCallbackServer {\n\n def \"using datetime-local input module\"() {\n given:\n html \"\"\"\n \/\/ tag::html[]\n \n \n \n <\/body>\n <\/html>\n \/\/ end::html[]\n \"\"\"\n\n when:\n \/\/ tag::example[]\n def input = $(name: \"next-meeting\").module(DateTimeLocalInput)\n input.dateTime = \"2018-12-09T20:16\"\n\n \/\/ end::example[]\n then:\n \/\/ tag::example[]\n assert input.dateTime == LocalDateTime.of(2018, 12, 9, 20, 16)\n\n \/\/ end::example[]\n\n when:\n \/\/ tag::example[]\n input.dateTime = LocalDateTime.of(2018, 12, 31, 0, 0)\n\n \/\/ end::example[]\n then:\n \/\/ tag::example[]\n assert input.dateTime == LocalDateTime.parse(\"2018-12-31T00:00\")\n \/\/ end::example[]\n }\n\n}\n","avg_line_length":28.1639344262,"max_line_length":75,"alphanum_fraction":0.6071012806} +{"size":3032,"ext":"groovy","lang":"Groovy","max_stars_count":1.0,"content":"package org.meadowhawk.identicon.util\n\nimport groovy.xml.MarkupBuilder\nimport org.meadowhawk.identicon.pattern.RenderPattern\n\nimport java.awt.Color\n\nclass SVGBuilder {\n static createSvg(File outputFile, int width, int height, Closure content) {\n def writer = new StringWriter()\n def markupBuilder = new MarkupBuilder(writer)\n\n content.setDelegate(markupBuilder)\n markupBuilder.svg(width:width,height:height, xmlns:'http:\/\/www.w3.org\/2000\/svg', 'xmlns:xlink':'http:\/\/www.w3.org\/1999\/xlink', version:'1.1') {\n content(width, height)\n }\n outputFile.withWriter {\n it << writer.toString()\n }\n }\n\n static createSvg(StringWriter writer, int width, int height, Closure content) {\n def markupBuilder = new MarkupBuilder(writer)\n content.setDelegate(markupBuilder)\n markupBuilder.svg(width:width,height:height, xmlns:'http:\/\/www.w3.org\/2000\/svg', 'xmlns:xlink':'http:\/\/www.w3.org\/1999\/xlink', version:'1.1') {\n content(width, height)\n }\n }\n\n static def hsbColor = { hue, saturation = 1.0f, brightness = 1.0f ->\n def color = java.awt.Color.getHSBColor(hue as float, saturation as float, brightness as float)\n if(hue == \"0\") \/\/overrideWith White\n color = java.awt.Color.WHITE\n return \"rgb(${color.red},${color.green},${color.blue})\"\n }\n\n static def rbgColor = { Color color ->\n return \"rgb(${color.red},${color.green},${color.blue})\"\n }\n static String hexFormat = \"%02x\"\n\n static String getHexColor(byte byte1 , byte byte2, byte byte3){\n String.format(hexFormat, byte1) + String.format(hexFormat, byte2) + String.format(hexFormat, byte3)\n }\n\n static void generateCircles(Writer writer, byte[] bytes, RenderPattern pattern, int width, int height){\n int colorCt = width\n String[] colors = pattern.fillColors(bytes, colorCt)\n String bgColor = (bytes[2]%2==0)?\"ffffff\": \"282828\"\n SVGBuilder.createSvg(writer, width, height) { w, h ->\n rect(x: 0, y: 0, width: w, height: h, fill: pattern.renderColor(bgColor)) \/\/White backfill\n colors.each { color->\n circle(cx:Math.random() * width, cy:Math.random() * height,r:Math.min(width,height)\/ (Math.abs(new Random().nextInt() % (25 - 10)) + 10) , fill:pattern.renderColor(color))\n }\n }\n }\n\n static void generateGrid(Writer writer, byte[] bytes, RenderPattern pattern, int width, int height){\n int colorCt = width * height\n String[] colors = pattern.fillColors(bytes, colorCt)\n SVGBuilder.createSvg(writer, width, height) { w, h ->\n int x = 0\n int y = 0\n int b = 0\n while (y < h) {\n while (x < w) {\n rect(x: x, y: y, width: 10, height: 10, fill: pattern.renderColor(colors[b]))\n x += 10\n b++\n }\n y += 10\n x = 0\n }\n }\n }\n}\n","avg_line_length":39.3766233766,"max_line_length":187,"alphanum_fraction":0.5920184697} +{"size":5982,"ext":"groovy","lang":"Groovy","max_stars_count":11.0,"content":"package com.synopsys.integration.pipeline.jenkins\n\nimport com.synopsys.integration.pipeline.exception.CommandExecutionException\nimport com.synopsys.integration.pipeline.scm.GitStage\nimport org.jenkinsci.plugins.workflow.cps.CpsScript\n\nclass JenkinsScriptWrapperImpl implements JenkinsScriptWrapper {\n final CpsScript script\n\n JenkinsScriptWrapperImpl(final CpsScript script) {\n this.script = script\n }\n\n @Override\n void archiveArtifacts(String artifactPattern) {\n script.archiveArtifacts artifactPattern\n }\n\n @Override\n int bat(String command) throws CommandExecutionException {\n try {\n return script.bat(script: command, returnStatus: true)\n } catch (Exception e) {\n throw new CommandExecutionException(e.getMessage(), e)\n }\n }\n\n @Override\n String bat(String command, Boolean returnStdout) throws CommandExecutionException {\n try {\n return script.bat(script: command, returnStdout: returnStdout)\n } catch (Exception e) {\n throw new CommandExecutionException(e.getMessage(), e)\n }\n }\n\n @Override\n void checkout(String url, String branch, String gitToolName, boolean changelog, boolean poll, String credentialsId) {\n String localBranch = branch.replace(\"origin\/\", \"\")\n script.checkout changelog: changelog, poll: poll, scm: [$class : 'GitSCM', branches: [[name: branch]], doGenerateSubmoduleConfigurations: false,\n extensions: [[$class: 'WipeWorkspace'], [$class: 'LocalBranch', localBranch: localBranch]],\n gitTool: gitToolName, submoduleCfg: [], userRemoteConfigs: [[credentialsId: credentialsId, url: url]]]\n }\n\n void closure(Closure closure) {\n closure.call()\n }\n\n @Override\n BuildWrapper currentBuild() {\n return new BuildWrapperImpl(script.currentBuild)\n }\n\n @Override\n void deleteDir() {\n script.deleteDir()\n }\n\n @Override\n void dir(String relativeDirectory, Closure closure) {\n script.dir(relativeDirectory, closure)\n }\n\n @Override\n void emailext(String content, String subjectLine, String recipientList) {\n script.emailext(body: content, subject: subjectLine, to: recipientList)\n }\n\n @Override\n int executeCommand(String command) {\n if (isUnix()) {\n return sh(command)\n }\n return bat(command)\n }\n\n @Override\n String executeCommand(String command, Boolean returnStdout) {\n if (isUnix()) {\n return sh(command, returnStdout)\n }\n return bat(command, returnStdout)\n }\n\n @Override\n void executeCommandWithException(String command) throws CommandExecutionException {\n int errorStatus\n if (isUnix()) {\n errorStatus = sh(command)\n } else {\n errorStatus = bat(command)\n }\n if (errorStatus != 0) {\n throw new CommandExecutionException(errorStatus, \"Executing command '${command}', resulted in error status code '${errorStatus}'\")\n }\n }\n\n @Override\n void executeGitPushToGithub(PipelineConfiguration pipelineConfiguration, String url, String githubCredentialsId, String gitPath) throws CommandExecutionException {\n assert url.startsWith(GitStage.GITHUB_HTTPS) : \"Required to use \" + GitStage.GITHUB_HTTPS + \" when publishing to github\"\n script.withCredentials([script.usernamePassword(credentialsId: githubCredentialsId, usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD')]) {\n String gitPassword = pipelineConfiguration.getScriptWrapper().getJenkinsProperty('GIT_PASSWORD')\n String gitUsername= pipelineConfiguration.getScriptWrapper().getJenkinsProperty('GIT_USERNAME')\n String adjustedBranch = url.replace(\"https:\/\/\",\"https:\/\/${gitUsername}:${gitPassword}@\")\n\n executeCommandWithException(\"${gitPath} push ${adjustedBranch}\")\n }\n }\n\n String getJenkinsProperty(String propertyName) {\n script.env.getProperty(propertyName)\n }\n\n void setJenkinsProperty(String propertyName, String value) {\n script.env.setProperty(propertyName, value)\n }\n\n @Override\n boolean isUnix() {\n return script.isUnix()\n }\n\n @Override\n void jacoco(LinkedHashMap jacocoOptions) {\n script.jacoco jacocoOptions\n }\n\n @Override\n void junit(LinkedHashMap junitOptions) {\n script.junit junitOptions\n }\n\n @Override\n void println(String message) {\n script.println message\n }\n\n @Override\n void pipelineProperties(List pipelineOptions) {\n script.properties(pipelineOptions)\n }\n\n @Override\n String readFile(String fileName) {\n return script.readFile(fileName)\n }\n\n @Override\n void step(String[] fields) {\n script.step fields\n }\n\n \/**\n * WorkflowScript\/CpsScript\n **\/\n @Override\n CpsScript script() {\n return script\n }\n\n @Override\n int sh(String command) throws CommandExecutionException {\n try {\n return script.sh(script: command, returnStatus: true)\n } catch (Exception e) {\n throw new CommandExecutionException(e.getMessage(), e)\n }\n }\n\n @Override\n String sh(String command, Boolean returnStdout) throws CommandExecutionException {\n try {\n return script.sh(script: command, returnStdout: returnStdout)\n } catch (Exception e) {\n throw new CommandExecutionException(e.getMessage(), e)\n }\n }\n\n @Override\n void stage(String stageName, Closure closure) {\n script.stage(stageName, closure)\n }\n\n @Override\n String tool(String toolName) {\n return script.tool(toolName)\n }\n\n @Override\n void writeFile(final String fileName, final String text) {\n script.writeFile(file: fileName, text: text)\n }\n}\n","avg_line_length":30.8350515464,"max_line_length":167,"alphanum_fraction":0.6487796724} +{"size":1003,"ext":"groovy","lang":"Groovy","max_stars_count":10.0,"content":"package com.slalom.delorean.spring.boot.controller\n\nimport com.slalom.autoconfiguration.delorean.TimeMachineConfigurationProperties\nimport org.springframework.test.web.servlet.MockMvc\nimport spock.lang.Specification\n\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get\nimport static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup\n\nclass TimeMachineControllerSpec extends Specification {\n def tmController = new TimeMachineController(new TimeMachineConfigurationProperties())\n\n MockMvc mm = standaloneSetup(tmController).build()\n\n def setup() {\n }\n\n def \"Test Successful LocalDate\"() {\n when:\n def response = mm.perform(get('\/time-machine\/2011-01-21')).andReturn().response\n\n then:\n response.status == 200\n }\n\n def \"Test Failing Date\"() {\n when:\n def response = mm.perform(get('\/time-machine\/20110101')).andReturn().response\n\n then:\n response.status == 400\n }\n}\n","avg_line_length":29.5,"max_line_length":90,"alphanum_fraction":0.7308075773} +{"size":740,"ext":"groovy","lang":"Groovy","max_stars_count":2.0,"content":"package org.pine.script.annotation\n\nimport org.codehaus.groovy.ast.ASTNode\nimport org.codehaus.groovy.ast.ClassNode\nimport org.codehaus.groovy.control.CompilePhase\nimport org.codehaus.groovy.control.SourceUnit\nimport org.codehaus.groovy.transform.AbstractASTTransformation\nimport org.codehaus.groovy.transform.GroovyASTTransformation\n\n@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)\nclass SpecScriptClassTransformation extends AbstractASTTransformation {\n\n @Override\n void visit(ASTNode[] nodes, SourceUnit source) {\n ClassNode configClass = (ClassNode)nodes[1]\n\n source.AST.getScriptClassDummy().addAnnotations(configClass.getAnnotations())\n\n source.AST.getClasses().remove(configClass)\n }\n}\n","avg_line_length":33.6363636364,"max_line_length":85,"alphanum_fraction":0.8081081081} +{"size":1292,"ext":"groovy","lang":"Groovy","max_stars_count":33.0,"content":"import com.haulmont.cuba.core.global.AppBeans\n\ndef persistence = AppBeans.get('cuba_Persistence')\ndef tx = persistence.createTransaction()\ntry {\n def result = []\n\n def em = persistence.getEntityManager()\n def ltList = em.createQuery('select lt from library$LiteratureType lt').getResultList()\n ltList.each { lt ->\n def count = em.createQuery('''\n select count(bi) from library$BookInstance bi \n where bi.libraryDepartment = ?1\n and bi.bookPublication.book.literatureType = ?2\n ''')\n .setParameter(1, params['library_department'])\n .setParameter(2, lt)\n .getSingleResult()\n def refCount = em.createQuery('''\n select count(bi) from library$BookInstance bi \n where bi.libraryDepartment = ?1\n and bi.bookPublication.book.literatureType = ?2 and bi.isReference = true''')\n .setParameter(1, params['library_department'])\n .setParameter(2, lt)\n .getSingleResult()\n\n result.add(['literature_type_name': lt.name, \n 'books_instances_amount': count, \n 'reference_books_instances_amount': refCount])\n }\n return result\n} finally {\n tx.end()\n}","avg_line_length":38.0,"max_line_length":97,"alphanum_fraction":0.5944272446} +{"size":4887,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"package com.github.joselion.prettyjupiter\n\nimport static com.github.joselion.prettyjupiter.helpers.Utils.ESC\n\nimport org.gradle.api.model.ObjectFactory\nimport org.gradle.api.tasks.testing.TestDescriptor\nimport org.gradle.testfixtures.ProjectBuilder\n\nimport spock.lang.Specification\n\nclass FailureTest extends Specification {\n\n private static final ObjectFactory objects = ProjectBuilder.builder().build().objects\n private static final Exception causeD = new Exception('Cause of error C')\n private static final Exception causeC = new Exception('Cause of error B', causeD)\n private static final Exception causeB = new Exception('Cause of error A', causeC)\n private static final AssertionError causeA = new AssertionError('Cause of top error', causeB)\n private static final Exception fullCause = new Exception('Top error', causeA)\n\n def '.cause'(Throwable topError, String result) {\n given:\n final Failure failure = new Failure(topError, desc(1), objects.newInstance(PrettyJupiterExtension))\n\n expect:\n failure.getCause() == result\n\n where:\n topError | result\n new Exception() | null\n causeC | \"${ESC}[33m+ java.lang.Exception: Cause of error C${ESC}[0m\"\n causeB | \"${ESC}[33m+ java.lang.Exception: Cause of error B\\n\" +\n \"\u2514\u2500\u2500\u2500 java.lang.Exception: Cause of error C${ESC}[0m\"\n causeA | \"${ESC}[33m+ java.lang.Exception: Cause of error A\\n\" +\n '\u2514\u2500\u252c\u2500 java.lang.Exception: Cause of error B\\n' +\n \" \u2514\u2500\u2500\u2500 java.lang.Exception: Cause of error C${ESC}[0m\"\n fullCause | \"${ESC}[33m+ java.lang.AssertionError: Cause of top error\\n\" +\n '\u2514\u2500\u252c\u2500 java.lang.Exception: Cause of error A\\n' +\n ' \u2514\u2500\u252c\u2500 java.lang.Exception: Cause of error B\\n' +\n \" \u2514\u2500\u2500\u2500 java.lang.Exception: Cause of error C${ESC}[0m\"\n }\n\n def '.location'(TestDescriptor descriptor, String location) {\n given:\n final Failure failure = new Failure(new Exception(), descriptor, objects.newInstance(PrettyJupiterExtension))\n\n expect:\n failure.getLocation() == location\n\n where:\n descriptor | location\n desc() | ''\n desc(1) | 'Test description 1'\n desc(3) | 'Test description 1 => Test description 2 => Test description 3'\n }\n\n def '.message'() {\n given:\n final String error = 'This should be an Assertion error!'\n final Failure failure = new Failure(new Exception(error), desc(1), objects.newInstance(PrettyJupiterExtension))\n\n expect:\n failure.getMessage() == \"${ESC}[91mjava.lang.Exception: ${error}${ESC}[0m\"\n }\n\n def '.trace'() {\n given:\n final String trace = '''\\\n |java.lang.Exception: Some error message\n | at java.base\/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)\n | at java.base\/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)\n | at java.base\/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)\n | at java.base\/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)\n | at java.base\/java.lang.reflect.Constructor.newInstance(Constructor.java:481)\n | at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:80)\n | at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:105)\n | at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:59)\n | at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:237)\n | at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:249)\n | --- and 60 more ---'''\n .stripMargin()\n final Failure failure = new Failure(new Exception('Some error message'), desc(1), objects.newInstance(PrettyJupiterExtension))\n\n expect:\n failure.getTrace() == \"${ESC}[90m${trace}${ESC}[0m\"\n }\n\n private TestDescriptor desc(Integer parents = 0) {\n final Integer num = parents + 1\n\n return Stub(TestDescriptor) {\n getParent() >> Stub(TestDescriptor) {\n getParent() >> descriptorWithParents(num)\n }\n }\n }\n\n private TestDescriptor descriptorWithParents(Integer num) {\n if (num == null) {\n return null\n }\n\n if (num == 0) {\n return Stub(TestDescriptor) {\n getParent() >> null\n getDisplayName() >> \"Test description ${num - 1}\"\n }\n }\n\n return Stub(TestDescriptor) {\n getParent() >> descriptorWithParents(num - 1)\n getDisplayName() >> \"Test description ${num - 1}\"\n }\n }\n}\n","avg_line_length":42.4956521739,"max_line_length":140,"alphanum_fraction":0.6599140577} +{"size":1315,"ext":"groovy","lang":"Groovy","max_stars_count":7.0,"content":"package org.tools4j.fix.spec\n\nimport spock.lang.Specification\n\n\/**\n * User: benjw\n * Date: 9\/3\/2018\n * Time: 6:37 AM\n *\/\nclass FixSpecParserTest extends Specification {\n def \"test FIX four four\"() {\n when:\n final FixSpecDefinition fixSpec = new FixSpecParser('path\/to\/FIX44.xml').parseSpec()\n\n then:\n assert fixSpec.fieldsByName.size() == 916\n assert fixSpec.messagesByName.size() == 92\n\n then:\n final MessageSpec nos = fixSpec.messagesByMsgType.get(\"D\")\n assert nos.fields.size() == 178\n }\n\n def \"test FIX default\"() {\n when:\n final FixSpecDefinition fixSpec = new FixSpecParser().parseSpec()\n\n then:\n assert fixSpec.fieldsByName.size() == 1606\n assert fixSpec.messagesByName.size() == 117\n\n then:\n final MessageSpec nos = fixSpec.messagesByMsgType.get(\"D\")\n assert nos.fields.size() == 264\n }\n\n def \"test FIX five zero SP two - from working dir\"() {\n when:\n final FixSpecDefinition fixSpec = new FixSpecParser().parseSpec()\n\n then:\n assert fixSpec.fieldsByName.size() == 1606\n assert fixSpec.messagesByName.size() == 117\n\n then:\n final MessageSpec nos = fixSpec.messagesByMsgType.get(\"D\")\n assert nos.fields.size() == 264\n }\n}\n","avg_line_length":26.3,"max_line_length":92,"alphanum_fraction":0.6174904943} +{"size":1963,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"import org.kie.jenkins.jobdsl.Constants\nimport org.kie.jenkins.jobdsl.templates.BasicJob\n\n\/\/ Job Description\nString jobDescription = \"Job responsible for building slave image\"\n\n\nString command = \"\"\"#!\/bin\/bash +x\ncd jenkins-slaves\n\n# include functionality for osbs builds\n.\/add-osbs.sh https:\/\/code.engineering.redhat.com\/gerrit\/bxms-jenkins\n\nexport ANSIBLE_SCP_IF_SSH=y\n\/opt\/packer\/bin\/packer build\\\\\n -var \"openstack_endpoint=https:\/\/rhos-d.infra.prod.upshift.rdu2.redhat.com:13000\/v3\"\\\\\n -var \"openstack_username=psi-rhba-jenkins\"\\\\\n -var \"openstack_password=\\$PSI_PASSWORD\"\\\\\n -var \"image_name=kie-rhel7-\\$BUILD_NUMBER\"\\\\\n -var \"ssh_private_key_file=\\$PSI_PRIVATE_KEY\"\\\\\n packer-kie-rhel7.json\n\"\"\"\n\n\/\/ Creates or updates a free style job.\ndef jobDefinition = job(\"slave-image-build\") {\n\n \/\/ Allows a job to check out sources from an SCM provider.\n scm {\n\n \/\/ Adds a Git SCM source.\n git {\n\n \/\/ Specify the branches to examine for changes and to build.\n branch(\"master\")\n\n \/\/ Adds a remote.\n remote {\n\n \/\/ Sets a remote URL for a GitHub repository.\n github(\"kiegroup\/kie-jenkins-scripts\")\n }\n }\n }\n\n \/\/ Adds pre\/post actions to the job.\n wrappers {\n\n \/\/ Binds environment variables to credentials.\n credentialsBinding {\n\n \/\/ Sets a variable to the text given in the credentials.\n string(\"PSI_PASSWORD\", \"psi-rhba-jenkins-password\")\n\n \/\/ Copies the file given in the credentials to a temporary location, then sets the variable to that location.\n file(\"PSI_PRIVATE_KEY\", \"kie-jenkins.pem\")\n }\n }\n\n \/\/ Label which specifies which nodes this job can run on.\n label(\"kie-linux&&kie-mem512m\")\n\n \/\/ Adds build steps to the jobs.\n steps {\n\n \/\/ Runs a shell script.\n shell(command)\n }\n}\n\nBasicJob.addCommonConfiguration(jobDefinition, jobDescription)\n","avg_line_length":27.6478873239,"max_line_length":121,"alphanum_fraction":0.654100866} +{"size":201,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/\/ vars\/module_Utilities.groovy\nimport groovy.json.JsonSlurperClassic\n \nMap parseJSONString(String json) {\n def jsonSlurper = new JsonSlurperClassic()\n return jsonSlurper.parseText(json) as Map\n}","avg_line_length":28.7142857143,"max_line_length":46,"alphanum_fraction":0.7860696517} +{"size":4171,"ext":"groovy","lang":"Groovy","max_stars_count":1.0,"content":"\/*\n * This file is part of TechReborn, licensed under the MIT License (MIT).\n *\n * Copyright (c) 2020 TechReborn\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\npackage techreborn\n\nimport net.minecraft.Bootstrap\nimport net.minecraft.SharedConstants\nimport net.minecraft.util.registry.BuiltinRegistries\nimport net.minecraft.world.EmptyBlockView\nimport net.minecraft.world.gen.HeightContext\nimport net.minecraft.world.gen.chunk.DebugChunkGenerator\nimport techreborn.world.OreDistribution\nimport techreborn.world.TargetDimension\n\nimport javax.imageio.ImageIO\nimport java.awt.*\nimport java.awt.image.BufferedImage\nimport java.nio.file.Paths\nimport java.util.List\n\nclass OreDistributionVisualiser {\n private static final Color[] colors = new Color[] {\n Color.black,\n Color.red,\n Color.pink,\n Color.orange,\n Color.yellow,\n Color.green,\n Color.magenta,\n Color.cyan,\n Color.blue\n }\n\n static void main(String[] args) {\n \/\/ Start the game up enough\n SharedConstants.createGameVersion()\n Bootstrap.initialize()\n\n generateOreDistributionVisualization()\n }\n\n static void generateOreDistributionVisualization() throws IOException {\n def heightContext = new FixedHeightContext(-64, 360)\n\n BufferedImage bi = new BufferedImage(450, 220, BufferedImage.TYPE_INT_ARGB)\n Graphics2D png = bi.createGraphics()\n Font font = new Font(\"TimesRoman\", Font.BOLD, 20)\n png.setFont(font)\n\n png.setPaint(Color.black)\n \/\/ Draw 0\n png.drawLine(0, -heightContext.minY, (overworldOres().size() * 10) + 20, -heightContext.minY)\n\n png.setPaint(Color.blue)\n \/\/ Draw ground\n png.drawLine(0, -heightContext.minY + 64, (overworldOres().size() * 10) + 20, -heightContext.minY + 64)\n\n int c = 1\n for (OreDistribution value : overworldOres()) {\n png.setPaint(colors[c])\n\n def yMin = value.minOffset.getY(heightContext) + -heightContext.minY\n def yMax = -heightContext.minY + value.maxY\n\n png.fill3DRect(c * 10, yMin, 10, yMax - yMin, true)\n\n png.drawString(value.name() + \"(%d -> %d)\".formatted(value.minOffset.getY(heightContext), value.maxY), 190, 25 * c)\n\n c += 1\n }\n\n ImageIO.write(bi, \"PNG\", Paths.get(\"ore_distribution.png\").toFile())\n }\n\n private static List overworldOres() {\n return Arrays.stream(OreDistribution.values())\n .filter(ore -> ore.dimension == TargetDimension.OVERWORLD)\n .toList()\n }\n\n private static class FixedHeightContext extends HeightContext {\n final int minY\n final int height\n\n FixedHeightContext(int minY, int height) {\n super(new DebugChunkGenerator(BuiltinRegistries.BIOME), EmptyBlockView.INSTANCE)\n\n this.minY = minY\n this.height = height\n }\n\n @Override\n int getMinY() {\n return minY\n }\n\n @Override\n int getHeight() {\n return height\n }\n }\n}\n","avg_line_length":33.6370967742,"max_line_length":127,"alphanum_fraction":0.6677055862} +{"size":4234,"ext":"groovy","lang":"Groovy","max_stars_count":1.0,"content":"\/*\n *\n * Copyright 2015-2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\n *\/\n\npackage springfox.documentation.spring.web.readers.operation\n\nimport com.fasterxml.classmate.TypeResolver\nimport org.springframework.plugin.core.OrderAwarePluginRegistry\nimport org.springframework.plugin.core.PluginRegistry\nimport springfox.documentation.schema.DefaultTypeNameProvider\nimport springfox.documentation.schema.JacksonEnumTypeDeterminer\nimport springfox.documentation.schema.TypeNameExtractor\nimport springfox.documentation.schema.mixins.SchemaPluginsSupport\nimport springfox.documentation.spi.DocumentationType\nimport springfox.documentation.spi.schema.TypeNameProviderPlugin\nimport springfox.documentation.spi.service.contexts.OperationContext\nimport springfox.documentation.spring.web.mixins.RequestMappingSupport\nimport springfox.documentation.spring.web.mixins.ServicePluginsSupport\nimport springfox.documentation.spring.web.plugins.DocumentationContextSpec\n\nimport static com.google.common.base.Strings.*\n\n@Mixin([RequestMappingSupport, ServicePluginsSupport, SchemaPluginsSupport])\nclass OperationResponseClassReaderSpec extends DocumentationContextSpec {\n OperationResponseClassReader sut\n \n def setup() {\n PluginRegistry modelNameRegistry =\n OrderAwarePluginRegistry.create([new DefaultTypeNameProvider()])\n def typeNameExtractor = new TypeNameExtractor(\n new TypeResolver(),\n modelNameRegistry,\n new JacksonEnumTypeDeterminer())\n\n sut = new OperationResponseClassReader(typeNameExtractor)\n }\n \n def \"Should support all documentation types\"() {\n expect:\n sut.supports(DocumentationType.SPRING_WEB)\n sut.supports(DocumentationType.SWAGGER_12)\n sut.supports(DocumentationType.SWAGGER_2)\n }\n\n def \"should have correct response class\"() {\n given:\n OperationContext operationContext = operationContext(documentationContext(), handlerMethod)\n when:\n sut.apply(operationContext)\n def operation = operationContext.operationBuilder().build()\n then:\n if (operation.responseModel.collection) {\n assert expectedClass == String.format(\"%s[%s]\", operation.responseModel.type, operation.responseModel.itemType)\n } else {\n assert expectedClass == operation.responseModel.type\n if (\"Map\".equals(operation.responseModel.type)) {\n assert operation.responseModel.isMap()\n assert !isNullOrEmpty(operation.responseModel.itemType)\n }\n if (allowableValues == null) {\n assert operation.responseModel.getAllowableValues() == null\n } else {\n assert allowableValues == operation.responseModel.getAllowableValues().values\n }\n }\n\n where:\n handlerMethod | expectedClass | allowableValues\n dummyHandlerMethod('methodWithConcreteResponseBody') | 'BusinessModel' | null\n dummyHandlerMethod('methodWithAPiAnnotationButWithoutResponseClass') | 'FunkyBusiness' | null\n dummyHandlerMethod('methodWithGenericType') | 'Paginated\u00abstring\u00bb' | null\n dummyHandlerMethod('methodWithListOfBusinesses') | 'List[BusinessModel]' | null\n dummyHandlerMethod('methodWithMapReturn') | 'Map\u00abstring,BusinessModel\u00bb'| null\n dummyHandlerMethod('methodWithEnumResponse') | 'string' | ['ONE', 'TWO']\n dummyHandlerMethod('methodWithByteArray') | 'Array[byte]' | ['ONE', 'TWO']\n }\n\n}\n","avg_line_length":45.0425531915,"max_line_length":121,"alphanum_fraction":0.7109116675} +{"size":2611,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\npackage groovy.bugs\n\nimport org.codehaus.groovy.control.CompilerConfiguration\nimport org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit\n\nclass Groovy7721Bug extends GroovyTestCase {\n void testCovariantArrayAtOverriding() {\n def config = new CompilerConfiguration()\n config.with {\n targetDirectory = createTempDir()\n jointCompilationOptions = [stubDir: createTempDir()]\n }\n\n File parentDir = createTempDir()\n try {\n def a = new File(parentDir, 'A.java')\n a.write '''\n package pack;\n interface A {\n Object[] bar();\n }\n\n '''\n def b = new File(parentDir, 'B.java')\n b.write '''\n package pack;\n interface B extends A {\n @Override\n String[] bar();\n }\n '''\n\n def c = new File(parentDir, 'C.groovy')\n c.write '''\n import groovy.transform.CompileStatic\n\n @CompileStatic\n class C {\n static def bar(pack.B b) {\n b.bar()\n }\n }\n '''\n def loader = new GroovyClassLoader(this.class.classLoader)\n def cu = new JavaAwareCompilationUnit(config, loader)\n cu.addSources([a, b, c] as File[])\n cu.compile()\n } finally {\n parentDir.deleteDir()\n config.targetDirectory?.deleteDir()\n config.jointCompilationOptions.stubDir?.deleteDir()\n }\n\n }\n\n private static File createTempDir() {\n File.createTempDir(\"groovyTest${System.currentTimeMillis()}\", \"\")\n }\n\n}\n","avg_line_length":32.2345679012,"max_line_length":73,"alphanum_fraction":0.5733435465} +{"size":4856,"ext":"groovy","lang":"Groovy","max_stars_count":2.0,"content":"\/*\n * Copyright 2020 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.gradle.configurationcache.inputs.undeclared\n\nimport org.gradle.integtests.fixtures.daemon.DaemonLogsAnalyzer\nimport org.gradle.integtests.fixtures.executer.AbstractGradleExecuter\nimport org.gradle.integtests.fixtures.executer.ExecutionFailure\nimport org.gradle.integtests.fixtures.executer.ExecutionResult\nimport org.gradle.integtests.fixtures.executer.GradleContextualExecuter\nimport org.gradle.integtests.fixtures.executer.GradleDistribution\nimport org.gradle.integtests.fixtures.executer.GradleExecuter\nimport org.gradle.integtests.fixtures.executer.IntegrationTestBuildContext\nimport org.gradle.integtests.fixtures.executer.OutputScrapingExecutionFailure\nimport org.gradle.integtests.fixtures.executer.OutputScrapingExecutionResult\nimport org.gradle.internal.nativeintegration.services.NativeServices\nimport org.gradle.test.fixtures.file.TestDirectoryProvider\nimport org.gradle.test.fixtures.file.TestFile\nimport org.gradle.testkit.runner.GradleRunner\nimport org.gradle.testkit.runner.internal.ToolingApiGradleExecutor\nimport org.gradle.util.Requires\nimport org.gradle.util.SetSystemProperties\nimport org.gradle.util.TestPrecondition\nimport org.junit.Rule\n\n@Requires(TestPrecondition.NOT_WINDOWS)\nclass UndeclaredBuildInputsTestKitInjectedJavaPluginIntegrationTest extends AbstractUndeclaredBuildInputsIntegrationTest implements JavaPluginImplementation {\n TestFile jar\n TestFile testKitDir\n\n @Override\n String getLocation() {\n return \"Plugin 'sneaky'\"\n }\n\n @Rule\n SetSystemProperties setSystemProperties = new SetSystemProperties(\n (NativeServices.NATIVE_DIR_OVERRIDE): buildContext.nativeServicesDir.absolutePath\n )\n\n @Override\n GradleExecuter createExecuter() {\n testKitDir = file(\"test-kit\")\n def executer = new TestKitBackedGradleExecuter(distribution, temporaryFolder, getBuildContext(), testKitDir)\n jar = file(\"plugins\/sneaky.jar\")\n executer.pluginClasspath.add(jar)\n return executer\n }\n\n def cleanup() {\n DaemonLogsAnalyzer.newAnalyzer(testKitDir.file(ToolingApiGradleExecutor.TEST_KIT_DAEMON_DIR_NAME)).killAll()\n }\n\n @Override\n void buildLogicApplication(BuildInputRead read) {\n def builder = artifactBuilder()\n javaPlugin(builder.sourceFile(\"SneakyPlugin.java\"), read)\n builder.resourceFile(\"META-INF\/gradle-plugins\/sneaky.properties\") << \"\"\"\nimplementation-class: SneakyPlugin\n \"\"\"\n builder.buildJar(jar)\n buildFile << \"\"\"\n plugins { id(\"sneaky\") }\n \"\"\"\n }\n\n static class TestKitBackedGradleExecuter extends AbstractGradleExecuter {\n List pluginClasspath = []\n private final IntegrationTestBuildContext buildContext\n private final TestFile testKitDir\n\n TestKitBackedGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider, IntegrationTestBuildContext buildContext, TestFile testKitDir) {\n super(distribution, testDirectoryProvider)\n this.testKitDir = testKitDir\n this.buildContext = buildContext\n }\n\n @Override\n void assertCanExecute() throws AssertionError {\n }\n\n @Override\n protected ExecutionResult doRun() {\n def runnerResult = createRunner().build()\n return OutputScrapingExecutionResult.from(runnerResult.output, \"\")\n }\n\n @Override\n protected ExecutionFailure doRunWithFailure() {\n def runnerResult = createRunner().buildAndFail()\n return OutputScrapingExecutionFailure.from(runnerResult.output, \"\")\n }\n\n private GradleRunner createRunner() {\n def runner = GradleRunner.create()\n if (!GradleContextualExecuter.embedded) {\n runner.withGradleInstallation(buildContext.gradleHomeDir)\n }\n runner.withTestKitDir(testKitDir)\n runner.withProjectDir(workingDir)\n def args = allArgs\n args.remove(\"--no-daemon\")\n runner.withArguments(args)\n runner.withPluginClasspath(pluginClasspath)\n runner.withEnvironment(environmentVars)\n runner.forwardOutput()\n runner\n }\n }\n}\n","avg_line_length":39.1612903226,"max_line_length":178,"alphanum_fraction":0.7343492586} +{"size":2517,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Copyright 2011-2019 The OTP authors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\npackage de.dkfz.tbi.otp.dataprocessing\n\nimport grails.compiler.GrailsCompileStatic\nimport grails.compiler.GrailsTypeChecked\nimport grails.gorm.transactions.Transactional\nimport groovy.transform.TypeCheckingMode\nimport org.springframework.security.access.prepost.PreAuthorize\n\nimport de.dkfz.tbi.otp.ngsdata.*\n\n@Transactional\n@GrailsCompileStatic\nclass AbstractMergingWorkPackageService {\n\n @GrailsCompileStatic(TypeCheckingMode.SKIP)\n @GrailsTypeChecked\n @PreAuthorize(\"hasRole('ROLE_OPERATOR')\")\n List findMergingWorkPackage(Individual individual, SeqType seqType, AntibodyTarget antibodyTarget = null) {\n assert individual\n assert seqType\n return AbstractMergingWorkPackage.createCriteria().list {\n sample {\n eq('individual', individual)\n }\n eq('seqType', seqType)\n if (antibodyTarget) {\n eq('antibodyTarget', antibodyTarget)\n } else {\n isNull('antibodyTarget')\n }\n }\n }\n\n @PreAuthorize(\"hasRole('ROLE_OPERATOR')\")\n List filterByCategory(List mergingWorkPackages, SampleTypePerProject.Category category) {\n return mergingWorkPackages.findAll {\n SampleTypeService.getCategory(it.project, it.sampleType) == category\n }\n }\n}\n","avg_line_length":40.5967741935,"max_line_length":149,"alphanum_fraction":0.733412793} +{"size":786,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\nimport groovy.transform.Field\nimport org.hitachivantara.ci.config.BuildData\n\n@Field BuildData buildData = BuildData.instance\n\ndef call() {\n node(params.SLAVE_NODE_LABEL ?: 'non-master') {\n timestamps {\n stages.configure()\n\n catchError {\n timeout(buildData.timeout) {\n stages.preClean()\n stages.checkout()\n stages.version()\n stages.build()\n stages.test()\n stages.push()\n stages.tag()\n stages.archive()\n stages.postClean()\n }\n }\n\n stages.report()\n }\n }\n}\n","avg_line_length":22.4571428571,"max_line_length":70,"alphanum_fraction":0.6005089059} +{"size":1691,"ext":"groovy","lang":"Groovy","max_stars_count":2.0,"content":"package com.hmtmcse.dtm.controllers.api\n\nimport com.hmtmcse.gs.GsRestProcessor\nimport com.hmtmcse.dtm.definition.ComplexityDefinitionService\n\nclass ApiComplexityV1Controller extends GsRestProcessor {\n\n ComplexityDefinitionService complexityDefinitionService\n\n def postCreate() {\n return create(complexityDefinitionService.create())\n }\n\n def postUpdate() {\n return update(complexityDefinitionService.update())\n }\n\n def getList() {\n return list(complexityDefinitionService.list())\n }\n\n def getDetails() {\n return details(complexityDefinitionService.details())\n }\n\n def getDetailsByTodo() {\n return customProcessor(complexityDefinitionService.getDetailsByTodo())\n }\n\n def getClone() {\n return customProcessor(complexityDefinitionService.getCloneComplexity())\n }\n\n def postClone() {\n return customProcessor(complexityDefinitionService.getCloneComplexity())\n }\n\n def getChangeStatus() {\n return customProcessor(complexityDefinitionService.changeStatus())\n }\n\n def postChangeStatus() {\n return customProcessor(complexityDefinitionService.changeStatus())\n }\n\n def getDetailsByTodoAndType() {\n return customProcessor(complexityDefinitionService.getDetailsByTodoAndType())\n }\n\n def postDetails() {\n return details(complexityDefinitionService.details())\n }\n\n def deleteDelete() {\n return delete(complexityDefinitionService.delete())\n }\n\n def deleteSoftDelete() {\n return update(complexityDefinitionService.softDelete())\n }\n\n def postSaveSort() {\n return customProcessor(complexityDefinitionService.saveSort())\n }\n\n}\n","avg_line_length":25.2388059701,"max_line_length":85,"alphanum_fraction":0.7143701952} +{"size":870,"ext":"groovy","lang":"Groovy","max_stars_count":104.0,"content":"package com.cezarykluczynski.stapi.server.species.mapper\n\nimport com.cezarykluczynski.stapi.client.v1.rest.model.SpeciesHeader\nimport com.cezarykluczynski.stapi.model.species.entity.Species\nimport com.cezarykluczynski.stapi.server.common.mapper.AbstractRealWorldPersonMapperTest\nimport com.google.common.collect.Lists\nimport org.mapstruct.factory.Mappers\n\nclass SpeciesHeaderRestMapperTest extends AbstractRealWorldPersonMapperTest {\n\n\tprivate SpeciesHeaderRestMapper speciesHeaderRestMapper\n\n\tvoid setup() {\n\t\tspeciesHeaderRestMapper = Mappers.getMapper(SpeciesHeaderRestMapper)\n\t}\n\n\tvoid \"maps DB entity to SOAP header\"() {\n\t\tgiven:\n\t\tSpecies species = new Species(\n\t\t\t\tname: NAME,\n\t\t\t\tuid: UID)\n\n\t\twhen:\n\t\tSpeciesHeader speciesHeader = speciesHeaderRestMapper.map(Lists.newArrayList(species))[0]\n\n\t\tthen:\n\t\tspeciesHeader.name == NAME\n\t\tspeciesHeader.uid == UID\n\t}\n\n}\n","avg_line_length":27.1875,"max_line_length":91,"alphanum_fraction":0.808045977} +{"size":3240,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"package javaposse.jobdsl.dsl.helpers.step\nimport com.google.common.base.Preconditions\nimport javaposse.jobdsl.dsl.helpers.AbstractContextHelper\n\nclass ConditionalStepsContext extends AbstractStepContext {\n\n RunConditionContext conditionContext\n String runnerClass\n\n ConditionalStepsContext() {\n super()\n }\n\n ConditionalStepsContext(String runnerName, Closure conditionClosure) {\n this(runnerName, [], conditionClosure)\n }\n\n ConditionalStepsContext(String runnerName, List stepNodes, Closure conditionClosure) {\n super(stepNodes)\n Preconditions.checkArgument(EvaluationRunners.find(runnerName) != null, \"${runnerName} not a valid evaluation runner.\")\n\n condition(conditionClosure)\n\n this.runnerClass = EvaluationRunners.find(runnerName)\n }\n\n def condition(Closure conditionClosure) {\n conditionContext = new RunConditionContext()\n\n AbstractContextHelper.executeInContext(conditionClosure, conditionContext)\n\n Preconditions.checkNotNull(conditionContext?.conditionName, \"No condition name specified\")\n }\n\n def runner(String runnerName) {\n Preconditions.checkArgument(EvaluationRunners.find(runnerName) != null, \"${runnerName} not a valid runner.\")\n runnerClass = EvaluationRunners.find(runnerName).longForm\n }\n\n def runner(EvaluationRunners runner) {\n runnerClass = runner.longForm\n }\n\n protected def createSingleStepNode() {\n def nodeBuilder = new NodeBuilder()\n\n return nodeBuilder.'org.jenkinsci.plugins.conditionalbuildstep.singlestep.SingleConditionalBuilder' {\n condition(class: conditionContext.conditionClass()) {\n conditionContext.conditionArgs.each { k, v ->\n \"${k}\" v\n }\n }\n runner(class: runnerClass)\n buildStep(class: stepNodes[0].name()) {\n stepNodes[0].children().each { c ->\n \"${c.name()}\"(c.attributes(), c.value())\n }\n }\n }\n }\n\n protected def createMultiStepNode() {\n def nodeBuilder = new NodeBuilder()\n\n return nodeBuilder.'org.jenkinsci.plugins.conditionalbuildstep.ConditionalBuilder' {\n runCondition(class: conditionContext.conditionClass()) {\n conditionContext.conditionArgs.each { k, v ->\n \"${k}\" v\n }\n }\n runner(class: runnerClass)\n conditionalBuilders(stepNodes)\n }\n }\n\n public static enum EvaluationRunners {\n Fail('org.jenkins_ci.plugins.run_condition.BuildStepRunner$Fail'),\n Unstable('org.jenkins_ci.plugins.run_condition.BuildStepRunner$Unstable'),\n RunUnstable('org.jenkins_ci.plugins.run_condition.BuildStepRunner$RunUnstable'),\n Run('org.jenkins_ci.plugins.run_condition.BuildStepRunner$Run'),\n DontRun('org.jenkins_ci.plugins.run_condition.BuildStepRunner$DontRun')\n\n final String longForm\n\n EvaluationRunners(String longForm) {\n this.longForm = longForm\n }\n\n public static find(String enumName) {\n values().find { it.name().toLowerCase() == enumName.toLowerCase() }\n }\n\n }\n}\n","avg_line_length":34.1052631579,"max_line_length":127,"alphanum_fraction":0.6567901235} +{"size":2311,"ext":"groovy","lang":"Groovy","max_stars_count":2.0,"content":"import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint\nimport static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase\nimport static com.kms.katalon.core.testdata.TestDataFactory.findTestData\nimport static com.kms.katalon.core.testobject.ObjectRepository.findTestObject\nimport static com.kms.katalon.core.testobject.ObjectRepository.findWindowsObject\nimport com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint\nimport com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords as CucumberKW\nimport com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile\nimport com.kms.katalon.core.model.FailureHandling as FailureHandling\nimport com.kms.katalon.core.testcase.TestCase as TestCase\nimport com.kms.katalon.core.testdata.TestData as TestData\nimport com.kms.katalon.core.testobject.TestObject as TestObject\nimport com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS\nimport com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI\nimport com.kms.katalon.core.windows.keyword.WindowsBuiltinKeywords as Windows\nimport internal.GlobalVariable as GlobalVariable\nimport org.openqa.selenium.Keys as Keys\n\nWebUI.openBrowser('')\n\nWebUI.navigateToUrl('http:\/\/localhost:8080\/')\n\nWebUI.click(findTestObject('Object Repository\/Page_UniSeat - Home\/a_Accedi'))\n\nWebUI.setText(findTestObject('Object Repository\/Page_Login\/input_Accedi_email'), 'a.decaro@studenti.unisa.it')\n\nWebUI.click(findTestObject('Object Repository\/Page_Login\/label_Password'))\n\nWebUI.setEncryptedText(findTestObject('Object Repository\/Page_Login\/input_E-Mail_password'), '2KQzu\/1eCRtlfOXIb806pg==')\n\nWebUI.click(findTestObject('Object Repository\/Page_Login\/button_Accedi'))\n\nWebUI.click(findTestObject('Object Repository\/Page_UniSeat - Home\/a_Seleziona'))\n\nWebUI.navigateToUrl('http:\/\/localhost:8080\/_comuni\/aule.jsp?edificio=F3#services')\n\nWebUI.click(findTestObject('Page_UniSeat - Edificio F3\/button_Prenota PostoP4'))\n\nWebUI.setText(findTestObject('Page_UniSeat - Edificio F3\/input_Durata _956af2'), '30')\n\nWebUI.click(findTestObject('Page_UniSeat - Edificio F3\/button_Prenota'))\n\nactual = WebUI.getText(findTestObject('Page_UniSeat - Edificio F3\/alertDialog'))\n\nexpected = 'Aula non disponibile'\n\nassert actual.equals(expected)\n\nWebUI.closeBrowser()\n\n","avg_line_length":45.3137254902,"max_line_length":120,"alphanum_fraction":0.8277801817} +{"size":399,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"package com.blazinc.invfriend.domain.repository\n\nimport com.blazinc.invfriend.domain.entity.Question\nimport org.springframework.data.mongodb.repository.MongoRepository\nimport org.springframework.stereotype.Repository\n\n\/**\n * User mongoDB repository\n *\/\n@Repository\ninterface QuestionRepository extends MongoRepository {\n\n Question findByQuestionNumber(Integer questionNumber)\n}\n","avg_line_length":26.6,"max_line_length":72,"alphanum_fraction":0.8370927318} +{"size":21010,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Copyright 2000-2014 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.jetbrains.plugins.groovy.lang.highlighting\n\nimport com.intellij.codeInsight.intention.IntentionAction\nimport com.intellij.codeInspection.InspectionProfileEntry\nimport org.jetbrains.plugins.groovy.codeInspection.assignment.GroovyAssignabilityCheckInspection\nimport org.jetbrains.plugins.groovy.codeInspection.bugs.GroovyConstructorNamedArgumentsInspection\nimport org.jetbrains.plugins.groovy.codeInspection.confusing.GroovyResultOfIncrementOrDecrementUsedInspection\nimport org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.GrUnresolvedAccessInspection\n\n\/**\n * @author Max Medvedev\n *\/\nclass GrAssignabilityTest extends GrHighlightingTestBase {\n InspectionProfileEntry[] getCustomInspections() { [new GroovyAssignabilityCheckInspection()] }\n\n public void testIncompatibleTypesAssignments() { doTest(); }\n\n public void testDefaultMapConstructorNamedArgs() {\n addBigDecimal()\n doTest(new GroovyConstructorNamedArgumentsInspection());\n }\n\n public void testDefaultMapConstructorNamedArgsError() {\n addBigDecimal()\n doTest(new GroovyConstructorNamedArgumentsInspection());\n }\n\n public void testDefaultMapConstructorWhenDefConstructorExists() {\n doTest(new GroovyConstructorNamedArgumentsInspection());\n }\n\n public void testUnresolvedMethodCallWithTwoDeclarations() {\n doTest();\n }\n\n public void testConstructor() {\n doTest(new GroovyConstructorNamedArgumentsInspection());\n }\n\n public void testEverythingAssignableToString() {doTest();}\n\n public void testMethodCallWithDefaultParameters() {doTest();}\n\n public void testClosureWithDefaultParameters() {doTest();}\n\n public void testClosureCallMethodWithInapplicableArguments() {doTest();}\n\n public void testCallIsNotApplicable() {doTest();}\n\n public void testPathCallIsNotApplicable() {doTest();}\n\n public void testByteArrayArgument() {doTest();}\n\n public void testPutValueToEmptyMap() {doTest();}\n\n public void _testPutIncorrectValueToMap() {doTest();} \/\/incorrect test\n\n public void testTupleTypeAssignments() {\n addBigDecimal();\n doTest();\n }\n\n public void testSignatureIsNotApplicableToList() {\n doTest();\n }\n\n public void testInheritConstructorsAnnotation() {\n doTest();\n }\n\n public void testCollectionAssignments() {doTest(); }\n\n public void testReturnAssignability() {doTest(); }\n\n public void testMapNotAcceptedAsStringParameter() {doTest();}\n\n public void testRawTypeInAssignment() {doTest();}\n\n public void testMapParamWithNoArgs() {doTest();}\n\n public void testInheritInterfaceInDelegate() {\n doTest();\n }\n\n public void testThisTypeInStaticContext() {\n doTest();\n }\n\n public void testAnonymousClassArgList() {\n doTest();\n }\n\n public void testTupleConstructorAttributes() {\n doTest();\n }\n\n public void testCanonicalConstructorApplicability() {\n myFixture.addClass(\"package groovy.transform; public @interface Canonical {}\");\n doTest();\n }\n\n public void testStringAssignableToChar() {\n doTest();\n }\n\n\n public void testCurrying() {\n doTest();\n }\n\n public void testAnotherCurrying() {\n doTest();\n }\n\n public void testResultOfIncUsed() {\n doTest(new GroovyResultOfIncrementOrDecrementUsedInspection());\n }\n\n public void testNativeMapAssignability() {\n doTest();\n }\n\n public void testTwoLevelGrMap() {\n doTest();\n }\n\n public void testPassingCollectionSubtractionIntoGenericMethod() {\n doTest(new GrUnresolvedAccessInspection());\n }\n\n public void testImplicitEnumCoercion() {\n doTest();\n }\n\n public void testUnknownVarInArgList() {\n doTest();\n }\n\n public void testCallableProperty() {\n doTest();\n }\n\n public void testEnumConstantConstructors() {\n doTest();\n }\n\n public void testLiteralConstructorUsages() {\n doTest();\n }\n\n public void testSpreadArguments() {\n doTest();\n }\n\n public void testDiamondTypeInferenceSOE() {\n testHighlighting(''' Map a; a[2] = [:] ''', false, false, false)\n }\n\n void _testThisInStaticMethodOfAnonymousClass() {\n testHighlighting('''\\\nclass A {\n static abc\n def foo() {\n new Runnable() {\n static<\/error> void run() {\n print abc\n }\n }.run()\n }\n}''', true, false, false);\n }\n\n public void testNonInferrableArgsOfDefParams() {\n testHighlighting('''\\\ndef foo0(def a) { }\ndef bar0(def b) { foo0(b) }\n\ndef foo1(Object a) { }\ndef bar1(def b) { foo1(b) }\n\ndef foo2(String a) { }\ndef bar2(def b) { foo2(b)<\/weak_warning> }\n''')\n }\n\n public void testPutAtApplicability() {\n myFixture.addClass(\"\"\"\\\npackage java.util;\npublic class LinkedHashMap extends HashMap implements Map {}\n\"\"\")\n\n testHighlighting('''\\\nLinkedHashMap> files = [:]\nfiles[new File('a')] = [new File('b')]\nfiles[new File('a')]<\/warning> = new File('b')\n''')\n }\n\n public void testStringToCharAssignability() {\n testHighlighting('''\\\ndef foo(char c){}\n\nfoo('a')<\/warning>\nfoo('a' as char)\nfoo('a' as Character)\n\nchar c = 'a'\n''')\n }\n\n void testMethodRefs1() {\n testHighlighting('''\\\nclass A {\n int foo(){2}\n\n Date foo(int x) {null}\n}\n\ndef foo = new A().&foo\n\nint i = foo()\nint i2<\/warning> = foo(2)\nDate d = foo(2)\nDate d2<\/warning> = foo()\n''')\n }\n\n void testMethodRefs2() {\n testHighlighting('''\\\nclass Bar {\n def foo(int i, String s2) {s2}\n def foo(int i, int i2) {i2}\n}\n\ndef cl = new Bar.<\/error>&foo\ncl = cl.curry(1)\nString s = cl(\"2\")\nint s2<\/warning> = cl(\"2\")\nint i = cl(3)\nString i2 = cl(3)\n''')\n }\n\n void testThrowObject() {\n testHighlighting('''\\\ndef foo() {\n throw new RuntimeException()\n}\ndef bar () {\n throw<\/warning> new Object()\n}\n\ndef test() {\n throw new Throwable()\n}\n''')\n }\n\n void testCategoryWithPrimitiveType() {\n testHighlighting('''\\\nclass Cat {\n static foo(Integer x) {}\n}\n\nuse(Cat) {\n 1.with {\n foo()\n }\n\n (1 as int).foo()\n}\n\nclass Ca {\n static foo(int x) {}\n}\n\nuse(Ca) {\n 1.foo<\/warning>()\n (1 as int).foo<\/warning>()\n}\n''')\n }\n\n void testCompileStaticWithAssignabilityCheck() {\n myFixture.addClass('''\\\npackage groovy.transform;\npublic @interface CompileStatic {\n}''')\n\n testHighlighting('''\\\nimport groovy.transform.CompileStatic\n\nclass A {\n\n def foo(String s) {\n int x<\/warning> = new Date()\n }\n\n @CompileStatic\n def bar() {\n int x<\/error> = new Date()\n }\n}\n''')\n }\n\n void testClosuresInAnnotations() {\n testHighlighting('''\\\n@interface Test {\n Class value()\n}\n\n@interface Other {\n String value()\n}\n\n@Test({String}) def foo1(){}\n@Test({2.class}) def foo2(){}\n@Test({2}) def foo3(){}\n@Test({abc}) def foo4(){}\n@Test(String) def foo5(){}\n''')\n }\n\n void testTupleAssignment() {\n testHighlighting('''\\\ndef (String x, int y)\n(x, y<\/warning>) = foo()\n\nprint x + y\n\nList foo() {[]}\n''')\n }\n\n void testTupleDeclaration() {\n testHighlighting('''\\\ndef (int x<\/warning>, String y) = foo()\n\nList foo() {[]}\n''')\n }\n\n void testCastClosureToInterface() {\n testHighlighting('''\\\ninterface Function {\n F fun(D d)\n}\n\ndef foo(Function function) {\n \/\/ print function.fun('abc')\n}\n\n\nfoo)'\">({println it.byteValue()} as Function)<\/warning>\nfoo({println it.substring(1)} as Function)\nfoo({println it.substring(1)} as Function)\nfoo({println it})<\/warning>\n\n''')\n }\n\n void testVarargsWithoutTypeName() {\n testHighlighting('''\\\ndef foo(String key, ... params) {\n\n}\n\nfoo('anc')\nfoo('abc', 1, '')\nfoo(5)<\/warning>\n''')\n }\n\n void testIncorrectReturnValue() {\n testHighlighting('''\\\nprivate int getObjects() {\n try {\n def t = \"test\";\n t.substring(0);\n }\n finally {\n \/\/...\n }\n\n return<\/warning> '';;\n}\n''')\n }\n\n\n void testForInAssignability() {\n testHighlighting('''\\\nfor (int x<\/warning> in ['a']){}\n''')\n }\n\n void testAssignabilityOfMethodProvidedByCategoryAnnotation() {\n testHighlighting('''\\\n@Category(List)\nclass EvenSieve {\n def getNo2() {\n removeAll { 4 % 2 == 0 } \/\/correct access\n add' cannot be applied to '(java.lang.Integer, java.lang.Integer)'\">(2, 3)<\/warning>\n }\n}\n''')\n }\n\n void testAssignabilityOfCategoryMethod() {\n testHighlighting('''\nclass Cat {\n static foo(Class c, int x) {}\n}\n\nclass X {}\n\nuse(Cat) {\n X.foo(1)\n}\n\n''')\n }\n\n void testImplicitConversionToArray() {\n testHighlighting('''\\\nString[] foo() {\n return 'ab'\n}\n\nString[] foox() {\n return 2\n}\n\nint[] bar() {\n return<\/warning> 'ab'\n}\n''')\n }\n\n void testAssignNullToPrimitiveTypesAndWrappers() {\n testHighlighting('''\\\nint x<\/warning> = null\ndouble y<\/warning> = null\nboolean a = null\nInteger z = null\nBoolean b = null\nInteger i = null\n''')\n }\n\n void testAssignNullToPrimitiveParameters() {\n testHighlighting('''\\\ndef _int(int x) {}\ndef _boolean(boolean x) {}\ndef _Boolean(Boolean x) {}\n\n_int(null)<\/warning>\n_boolean(null)<\/warning>\n_Boolean(null)\n''')\n }\n\n void testInnerWarning() {\n testHighlighting('''\\\npublic static void main(String[] args) {\n bar (foo(foo(foo('2')<\/warning>)))<\/warning>\n}\n\nstatic def T foo(T abc) {\n abc\n}\n\nstatic bar(String s) {\n\n}\n''')\n }\n\n void testLiteralConstructorWithNamedArgs() {\n testHighlighting('''\\\nimport groovy.transform.Immutable\n\n@Immutable class Money {\n String currency\n int amount\n}\n\nMoney d = [amount: 100, currency:'USA']\n\n''')\n }\n\n void testBooleanIsAssignableToAny() {\n testHighlighting('''\\\n boolean b1 = new Object()\n boolean b2 = null\n Boolean b3 = new Object()\n Boolean b4 = null\n''')\n }\n\n void testArrayAccess() {\n testHighlighting('''\\\nint [] i = [1, 2]\n\nprint i[1]\nprint i[1, 2]<\/warning>\nprint i[1..2]\nprint i['a']\nprint i['a', 'b']<\/warning>\n''')\n }\n\n void testArrayAccess2() {\n testHighlighting('''\\\nint[] i() { [1, 2] }\n\nprint i()[1]\nprint i()[1, 2]<\/warning>\nprint i()[1..2]\nprint i()['a']\nprint i()['a', 'b']<\/warning>\n''')\n }\n\n void testArrayAccess3() {\n testHighlighting('''\\\nclass X {\n def getAt(int x) {''}\n}\n\nX i() { new X() }\n\nprint i()[1]\nprint i()[1, 2]<\/warning>\nprint i()[1..2]<\/warning>\nprint i()['a']\nprint i()['a', 'b']<\/warning>\n''')\n }\n\n void testArrayAccess4() {\n testHighlighting('''\\\nclass X {\n def getAt(int x) {''}\n}\n\nX i = new X()\n\nprint i[1]\nprint i[1, 2]<\/warning>\nprint i[1..2]<\/warning>\nprint i['a']\nprint i['a', 'b']<\/warning>\n''')\n }\n\n void testArrayAccess5() {\n testHighlighting('''\\\nprint a[1, 2]<\/warning>\n''')\n }\n\n void testArrayAccess6() {\n testHighlighting('''\\\nint[] i = [1, 2]\n\ni[1] = 2\ni[1, 2]<\/warning> = 2\ni[1]<\/warning> = 'a'\ni['a'] = 'b'\ni['a', 'b']<\/warning> = 1\n''')\n }\n\n void testArrayAccess7() {\n testHighlighting('''\\\nint[] i() { [1, 2] }\n\ni()[1] = 2\ni()[1, 2]<\/warning> = 2\ni()[1]<\/warning> = 'a'\ni()['a'] = 'b'\ni()['a', 'b']<\/warning> = 1\n''')\n }\n\n void testArrayAccess8() {\n testHighlighting('''\\\nclass X {\n def putAt(int x, int y) {''}\n}\n\nX i() { new X() }\n\ni()[1] = 2\ni()[1, 2]<\/warning> = 2\ni()[1]<\/warning> = 'a'\ni()['a'] = 'b'\ni()['a', 'b']<\/warning> = 1\n''')\n }\n\n void testArrayAccess9() {\n testHighlighting('''\\\nclass X {\n def putAt(int x, int y) {''}\n}\n\nX i = new X()\n\ni[1] = 2\ni[1, 2]<\/warning> = 2\ni[1]<\/warning> = 'a'\ni['a'] = 'b'\ni['a', 'b']<\/warning> = 1\n''')\n }\n\n void testArrayAccess10() {\n testHighlighting('''\\\na[1, 3]<\/warning> = 2\n''')\n }\n\n public void testVarWithInitializer() {\n testHighlighting('''\\\nObject o = new Date()\nfoo(o)\nbar(o)<\/warning>\n\ndef foo(Date d) {}\ndef bar(String s) {}\n''')\n }\n\n void testClassTypesWithMadGenerics() {\n testHighlighting('''\\\n\/\/no warnings are expected!\n\nclass CollectionTypeTest {\n void implicitType() {\n def classes = [String, Integer]\n assert classNames(classes + [Double, Long]) == ['String', 'Integer', 'Double', 'Long'] \/\/ warning here\n assert classNames([Double, Long] + classes) == ['Double', 'Long', 'String', 'Integer']\n }\n\n void explicitInitType() {\n Collection classes = [String, Integer]\n assert classNames(classes + [Double, Long]) == ['String', 'Integer', 'Double', 'Long']\n assert classNames([Double, Long] + classes) == ['Double', 'Long', 'String', 'Integer'] \/\/ warning here\n }\n\n void explicitSumType() {\n Collection classes = [String, Integer]\n assert classNames(classes + [Double, Long]) == ['String', 'Integer', 'Double', 'Long']\n\n Collection var = [Double, Long] + classes\n assert classNames(var) == ['Double', 'Long', 'String', 'Integer']\n }\n\n private static Collection classNames(Collection classes) {\n return classes.collect { it.simpleName }\n }\n}\n''')\n }\n\n void testParameterInitializerWithGenericType() {\n testHighlighting('''\\\nclass PsiElement {}\nclass Foo extends PsiElement implements I {}\n\ninterface I {}\n\ndef T foo1(Class ' to 'Class'\">x<\/warning> = String ) {}\ndef T foo2(Class x = PsiElement ) {}\ndef T foo3(Class x = PsiElement ) {}\ndef T foo4(Class ' to 'Class'\">x<\/warning> = PsiElement ) {}\ndef T foo5(Class x = Foo ) {}\n''')\n }\n\n void testFixVariableType() {\n testHighlighting('''\\\nint xx<\/warning> = 'abc'\n''')\n\n\n final IntentionAction intention = myFixture.findSingleIntention('Change variable')\n myFixture.launchAction(intention)\n myFixture.checkResult('''\\\nString xx = 'abc'\n''')\n\n }\n\n void testFixVariableType2() {\n testHighlighting('''\\\nint xx = 5\n\nxx<\/warning> = 'abc'\n''')\n\n final IntentionAction intention = myFixture.findSingleIntention('Change variable')\n myFixture.launchAction(intention)\n myFixture.checkResult('''\\\nString xx = 5\n\nxx = 'abc'\n''')\n\n }\n\n\n void testInnerClassConstructor0() {\n testHighlighting('''\\\nclass A {\n class Inner {\n def Inner() {}\n }\n\n def foo() {\n new Inner() \/\/correct\n }\n\n static def bar() {\n new Inner<\/error>() \/\/semi-correct\n new Inner(new A()) \/\/correct\n }\n}\n\nnew A.Inner() \/\/semi-correct\nnew A.Inner(new A()) \/\/correct\n''')\n }\n\n void testInnerClassConstructor1() {\n testHighlighting('''\\\nclass A {\n class Inner {\n def Inner(A a) {}\n }\n\n def foo() {\n new Inner(new A()) \/\/correct\n new Inner()<\/warning>\n new Inner(new A(), new A())<\/warning>\n }\n\n static def bar() {\n new Inner(new A(), new A()) \/\/correct\n new Inner(new A())<\/warning> \/\/incorrect: first arg is recognized as an enclosing instance arg\n }\n}\n\nnew A.Inner()<\/warning> \/\/incorrect\nnew A.Inner(new A())<\/warning> \/\/incorrect: first arg is recognized as an enclosing instance arg\nnew A.Inner(new A(), new A()) \/\/correct\n''')\n }\n\n void testClosureIsNotAssignableToSAMInGroovy2_1() {\n testHighlighting('''\\\ninterface X {\n def foo()\n}\n\nX x<\/warning> = {print 2}\n''')\n }\n\n void testVoidMethodAssignability() {\n testHighlighting('''\\\nvoid foo() {}\n\ndef foo = foo()\n\ndef bar() {\n foo() \/\/no warning\n}\n\ndef zoo() {\n return foo()\n}\n''')\n }\n\n void testBinaryOperatorApplicability() {\n testHighlighting('''\\\nvoid bug(Collection foo, Collection bar) {\n foo )'\"><<<\/warning> bar \/\/ warning missed\n foo << \"a\"\n}''')\n }\n\n void testPlusIsApplicable() {\n testHighlighting('''\\\nprint 1 + 2\n\nprint 4 +<\/warning> new ArrayList()\n''')\n }\n}\n","avg_line_length":25.5907429963,"max_line_length":192,"alphanum_fraction":0.6634459781} +{"size":2856,"ext":"groovy","lang":"Groovy","max_stars_count":282.0,"content":"\/*\n * Copyright 2014-2019 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage nebula.plugin.dependencylock.tasks\n\nimport nebula.plugin.dependencylock.exceptions.DependencyLockException\nimport nebula.plugin.scm.providers.ScmFactory\nimport nebula.plugin.scm.providers.ScmProvider\nimport org.gradle.api.tasks.Input\nimport org.gradle.api.tasks.Internal\nimport org.gradle.api.tasks.Optional\nimport org.gradle.api.tasks.TaskAction\nimport org.gradle.api.tasks.TaskExecutionException\n\nclass CommitLockTask extends AbstractLockTask {\n @Internal\n String description = 'Commit the lock files if an gradle-scm-plugin implementation is applied'\n\n @Internal\n ScmFactory scmFactory\n\n @Input\n @Optional\n String branch\n\n @Input\n @Optional\n String commitMessage\n\n @Input\n @Optional\n List patternsToCommit\n\n @Input\n @Optional\n Boolean shouldCreateTag = false\n\n @Input\n @Optional\n String tag\n\n @Input\n @Optional\n Integer remoteRetries = 3\n\n @TaskAction\n void commit() {\n ScmProvider provider = getScmFactory().create()\n\n commitLocks(provider)\n\n if (getShouldCreateTag()) {\n provider.tag(getTag(), \"Creating ${getTag()}\")\n }\n }\n\n private commitLocks(ScmProvider provider) {\n int commitTries = 0\n boolean successfulCommit = false\n\n while ((commitTries < getRemoteRetries()) && !successfulCommit) {\n successfulCommit = provider.commit(getCommitMessage(), getPatternsToCommit())\n logger.info(\"Commit returns: ${successfulCommit}\")\n if (!successfulCommit) {\n commitTries++\n if ((commitTries < getRemoteRetries()) && provider.updateFromRepository()) {\n logger.info('Grabbed latest changes from repository')\n logger.info('Retrying commit')\n } else {\n logger.error('SCM update failed')\n throw new TaskExecutionException(this, new DependencyLockException('Cannot commit locks, cannot update from repository'))\n }\n }\n }\n\n if (!successfulCommit) {\n logger.error('SCM update failed')\n throw new TaskExecutionException(this, new DependencyLockException('Cannot commit locks'))\n }\n }\n}\n","avg_line_length":30.3829787234,"max_line_length":141,"alphanum_fraction":0.668767507} +{"size":328,"ext":"groovy","lang":"Groovy","max_stars_count":1.0,"content":"package com.cabolabs.openehr.opt.model.domain\n\nimport com.cabolabs.openehr.opt.model.IntervalFloat\nimport com.cabolabs.openehr.opt.model.IntervalInt\n\n@groovy.util.logging.Log4j\nclass CQuantityItem {\n\n \/\/ property: CODE_PHRASE\n IntervalFloat magnitude \/\/ can be null\n IntervalInt precision \/\/ can be null\n String units\n}\n","avg_line_length":23.4285714286,"max_line_length":51,"alphanum_fraction":0.7835365854} +{"size":1065,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"package uk.co.littlemike.gradle.webapp.version\n\nimport org.gradle.api.Plugin\nimport org.gradle.api.Project\n\nclass WebappVersionPlugin implements Plugin {\n private static final String FILENAME = 'version.json';\n\n @Override\n void apply(Project project) {\n File fileLocation = new File(project.buildDir, 'webapp-version');\n\n project.apply(plugin: 'uk.co.littlemike.build-version-plugin')\n project.task('generate-version-json') << {\n writeVersionFile(fileLocation, new VersionInfo(\n buildInfo: project.buildInfo,\n projectVersion: project.version))\n }\n\n project.apply(plugin: 'war')\n project.war.dependsOn('generate-version-json')\n project.war {\n from(fileLocation) {\n include FILENAME\n }\n }\n }\n\n void writeVersionFile(File location, VersionInfo versionInfo) {\n location.mkdirs();\n File file = new File(location, FILENAME)\n file.delete()\n file << versionInfo.asJson()\n }\n}\n","avg_line_length":29.5833333333,"max_line_length":73,"alphanum_fraction":0.6253521127} +{"size":1658,"ext":"groovy","lang":"Groovy","max_stars_count":2.0,"content":"\/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage com.thoughtworks.go.apiv4.dashboard\n\nimport com.thoughtworks.go.config.remote.FileConfigOrigin\nimport com.thoughtworks.go.config.security.Permissions\nimport com.thoughtworks.go.config.security.users.Everyone\nimport com.thoughtworks.go.server.dashboard.GoDashboardPipeline\nimport com.thoughtworks.go.server.dashboard.TimeStampBasedCounter\nimport com.thoughtworks.go.util.Clock\n\nimport static com.thoughtworks.go.helpers.PipelineModelMother.pipeline_model\nimport static org.mockito.Mockito.mock\nimport static org.mockito.Mockito.when\n\nclass GoDashboardPipelineMother {\n\n static GoDashboardPipeline dashboardPipeline(pipeline_name, group_name = \"group1\", permissions = new Permissions(Everyone.INSTANCE, Everyone.INSTANCE, Everyone.INSTANCE, Everyone.INSTANCE), timestamp = 1000L) {\n def clock = mock(Clock.class)\n when(clock.currentTimeMillis()).thenReturn(timestamp)\n new GoDashboardPipeline(pipeline_model(pipeline_name, 'pipeline-label'), permissions, group_name, null, new TimeStampBasedCounter(clock), new FileConfigOrigin(), 0)\n }\n}\n","avg_line_length":44.8108108108,"max_line_length":212,"alphanum_fraction":0.7967430639} +{"size":2328,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/*\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.netflix.spinnaker.igor\n\nimport groovy.transform.Canonical\nimport org.springframework.boot.context.properties.ConfigurationProperties\nimport org.springframework.boot.context.properties.NestedConfigurationProperty\n\n@Canonical\n@ConfigurationProperties\nclass IgorConfigurationProperties {\n static class SpinnakerProperties {\n @Canonical\n static class JedisProperties {\n String prefix = 'igor'\n }\n\n @NestedConfigurationProperty\n final JedisProperties jedis = new JedisProperties()\n\n @Canonical\n static class BuildProperties {\n int pollInterval = 60\n }\n\n @NestedConfigurationProperty\n final BuildProperties build = new BuildProperties()\n }\n\n @NestedConfigurationProperty\n final SpinnakerProperties spinnaker = new SpinnakerProperties()\n\n @Canonical\n static class RedisProperties {\n String connection = \"redis:\/\/localhost:6379\"\n int timeout = 2000\n }\n\n @NestedConfigurationProperty\n final RedisProperties redis = new RedisProperties()\n\n @Canonical\n static class ClientProperties {\n int timeout = 30000\n }\n\n @NestedConfigurationProperty\n final ClientProperties client = new ClientProperties()\n\n @Canonical\n static class ServicesProperties {\n @Canonical\n static class ServiceConfiguration {\n String baseUrl\n }\n\n @NestedConfigurationProperty\n final ServiceConfiguration clouddriver = new ServiceConfiguration()\n @NestedConfigurationProperty\n final ServiceConfiguration echo = new ServiceConfiguration()\n }\n\n @NestedConfigurationProperty\n final ServicesProperties services = new ServicesProperties()\n}\n","avg_line_length":29.1,"max_line_length":78,"alphanum_fraction":0.7173539519} +{"size":54997,"ext":"groovy","lang":"Groovy","max_stars_count":null,"content":"\/**\n * Copyright 2021\n *\n * Based on the original work done by https:\/\/github.com\/Wattos\/hubitat\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at:\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License\n * for the specific language governing permissions and limitations under the License.\n *\n * Home Connect Integration (APP for Home Conection API integration)\n *\n * Author: Rangner Ferraz Guimaraes (rferrazguimaraes)\n * Date: 2021-11-28\n * Version: 1.0 - Initial commit\n *\/\n\nimport groovy.transform.Field\nimport groovy.json.JsonSlurper\n\n@Field static String messageBuffer = \"\"\n@Field static Integer messageScopeCount = 0\n\ndefinition(\n name: 'Home Connect Integration',\n namespace: 'rferrazguimaraes',\n author: 'Rangner Ferraz Guimaraes',\n description: 'Integrates with Home Connect',\n category: 'My Apps',\n iconUrl: '',\n iconX2Url: '',\n iconX3Url: ''\n)\n\n@Field HomeConnectAPI = HomeConnectAPI_create(oAuthTokenFactory: {return getOAuthAuthToken()}, language: {return getLanguage()});\n@Field Utils = Utils_create();\n@Field List LOG_LEVELS = [\"error\", \"warn\", \"info\", \"debug\", \"trace\"]\n@Field String DEFAULT_LOG_LEVEL = LOG_LEVELS[1]\ndef driverVer() { return \"1.0\" }\n\n\/\/ ===== Settings =====\nprivate getClientId() { settings.clientId }\nprivate getClientSecret() { settings.clientSecret }\n\n\/\/ ===== Lifecycle methods ====\ndef installed() {\n Utils.toLogger(\"info\", \"installing Home Connect\")\n synchronizeDevices();\n}\n\ndef uninstalled() {\n Utils.toLogger(\"info\", \"uninstalled Home Connect\")\n deleteChildDevicesByDevices(getChildDevices());\n}\n\ndef updated() {\t\n Utils.toLogger(\"info\", \"updating with settings\")\n synchronizeDevices();\n}\n\n\/\/ ===== Helpers =====\ndef getHomeConnectAPI() {\n return HomeConnectAPI;\n}\n\ndef getUtils() {\n return Utils;\n}\n\n\/\/ ===== Pages =====\npreferences {\n page(name: \"pageIntro\")\n page(name: \"pageAuthentication\")\n page(name: \"pageDevices\")\n}\n\ndef pageIntro() {\n Utils.toLogger(\"debug\", \"Showing Introduction Page\");\n\n def countries = HomeConnectAPI.getSupportedLanguages();\n def countriesList = Utils.toFlattenMap(countries);\n if (region != null) {\n\t\tatomicState.langCode = region\n Utils.toLogger(\"debug\", \"atomicState.langCode: ${region}\")\n\t\tatomicState.countryCode = countriesList.find { it.key == region}?.value\n Utils.toLogger(\"debug\", \"atomicState.countryCode(${atomicState.countryCode})\")\n }\n\n return dynamicPage(\n name: 'pageIntro',\n title: 'Home Connect Introduction', \n nextPage: 'pageAuthentication',\n install: false, \n uninstall: true) {\n section(\"\"\"\\\n |This application connects to the Home Connect service.\n |It will allow you to monitor your smart appliances from Home Connect within Hubitat.\n |\n |Please note, before you can proceed, you will need to:\n | 1. Sign up at Home Connect Developer Portal<\/a>.\n | 2. Go to Home Connect Applications<\/a>.\n | 3. Register a new application with the following values:\n | * Application ID<\/b>: hubitat-homeconnect-integration\n | * OAuth Flow<\/b>: Authorization Code Grant Flow\n | * Redirect URI<\/b>: ${getFullApiServerUrl()}\/oauth\/callback\n | * You can leave the rest as blank\n | 4. Copy the following values down below.\n |\"\"\".stripMargin()) {}\n section('Enter your Home Connect Developer Details.') {\n input name: 'clientId', title: 'Client ID', type: 'text', required: true\n input name: 'clientSecret', title: 'Client Secret', type: 'text', required: true\n \t\t\tinput \"region\", \"enum\", title: \"Select your region\", options: countriesList, required: true\n \t\t\tinput \"logLevel\", \"enum\", title: \"Log Level\", options: LOG_LEVELS, defaultValue: DEFAULT_LOG_LEVEL, required: false\n }\n section('''\\\n |Press 'Next' to connect to your Home Connect Account.\n |'''.stripMargin()) {}\n }\n}\n\ndef pageAuthentication() {\n Utils.toLogger(\"debug\", \"Showing Authentication Page\");\n\n if (!atomicState.accessToken) {\n atomicState.accessToken = createAccessToken();\n }\n\n return dynamicPage(\n name: 'pageAuthentication', \n title: 'Home Connect Authentication',\n nextPage: 'pageDevices',\n install: false, \n uninstall: false) {\n section() {\n def title = \"Connect to Home Connect\"\n if (atomicState.oAuthAuthToken) {\n Utils.showHideNextButton(true);\n title = \"Re-connect to Home Connect\"\n paragraph 'Success!<\/b> You are connected to Home Connect. Please press the Next button.'\n } else {\n Utils.showHideNextButton(false);\n paragraph 'To continue, you need to connect your hubitat to Home connect. Please press the button below to connect'\n }\n \n href url: generateOAuthUrl(), style:'external', required:false, 'title': title\n }\n }\n}\n\ndef pageDevices() {\n HomeConnectAPI.getHomeAppliances() { devices -> homeConnectDevices = devices}\n def deviceList = [:]\n\tstate.foundDevices = []\n\thomeConnectDevices.each {\n deviceList << [\"${it.haId}\":\"${it.name} (${it.type}) (${it.haId})\"]\n\t\tstate.foundDevices << [haId: it.haId, name: it.name, type: it.type]\n\t}\n\n return dynamicPage(\n name: 'pageDevices', \n title: 'Home Connect Devices',\n install: true, \n uninstall: true) {\n section() {\n paragraph 'Select the following devices';\n input name: 'devices', title: 'Select Devices', type: 'enum', required: true, multiple:true, options: deviceList\n }\n }\n}\n\n\/\/ ==== App behaviour ====\n\ndef synchronizeDevices() {\n def childDevices = getChildDevices();\n def childrenMap = childDevices.collectEntries {\n [ \"${it.deviceNetworkId}\": it ]\n };\n\n for (homeConnectDeviceId in settings.devices) {\n def hubitatDeviceId = homeConnectIdToDeviceNetworkId(homeConnectDeviceId);\n\n if (childrenMap.containsKey(hubitatDeviceId)) {\n childrenMap.remove(hubitatDeviceId)\n continue;\n }\n\n def homeConnectDevice = state.foundDevices.find({it.haId == homeConnectDeviceId})\n switch(homeConnectDevice.type) {\n case \"Dishwasher\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect Dishwasher', hubitatDeviceId);\n break\n case \"Dryer\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect Dryer', hubitatDeviceId);\n break\n case \"Washer\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect Washer', hubitatDeviceId);\n break\n case \"WasherDryer\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect WasherDryer', hubitatDeviceId);\n break\n case \"FridgeFreezer\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect FridgeFreezer', hubitatDeviceId);\n break\n case \"Oven\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect Oven', hubitatDeviceId);\n break\n case \"CoffeeMaker\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect CoffeeMaker', hubitatDeviceId);\n break\n case \"Hood\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect Hood', hubitatDeviceId);\n break\n case \"Hob\":\n device = addChildDevice('rferrazguimaraes', 'Home Connect Hob', hubitatDeviceId);\n break\n default:\n Utils.toLogger(\"error\", \"Not supported: ${homeConnectDevice.type}\");\n break\n }\n }\n\n deleteChildDevicesByDevices(childrenMap.values());\n}\n\ndef deleteChildDevicesByDevices(devices) {\n for (d in devices) {\n deleteChildDevice(d.deviceNetworkId);\n }\n}\n\ndef homeConnectIdToDeviceNetworkId(haId) {\n return \"${haId}\"\n}\n\ndef intializeStatus(device) {\n def haId = device.deviceNetworkId\n \n Utils.toLogger(\"info\", \"Initializing the status of the device ${haId}\")\n HomeConnectAPI.getStatus(haId) { status ->\n device.deviceLog(\"info\", \"Status received: ${status}\")\n processMessage(device, status);\n }\n \n HomeConnectAPI.getSettings(haId) { settings ->\n device.deviceLog(\"info\", \"Settings received: ${settings}\")\n processMessage(device, settings);\n }\n\n try {\n HomeConnectAPI.getActiveProgram(haId) { activeProgram ->\n device.deviceLog(\"info\", \"ActiveProgram received: ${activeProgram}\")\n processMessage(device, activeProgram);\n }\n } catch (Exception e) {\n \/\/ no active program\n if(device.getDataValue(\"ActiveProgram\") != \"\") {\n device.sendEvent(name: \"ActiveProgram\", value: \"newStat\", descriptionText: \"Active Program changed to: ${newStat}\", displayed: true, isStateChange: true)\n }\n }\n}\n\ndef startProgram(device, programKey, optionKey = \"\") {\n Utils.toLogger(\"debug\", \"startProgram device: ${device}\")\n\n HomeConnectAPI.setActiveProgram(device.deviceNetworkId, programKey, optionKey) { availablePrograms ->\n Utils.toLogger(\"info\", \"setActiveProgram availablePrograms: ${availablePrograms}\")\n }\n}\n\ndef stopProgram(device) {\n Utils.toLogger(\"debug\", \"stopProgram device: ${device}\")\n\n HomeConnectAPI.setStopProgram(device.deviceNetworkId) { availablePrograms ->\n Utils.toLogger(\"info\", \"stopProgram availablePrograms: ${availablePrograms}\")\n }\n}\n\ndef setPowertate(device, boolean state) {\n Utils.toLogger(\"debug\", \"setPowertate from ${device} - ${state}\")\n\n HomeConnectAPI.setSettings(device.deviceNetworkId, \"BSH.Common.Setting.PowerState\", state ? \"BSH.Common.EnumType.PowerState.On\" : \"BSH.Common.EnumType.PowerState.Off\") { settings ->\n device.deviceLog(\"info\", \"Settings Sent: ${updateState}\")\n }\n}\n\ndef getAvailableProgramList(device) {\n Utils.toLogger(\"debug\", \"getAvailableProgramList device: ${device}\")\n def availableProgramList = []\n \n HomeConnectAPI.getAvailablePrograms(device.deviceNetworkId) { availablePrograms ->\n Utils.toLogger(\"info\", \"updateAvailableProgramList availablePrograms: ${availablePrograms}\")\n availableProgramList = availablePrograms\n }\n \n return availableProgramList\n}\n\ndef setSelectedProgram(device, programKey, optionKey = \"\") {\n Utils.toLogger(\"debug\", \"setSelectedProgram device: ${device}\")\n \n HomeConnectAPI.setSelectedProgram(device.deviceNetworkId, programKey, optionKey) { availablePrograms ->\n Utils.toLogger(\"info\", \"setSelectedProgram availablePrograms: ${availablePrograms}\")\n }\n}\n\ndef getAvailableProgramOptionsList(device, programKey) {\n Utils.toLogger(\"debug\", \"getAvailableProgramOptionsList device: ${device} - programKey: ${programKey}\")\n def availableProgramOptionsList = []\n \n HomeConnectAPI.getAvailableProgram(device.deviceNetworkId, \"${programKey}\") { availableProgram ->\n Utils.toLogger(\"debug\", \"updateAvailableOptionList availableProgram: ${availableProgram}\")\n if(availableProgram) { \n Utils.toLogger(\"debug\", \"updateAvailableOptionList availableProgram.options: ${availableProgram.options}\")\n availableProgramOptionsList = availableProgram.options\n }\n }\n \n return availableProgramOptionsList\n}\n\ndef setSelectedProgramOption(device, optionKey, optionValue) {\n Utils.toLogger(\"debug\", \"setSelectedProgramOption device: ${device} - optionKey: ${optionKey} - optionValue: ${optionValue}\")\n \n HomeConnectAPI.setSelectedProgramOption(device.deviceNetworkId, optionKey, optionValue) { availablePrograms ->\n Utils.toLogger(\"info\", \"setSelectedProgramOption availablePrograms: ${availablePrograms}\")\n }\n}\n\ndef processMessage(device, ArrayList textArrayList) {\n Utils.toLogger(\"debug\", \"processMessage from ${device} message array list: ${textArrayList}\")\n\n if (textArrayList == null || textArrayList.isEmpty()) { \n device.deviceLog(\"debug\", \"Ignore eventstream message\")\n return\n }\n \n def text = new groovy.json.JsonBuilder(textArrayList).toString()\n Utils.toLogger(\"debug\", \"processMessage from ${device} message text: ${text}\")\n \n if(!text.contains('items:')) {\n text = \"data:{\\\"items\\\":\" + text + \"}\"\n }\n \n processMessage(device, text);\n}\n\ndef processMessage(device, String text) {\n Utils.toLogger(\"debug\", \"processMessage from ${device} message: ${text}\")\n \n \/\/ EventStream is documented here\n \/\/ https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Server-sent_events\/Using_server-sent_events#event_stream_format\n\n \/\/ Ignore comment lines from event stream\n if (text == null || text.trim().isEmpty() || text.startsWith(':')) { \n device.deviceLog(\"debug\", \"Ignore eventstream message\")\n return\n }\n \n if(text.contains('items')) {\n if(!text.contains('data:')) {\n text = \"data:\" + text\n } \n } else { \n if(text.contains('{')) {\n messageBuffer += text\n messageScopeCount += 1\n device.deviceLog(\"debug\", \"text contains { - messageScopeCount:${messageScopeCount} - messageBuffer: ${messageBuffer}\") \n return \/\/ message not finished yet\n } else if(text.contains('}')) {\n messageBuffer += text\n messageScopeCount -= 1\n device.deviceLog(\"debug\", \"text contains } - messageScopeCount:${messageScopeCount} - messageBuffer: ${messageBuffer}\")\n if(messageScopeCount == 0) { \/\/ message finished\n if(messageBuffer.contains('error'))\n {\n text = \"error:\" + messageBuffer\n }\n device.deviceLog(\"debug\", \"messageBuffer complet: ${messageBuffer}\") \n device.deviceLog(\"debug\", \"text complet: ${text}\")\n } else {\n return \/\/ message not finished yet\n }\n } else if(!messageBuffer.isEmpty()) {\n messageBuffer += text\n device.deviceLog(\"debug\", \"message buffer concat - messageScopeCount:${messageScopeCount} - messageBuffer: ${messageBuffer}\")\n return \/\/ message not finished yet\n }\n }\n \n messageBuffer = \"\"\n \n \/\/ Parse the lines of data. Expected types are: event, data, id, retry -- all other fields ignored.\n def (String type, String message) = text.split(':', 2)\n device.deviceLog(\"debug\", \"type: ${type}\")\n device.deviceLog(\"debug\", \"message: ${message}\")\n switch (type) {\n case 'id':\n device.deviceLog(\"debug\", \"Received ID: ${message}\")\n break\n\n case 'data':\n device.deviceLog(\"debug\", \"Received data: ${message}\")\n if (!message.isEmpty()) { \/\/ empty messages are just KEEP-AlIVE messages\n def result = new JsonSlurper().parseText(message)?.items\n device.deviceLog(\"debug\", \"result: ${result}\")\n processData(device, result)\n }\n break\n\n case 'event':\n device.deviceLog(\"debug\", \"Received event: ${message}\")\n break\n\n case 'retry':\n device.deviceLog(\"debug\", \"Received retry: ${message}\")\n break\n\n case 'error':\n device.deviceLog(\"error\", \"Received error: ${message}\")\n def result = new JsonSlurper().parseText(message)\n \/\/device.deviceLog(\"error\", \"result: ${result}\")\n processData(device, result)\n break\n\n default:\n device.deviceLog(\"debug\", \"Received unknown data: ${text}\")\n } \n}\n\ndef processData(device, data) {\n Utils.toLogger(\"debug\", \"processData: ${device} - ${data}\")\n\n \/\/if(data instanceof ArrayList) {\n data.each {\n switch(it.key) {\n case \"BSH.Common.Status.DoorState\":\n device.sendEvent(name: \"DoorState\", value: \"${it.displayvalue}\", displayed: true, isStateChange: true)\n device.sendEvent(name: \"contact\", value: \"${it.displayvalue.toLowerCase()}\")\n break\n case \"BSH.Common.Status.OperationState\":\n device.sendEvent(name: \"OperationState\", value: \"${it.displayvalue}\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Status.RemoteControlActive\":\n device.sendEvent(name: \"RemoteControlActive\", value: \"${it.value}\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Status.RemoteControlStartAllowed\":\n device.sendEvent(name: \"RemoteControlStartAllowed\", value: \"${it.value}\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Setting.PowerState\":\n device.sendEvent(name: \"PowerState\", value: \"${it.displayvalue}\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Root.SelectedProgram\":\n device.sendEvent(name: \"SelectedProgram\", value: \"${it.displayvalue}\", displayed: true, isStateChange: true)\n device.updateSetting(\"selectedProgram\", [value:\"${it.displayvalue}\", type:\"enum\"])\n break\n case \"BSH.Common.Root.ActiveProgram\":\n device.sendEvent(name: \"ActiveProgram\", value: \"${it.displayvalue}\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Option.RemainingProgramTime\":\n device.sendEvent(name: \"RemainingProgramTime\", value: \"${Utils.convertSecondsToTime(it.value)}\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Option.ElapsedProgramTime\":\n device.sendEvent(name: \"ElapsedProgramTime\", value: \"${Utils.convertSecondsToTime(it.value)}\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Option.Duration\":\n device.sendEvent(name: \"Duration\", value: \"${Utils.convertSecondsToTime(it.value)}\", displayed: true, isStateChange: true)\n break \n case \"BSH.Common.Option.ProgramProgress\":\n device.sendEvent(name: \"ProgramProgress\", value: \"${it.value}%\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Option.StartInRelative\":\n device.sendEvent(name: \"StartInRelative\", value: \"${Utils.convertSecondsToTime(it.value)}\", displayed: true, isStateChange: true)\n break\n case \"BSH.Common.Event.ProgramFinished\":\n device.sendEvent(name: \"EventPresentState\", value: \"${it.displayvalue}\", displayed: true, isStateChange: true)\n break\n case \"Dishcare.Dishwasher.Option.IntensivZone\":\n device.sendEvent(name: \"IntensivZone\", value: \"${it.value}\", displayed: true, isStateChange: true)\n device.updateSetting(\"${it.name.replaceAll(\"\\\\s\",\"\")}\", [value:\"${it.value}\", type:\"bool\"])\n break\n case \"Dishcare.Dishwasher.Option.BrillianceDry\":\n device.sendEvent(name: \"BrillianceDry\", value: \"${it.value}\", displayed: true, isStateChange: true)\n device.updateSetting(\"${it.name.replaceAll(\"\\\\s\",\"\")}\", [value:\"${it.value}\", type:\"bool\"])\n break\n case \"Dishcare.Dishwasher.Option.VarioSpeedPlus\":\n device.sendEvent(name: \"VarioSpeedPlus\", value: \"${it.value}\", displayed: true, isStateChange: true)\n device.updateSetting(\"${it.name.replaceAll(\"\\\\s\",\"\")}\", [value:\"${it.value}\", type:\"bool\"])\n break\n case \"Dishcare.Dishwasher.Option.SilenceOnDemand\":\n device.sendEvent(name: \"SilenceOnDemand\", value: \"${it.value}\", displayed: true, isStateChange: true)\n device.updateSetting(\"${it.name.replaceAll(\"\\\\s\",\"\")}\", [value:\"${it.value}\", type:\"bool\"])\n break\n case \"Dishcare.Dishwasher.Option.HalfLoad\":\n device.sendEvent(name: \"HalfLoad\", value: \"${it.value}\", displayed: true, isStateChange: true)\n device.updateSetting(\"${it.name.replaceAll(\"\\\\s\",\"\")}\", [value:\"${it.value}\", type:\"bool\"])\n break\n case \"Dishcare.Dishwasher.Option.ExtraDry\":\n device.sendEvent(name: \"ExtraDry\", value: \"${it.value}\", displayed: true, isStateChange: true)\n device.updateSetting(\"${it.name.replaceAll(\"\\\\s\",\"\")}\", [value:\"${it.value}\", type:\"bool\"])\n break\n case \"Dishcare.Dishwasher.Option.HygienePlus\":\n device.sendEvent(name: \"HygienePlus\", value: \"${it.value}\", displayed: true, isStateChange: true)\n device.updateSetting(\"${it.name.replaceAll(\"\\\\s\",\"\")}\", [value:\"${it.value}\", type:\"bool\"])\n break\n case \"Cooking.Common.Option.Hood.VentingLevel\":\n device.sendEvent(name: \"VentingLevel\", value: \"${it.displayvalue}\", displayed: true, isStateChange: true)\n break\n case \"Cooking.Common.Option.Hood.IntensiveLevel\":\n device.sendEvent(name: \"IntensiveLevel\", value: \"${it.value}\", displayed: true, isStateChange: true)\n break\n case \"error\":\n device.sendEvent(name: \"LastErrorMessage\", value: \"${Utils.convertErrorMessageTime(it.value?.description)}\", displayed: true)\n break\n default:\n device.deviceLog(\"error\", \"Message not supported: (${it})\")\n break\n }\n }\n\/* } else if(data instanceof Map) {\n Utils.toLogger(\"debug\", \"It's a Map!\")\n data.each {\n switch(it.key) {\n default:\n device.deviceLog(\"debug\", \"Not supported: (${it})\")\n break\n }\n }\n }*\/\n}\n\n\/\/TODO: Move out into helper library\n\/\/ ===== Authentication =====\n\/\/ See Home Connect Developer documentation here: https:\/\/developer.home-connect.com\/docs\/authorization\/flow\nprivate final OAUTH_AUTHORIZATION_URL() { 'https:\/\/api.home-connect.com\/security\/oauth\/authorize' }\nprivate final OAUTH_TOKEN_URL() { 'https:\/\/api.home-connect.com\/security\/oauth\/token' }\nprivate final ENDPOINT_APPLIANCES() { '\/api\/homeappliances' }\n\nmappings {\n path(\"\/oauth\/callback\") {action: [GET: \"oAuthCallback\"]};\n}\n\ndef generateOAuthUrl() {\n atomicState.oAuthInitState = UUID.randomUUID().toString();\n def params = [\n 'client_id': getClientId(),\n 'redirect_uri': getOAuthRedirectUrl(),\n 'response_type': 'code',\n 'scope': 'IdentifyAppliance Monitor Settings Control',\n 'state': atomicState.oAuthInitState\n ];\n return \"${OAUTH_AUTHORIZATION_URL()}?${Utils.toQueryString(params)}\";\n}\n\ndef getOAuthRedirectUrl() {\n return \"${getFullApiServerUrl()}\/oauth\/callback?access_token=${atomicState.accessToken}\";\n}\n\ndef oAuthCallback() {\n Utils.toLogger(\"debug\", \"Received oAuth callback\");\n\n def code = params.code;\n def oAuthState = params.state;\n if (oAuthState != atomicState.oAuthInitState) {\n Utils.toLogger(\"error\", \"Init state did not match our state on the callback. Ignoring the request\")\n return renderOAuthFailure();\n }\n \n \/\/ Prevent any replay attacks and re-initialize the state\n atomicState.oAuthInitState = null;\n atomicState.oAuthRefreshToken = null;\n atomicState.oAuthAuthToken = null;\n atomicState.oAuthTokenExpires = null;\n\n acquireOAuthToken(code);\n\n if (!atomicState.oAuthAuthToken) {\n return renderOAuthFailure();\n }\n renderOAuthSuccess();\n}\n\ndef acquireOAuthToken(String code) {\n Utils.toLogger(\"debug\", \"Acquiring OAuth Authentication Token\");\n apiRequestAccessToken([\n 'grant_type': 'authorization_code',\n 'code': code,\n 'client_id': getClientId(),\n 'client_secret': getClientSecret(),\n 'redirect_uri': getOAuthRedirectUrl(),\n ]);\n}\n\ndef refreshOAuthToken() {\n Utils.toLogger(\"debug\", \"Refreshing OAuth Authentication Token\");\n apiRequestAccessToken([\n 'grant_type': 'refresh_token',\n 'refresh_token': atomicState.oAuthRefreshToken,\n 'client_secret': getClientSecret(),\n ]);\n}\n\ndef apiRequestAccessToken(body) {\n try {\n httpPost(uri: OAUTH_TOKEN_URL(), requestContentType: 'application\/x-www-form-urlencoded', body: body) { response ->\n if (response && response.data && response.success) {\n atomicState.oAuthRefreshToken = response.data.refresh_token\n atomicState.oAuthAuthToken = response.data.access_token\n atomicState.oAuthTokenExpires = now() + (response.data.expires_in * 1000)\n } else {\n log.error \"Failed to acquire OAuth Authentication token. Response was not successful.\"\n }\n }\n } catch (e) {\n log.error \"Failed to acquire OAuth Authentication token due to Exception: ${e}\"\n }\n}\n\ndef getOAuthAuthToken() {\n \/\/ Expire the token 1 minute before to avoid race conditions\n if(now() >= atomicState.oAuthTokenExpires - 60_000) {\n refreshOAuthToken();\n }\n \n return atomicState.oAuthAuthToken;\n}\n\ndef getLanguage() {\n return atomicState.langCode;\n}\n\ndef renderOAuthSuccess() {\n render contentType: 'text\/html', data: '''\n

    Your Home Connect Account is now connected to Hubitat<\/p>\n

    Close this window to continue setup.<\/p>\n '''\n}\n\ndef renderOAuthFailure() {\n render contentType: 'text\/html', data: '''\n

    Unable to connect to Home Connect. You can see the logs for more information<\/p>\n

    Close this window to try again.<\/p>\n '''\n}\n\n\/**\n * The Home Connect API\n *\n * The complete documentation can be found here: https:\/\/apiclient.home-connect.com\/#\/\n *\/\ndef HomeConnectAPI_create(Map params = [:]) {\n def defaultParams = [\n apiUrl: 'https:\/\/api.home-connect.com',\n language: 'en-US',\n oAuthTokenFactory: null\n ]\n\n def resolvedParams = defaultParams << params;\n def apiUrl = resolvedParams['apiUrl']\n def oAuthTokenFactory = resolvedParams['oAuthTokenFactory']\n def language = resolvedParams['language']\n\n def instance = [:];\n def json = new JsonSlurper();\n\n def authHeaders = {\n return ['Authorization': \"Bearer ${oAuthTokenFactory()}\", 'Accept-Language': \"${language()}\", 'accept': \"application\/vnd.bsh.sdk.v1+json\"]\n }\n\n def apiGet = { path, closure ->\n Utils.toLogger(\"debug\", \"API Get Request to Home Connect with path $path\")\n return httpGet(uri: apiUrl,\n 'path': path,\n 'headers': authHeaders()) { response -> \n closure.call(json.parseText(response.data.text));\n }\n };\n\n def apiPut = { path, data, closure ->\n Utils.toLogger(\"debug\", \"API Put Request to Home Connect with path ${path}\")\n Utils.toLogger(\"debug\", \"API Put original - ${data}\")\n String body = new groovy.json.JsonBuilder(data).toString()\n Utils.toLogger(\"debug\", \"API Put Converted - ${body}\")\n \n try {\n return httpPut(uri: apiUrl,\n path: path,\n contentType: \"application\/json\",\n requestContentType: 'application\/json',\n body: body,\n headers: authHeaders()) { response -> \n Utils.toLogger(\"debug\", \"API Put response.data - ${response.data}\")\n if(response.data && response.data.text)\n {\n closure.call(json.parseText(response.data.text));\n }\n }\n } catch (Exception e) {\n Utils.toLogger(\"error\", \"Error apiPut - ${e}\")\n }\n };\n\n def apiDelete = { path, closure ->\n Utils.toLogger(\"debug\", \"API Delete Request to Home Connect with path ${path}\")\n \n try {\n return httpDelete(uri: apiUrl,\n 'path': path,\n 'headers': authHeaders()) { response -> \n if (response.status == 200) {\n Utils.toLogger(\"debug\", \"API Delete response - ${response.data}\")\n if(response.data && response.data.text)\n {\n closure.call(json.parseText(response.data.text));\n }\n }\n }\n } catch (Exception e) {\n Utils.toLogger(\"error\", \"Error apiDelete - ${e}\")\n }\n };\n\n \/**\n * Get all home appliances which are paired with the logged-in user account.\n *\n * This endpoint returns a list of all home appliances which are paired\n * with the logged-in user account. All paired home appliances are returned\n * independent of their current connection atomicState. The connection state can\n * be retrieved within the field 'connected' of the respective home appliance.\n * The haId is the primary access key for further API access to a specific\n * home appliance.\n *\n * Example return value:\n * [\n * {\n * \"name\": \"My Bosch Oven\",\n * \"brand\": \"BOSCH\",\n * \"vib\": \"HNG6764B6\",\n * \"connected\": true,\n * \"type\": \"Oven\",\n * \"enumber\": \"HNG6764B6\/09\",\n * \"haId\": \"BOSCH-HNG6764B6-0000000011FF\"\n * }\n * ]\n *\/\n instance.getHomeAppliances = { closure ->\n Utils.toLogger(\"info\", \"Retrieving Home Appliances from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\") { response ->\n closure.call(response.data.homeappliances)\n }\n };\n\n \/**\n * Get a specfic home appliances which are paired with the logged-in user account.\n *\n * This endpoint returns a specific home appliance which is paired with the\n * logged-in user account. It is returned independent of their current\n * connection atomicState. The connection state can be retrieved within the field\n * 'connected' of the respective home appliance.\n * The haId is the primary access key for further API access to a specific\n * home appliance.\n *\n * Example return value:\n *\n * {\n * \"name\": \"My Bosch Oven\",\n * \"brand\": \"BOSCH\",\n * \"vib\": \"HNG6764B6\",\n * \"connected\": true,\n * \"type\": \"Oven\",\n * \"enumber\": \"HNG6764B6\/09\",\n * \"haId\": \"BOSCH-HNG6764B6-0000000011FF\"\n * }\n *\/\n instance.getHomeAppliance = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\") { response ->\n closure.call(response.data)\n }\n };\n\n \/**\n * Get all programs of a given home appliance.\n *\n * Example return value:\n *\n * [\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.HotAir\",\n * \"constraints\": {\n * \"available\": true,\n * \"execution\": \"selectandstart\"\n * }\n * },\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.TopBottomHeating\",\n * \"constraints\": {\n * \"available\": true,\n * \"execution\": \"selectandstart\"\n * }\n * },\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.PizzaSetting\",\n * \"constraints\": {\n * \"available\": true,\n * \"execution\": \"selectonly\"\n * }\n * }\n * ]\n *\/\n instance.getPrograms = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving All Programs of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\") { response ->\n closure.call(response.data.programs)\n }\n };\n\n \/**\n * Get all programs which are currently available on the given home appliance.\n *\n * Example return value:\n *\n * [\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.HotAir\",\n * \"constraints\": {\n * \"available\": true,\n * \"execution\": \"selectandstart\"\n * }\n * },\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.TopBottomHeating\",\n * \"constraints\": {\n * \"available\": true,\n * \"execution\": \"selectandstart\"\n * }\n * },\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.PizzaSetting\",\n * \"constraints\": {\n * \"available\": true,\n * \"execution\": \"selectonly\"\n * }\n * }\n * ]\n *\/\n instance.getAvailablePrograms = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving All Programs of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/available\") { response ->\n closure.call(response.data.programs)\n }\n };\n\n \/**\n * Get specific available program.\n *\n * Example return value:\n *\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.HotAir\",\n * \"options\": [\n * {\n * \"key\": \"Cooking.Oven.Option.SetpointTemperature\",\n * \"type\": \"Int\",\n * \"unit\": \"\u00b0C\",\n * \"constraints\": {\n * \"min\": 30,\n * \"max\": 250\n * }\n * },\n * {\n * \"key\": \"BSH.Common.Option.Duration\",\n * \"type\": \"Int\",\n * \"unit\": \"seconds\",\n * \"constraints\": {\n * \"min\": 1,\n * \"max\": 86340\n * }\n * }\n * ]\n * }\n *\/\n instance.getAvailableProgram = { haId, programKey, closure ->\n Utils.toLogger(\"info\", \"Retrieving the '${programKey}' Program of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/available\/${programKey}\") { response ->\n closure.call(response.data)\n }\n };\n\n \/**\n * Get program which is currently executed.\n *\n * Example return value:\n *\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.HotAir\",\n * \"options\": [\n * {\n * \"key\": \"Cooking.Oven.Option.SetpointTemperature\",\n * \"value\": 230,\n * \"unit\": \"\u00b0C\"\n * },\n * {\n * \"key\": \"BSH.Common.Option.Duration\",\n * \"value\": 1200,\n * \"unit\": \"seconds\"\n * }\n * ]\n * }\n *\/\n instance.getActiveProgram = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving the active Program of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/active\") { response ->\n closure.call(response.data)\n }\n };\n \n instance.setActiveProgram = { haId, programKey, options = \"\", closure ->\n def data = [key: \"${programKey}\"]\n if (options != \"\") {\n data.put(\"options\", options)\n } \n Utils.toLogger(\"info\", \"Set the active program '${programKey}' of Home Appliance '$haId' from Home Connect\")\n apiPut(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/active\", [data: data]) { response ->\n closure.call(response.data)\n }\n }; \n\n instance.setStopProgram = { haId, closure ->\n Utils.toLogger(\"info\", \"Stop the active program of Home Appliance '$haId' from Home Connect\")\n apiDelete(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/active\") { response ->\n closure.call(response.data)\n }\n }; \n \/*def start_program(self, program_key, options=None):\n \"\"\"Start a program.\"\"\"\n if options is not None:\n return self.put(\n \"\/programs\/active\", {\"data\": {\"key\": program_key, \"options\": options}}\n )\n return self.put(\"\/programs\/active\", {\"data\": {\"key\": program_key}})*\/\n\n \/**\n * Get all options of the active program like temperature or duration.\n *\n * Example return value:\n *\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.HotAir\",\n * \"options\": [\n * {\n * \"key\": \"Cooking.Oven.Option.SetpointTemperature\",\n * \"value\": 230,\n * \"unit\": \"\u00b0C\"\n * },\n * {\n * \"key\": \"BSH.Common.Option.Duration\",\n * \"value\": 1200,\n * \"unit\": \"seconds\"\n * }\n * ]\n * }\n *\/\n instance.getActiveProgramOptions = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving the active Program Options of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/active\/options\") { response ->\n \/\/Utils.toLogger(\"info\", \"getActiveProgramOptions of Home Appliance '$haId' from Home Connect ${response.data}\")\n closure.call(response.data.options)\n }\n };\n\n \/**\n * Get one specific option of the active program, e.g. the duration.\n *\n * Example return value:\n *\n * {\n * \"key\": \"Cooking.Oven.Option.SetpointTemperature\",\n * \"value\": 180,\n * \"unit\": \"\u00b0C\"\n * }\n *\/\n instance.getActiveProgramOption = { haId, optionKey, closure ->\n Utils.toLogger(\"info\", \"Retrieving the active Program Option '${optionKey}' of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/active\/options\/${optionKey}\") { response ->\n closure.call(response.data.options)\n }\n };\n \n instance.setActiveProgramOption = { haId, optionKey, value, unit = \"\", closure ->\n def data = [key: \"${optionKey}\", value: \"${value}\"]\n if (unit != \"\") {\n data.put(\"unit\", unit)\n }\n Utils.toLogger(\"info\", \"Retrieving the active Program Option '${optionKey}' of Home Appliance '$haId' from Home Connect\")\n apiPut(\"${ENDPOINT_APPLIANCES()}\/${haId}\/settings\/${settingsKey}\", [data: data]) { response ->\n closure.call(response.data)\n }\n \n \/*apiPut(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/active\/options\/${optionKey}\", \n \"{\\\"data\\\": {\\\"key\\\": ${optionKey}, \\\"value\\\": ${value}, ${unit}}}\") { response ->\n closure.call(response.data.options)\n }*\/\n \/*apiPut(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/active\/options\/${optionKey}\", \n [data: [key:optionKey ]]\n \"{\\\"data\\\": {\\\"key\\\": ${optionKey}, \\\"value\\\": ${value}, ${unit}}}\") { response ->\n closure.call(response.data.options)\n }*\/\n\n };\n\n \/**\n * Get the program which is currently selected.\n *\n * In most cases the selected program is the program which is currently shown on the display of the home appliance.\n * This program can then be manually adjusted or started on the home appliance itself. \n * \n * Example return value:\n *\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.HotAir\",\n * \"options\": [\n * {\n * \"key\": \"Cooking.Oven.Option.SetpointTemperature\",\n * \"value\": 230,\n * \"unit\": \"\u00b0C\"\n * },\n * {\n * \"key\": \"BSH.Common.Option.Duration\",\n * \"value\": 1200,\n * \"unit\": \"seconds\"\n * }\n * ]\n * }\n *\/\n instance.getSelectedProgram = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving the selected Program of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/selected\") { response ->\n closure.call(response.data)\n }\n };\n\n instance.setSelectedProgram = { haId, programKey, options = \"\", closure ->\n def data = [key: \"${programKey}\"]\n if (options != \"\") {\n data.put(\"options\", options)\n } \n Utils.toLogger(\"info\", \"Set the selected program '${programKey}' of Home Appliance '$haId' from Home Connect\")\n apiPut(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/selected\", [data: data]) { response ->\n closure.call(response.data)\n }\n }; \n\n \/**\n * Get all options of selected program.\n *\n * Example return value:\n *\n * {\n * \"key\": \"Cooking.Oven.Program.HeatingMode.HotAir\",\n * \"options\": [\n * {\n * \"key\": \"Cooking.Oven.Option.SetpointTemperature\",\n * \"value\": 230,\n * \"unit\": \"\u00b0C\"\n * },\n * {\n * \"key\": \"BSH.Common.Option.Duration\",\n * \"value\": 1200,\n * \"unit\": \"seconds\"\n * }\n * ]\n * }\n *\/\n instance.getSelectedProgramOptions = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving the selected Program Options of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/selected\/options\") { response ->\n closure.call(response.data.options)\n }\n };\n\n \/**\n * Get specific option of selected program\n *\n * Example return value:\n *\n * {\n * \"key\": \"Cooking.Oven.Option.SetpointTemperature\",\n * \"value\": 180,\n * \"unit\": \"\u00b0C\"\n * }\n *\/\n instance.getSelectedProgramOption = { haId, optionKey, closure ->\n Utils.toLogger(\"info\", \"Retrieving the selected Program Option ${optionKey} of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/selected\/options\/${optionKey}\") { response ->\n closure.call(response.data.options)\n }\n };\n\n instance.setSelectedProgramOption = { haId, optionKey, optionValue, closure ->\n def data = [key: \"${optionKey}\", value: optionValue]\n Utils.toLogger(\"info\", \"Retrieving the selected Program Option ${optionKey} of Home Appliance '$haId' from Home Connect\")\n apiPut(\"${ENDPOINT_APPLIANCES()}\/${haId}\/programs\/selected\/options\/${optionKey}\", [data: data]) { response ->\n closure.call(response.data)\n }\n }; \n\n \/**\n * Get current status of home appliance\n *\n * A detailed description of the available status can be found here:\n *\n * https:\/\/developer.home-connect.com\/docs\/api\/status\/remotecontrolactivationstate - Remote control activation state\n * https:\/\/developer.home-connect.com\/docs\/api\/status\/remotestartallowancestate - Remote start allowance state\n * https:\/\/developer.home-connect.com\/docs\/api\/status\/localcontrolstate - Local control state\n * https:\/\/developer.home-connect.com\/docs\/status\/operation_state - Operation state\n * https:\/\/developer.home-connect.com\/docs\/status\/door_state - Door state\n *\n * Several more device-specific states can be found at https:\/\/developer.home-connect.com\/docs\/api\/status\/remotecontrolactivationatomicState.\n *\n * Example return value:\n *\n * [\n * {\n * \"key\": \"BSH.Common.Status.OperationState\",\n * \"value\": \"BSH.Common.EnumType.OperationState.Ready\"\n * },\n * {\n * \"key\": \"BSH.Common.Status.LocalControlActive\",\n * \"value\": true\n * }\n * ]\n *\/\n instance.getStatus = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving the status of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/status\") { response ->\n closure.call(response.data.status)\n }\n };\n\n \/**\n * Get current status of home appliance\n *\n * A detailed description of the available status can be found here:\n *\n * https:\/\/developer.home-connect.com\/docs\/api\/status\/remotecontrolactivationstate - Remote control activation state\n * https:\/\/developer.home-connect.com\/docs\/api\/status\/remotestartallowancestate - Remote start allowance state\n * https:\/\/developer.home-connect.com\/docs\/api\/status\/localcontrolstate - Local control state\n * https:\/\/developer.home-connect.com\/docs\/status\/operation_state - Operation state\n * https:\/\/developer.home-connect.com\/docs\/status\/door_state - Door state\n *\n * Several more device-specific states can be found at https:\/\/developer.home-connect.com\/docs\/api\/status\/remotecontrolactivationatomicState.\n *\n * Example return value:\n *\n * {\n * \"key\": \"BSH.Common.Status.OperationState\",\n * \"value\": \"BSH.Common.EnumType.OperationState.Ready\"\n * }\n *\/\n instance.getSingleStatus = { haId, statusKey, closure ->\n Utils.toLogger(\"info\", \"Retrieving the status '${statusKey}' of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/status\/${statusKey}\") { response ->\n closure.call(response.data)\n }\n };\n\n \/**\n * Get a list of available settings\n *\n * Get a list of available setting of the home appliance.\n * Further documentation can be found here:\n *\n * https:\/\/developer.home-connect.com\/docs\/settings\/power_state - Power state\n * https:\/\/developer.home-connect.com\/docs\/api\/settings\/fridgetemperature - Fridge temperature\n * https:\/\/developer.home-connect.com\/docs\/api\/settings\/fridgesupermode - Fridge super mode\n * https:\/\/developer.home-connect.com\/docs\/api\/settings\/freezertemperature - Freezer temperature\n * https:\/\/developer.home-connect.com\/docs\/api\/settings\/freezersupermode - Freezer super mode\n *\n * Example return value:\n *\n * [\n * {\n * \"key\": \"BSH.Common.Setting.PowerState\",\n * \"value\": \"BSH.Common.EnumType.PowerState.On\"\n * },\n * {\n * \"key\": \"Refrigeration.FridgeFreezer.Setting.SuperModeFreezer\",\n * \"value\": true\n * }\n * ]\n *\/\n instance.getSettings = { haId, closure ->\n Utils.toLogger(\"info\", \"Retrieving the settings of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/settings\") { response ->\n closure.call(response.data.settings)\n }\n };\n\n \/**\n * Get a specific setting\n *\n *\n * Example return value:\n *\n * {\n * \"key\": \"BSH.Common.Setting.PowerState\",\n * \"value\": \"BSH.Common.EnumType.PowerState.On\",\n * \"type\": \"BSH.Common.EnumType.PowerState\",\n * \"constraints\": {\n * \"allowedvalues\": [\n * \"BSH.Common.EnumType.PowerState.On\",\n * \"BSH.Common.EnumType.PowerState.Standby\"\n * ],\n * \"access\": \"readWrite\"\n * }\n * }\n *\/\n instance.getSetting = { haId, settingsKey, closure ->\n Utils.toLogger(\"info\", \"Retrieving the setting '${settingsKey}' of Home Appliance '$haId' from Home Connect\")\n apiGet(\"${ENDPOINT_APPLIANCES()}\/${haId}\/settings\/${settingsKey}\") { response ->\n closure.call(response.data)\n }\n };\n\n instance.setSettings = { haId, settingsKey, value, closure ->\n Utils.toLogger(\"info\", \"Set the setting '${settingsKey}' of Home Appliance '$haId' from Home Connect\")\n \/\/Utils.toLogger(\"info\", \"Test: ${new groovy.json.JsonBuilder([data: [key: \"${settingsKey}\", value: \"${value}\"]]).toString()}\")\n \n \/\/def updatedState = [:]\n \/\/updatedState.put(\"key\", settingsKey);\n \/\/updatedState.put(\"value\", value);\n \/\/\"{\\\"data\\\": {\\\"key\\\": ${settingsKey}, \\\"value\\\": ${value}}}\"\n \/\/String wrapper = \"{\\\"data\\\":\" + desiredState + \"}\";\n \/\/{\"data\":{\"key\":\"BSH.Common.Setting.PowerState\",\"value\":\"BSH.Common.EnumType.PowerState.On\"}}\n apiPut(\"${ENDPOINT_APPLIANCES()}\/${haId}\/settings\/${settingsKey}\", [data: [key: \"${settingsKey}\", value: \"${value}\"]]) { response ->\n closure.call(response.data)\n }\n };\n \n \/*instance.setSettings = { haId, settingsKey, value, closure ->\n Utils.toLogger(\"info\", \"Set the setting '${settingsKey}' of Home Appliance '$haId' from Home Connect\")\n apiPut(\"${ENDPOINT_APPLIANCES()}\/${haId}\/settings\/${settingsKey}\", \"{\\\"data\\\": {\\\"key\\\": ${settingsKey}, \\\"value\\\": ${value}}}\") { response ->\n closure.call(response.data)\n }\n };*\/ \n\n\n \/**\n * Get stream of events for one appliance\n *\n * NOTE: This can only be done from within a device driver. It will not work within an app\n *\/\n instance.connectDeviceEvents = { haId, interfaces -> \n Utils.toLogger(\"info\", \"Connecting to the event stream of Home Appliance '$haId' from Home Connect\")\n \/\/Utils.toLogger(\"info\", \"authHeaders '${authHeaders()}' \")\n interfaces.eventStream.connect(\n \"${apiUrl}${ENDPOINT_APPLIANCES()}\/${haId}\/events\",\n [rawData: true,\n ignoreSSLIssues: true,\n headers: ([ 'Accept': 'text\/event-stream' ] << authHeaders())])\n };\n\n \/**\n * stop stream of events for one appliance\n *\n * NOTE: This can only be done from within a device driver. It will not work within an app\n *\/\n instance.disconnectDeviceEvents = { haId, interfaces -> \n Utils.toLogger(\"info\", \"Disconnecting to the event stream of Home Appliance '$haId' from Home Connect\")\n interfaces.eventStream.close()\n };\n \n \/**\n * Get stream of events for all appliances \n *\n * NOTE: This can only be done from within a device driver. It will not work within an app\n *\/\n instance.connectEvents = { interfaces -> \n Utils.toLogger(\"info\", \"Connecting to the event stream of all Home Appliances from Home Connect\")\n interfaces.eventStream.connect(\n \"${apiUrl}\/api\/homeappliances\/events\",\n [rawData: true,\n ignoreSSLIssues: true,\n headers: ([ 'Accept': 'text\/event-stream' ] << authHeaders())])\n };\n\n instance.getSupportedLanguages = {\n Utils.toLogger(\"info\", \"Getting the list of supported languages\")\n \/\/ Documentation: https:\/\/api-docs.home-connect.com\/general?#supported-languages\n return [\"Bulgarian\": [\"Bulgaria\": \"bg-BG\"], \n \"Chinese (Simplified)\": [\"China\": \"zh-CN\", \"Hong Kong\": \"zh-HK\", \"Taiwan, Province of China\": \"zh-TW\"], \n \"Czech\": [\"Czech Republic\": \"cs-CZ\"], \n \"Danish\": [\"Denmark\": \"da-DK\"],\n \"Dutch\": [\"Belgium\": \"nl-BE\", \"Netherlands\": \"nl-NL\"],\n \"English\": [\"Australia\": \"en-AU\", \"Canada\": \"en-CA\", \"India\": \"en-IN\", \"New Zealand\": \"en-NZ\", \"Singapore\": \"en-SG\", \"South Africa\": \"en-ZA\", \"United Kingdom\": \"en-GB\", \"United States\": \"en-US\"],\n \"Finnish\": [\"Finland\": \"fi-FI\"],\n \"French\": [\"Belgium\": \"fr-BE\", \"Canada\": \"fr-CA\", \"France\": \"fr-FR\", \"Luxembourg\": \"fr-LU\", \"Switzerland\": \"fr-CH\"],\n \"German\": [\"Austria\": \"de-AT\", \"Germany\": \"de-DE\", \"Luxembourg\": \"de-LU\", \"Switzerland\": \"de-CH\"],\n \"Greek\": [\"Greece\": \"el-GR\"],\n \"Hungarian\": [\"Hungary\": \"hu-HU\"],\n \"Italian\": [\"Italy\": \"it-IT\", \"Switzerland\": \"it-CH\"],\n \"Norwegian\": [\"Norway\": \"nb-NO\"],\n \"Polish\": [\"Poland\": \"pl-PL\"],\n \"Portuguese\": [\"Portugal\": \"pt-PT\"],\n \"Romanian\": [\"Romania\": \"ro-RO\"],\n \"Russian\": [\"Russian Federation\": \"ru-RU\"],\n \"Serbian\": [\"Suriname\": \"sr-SR\"],\n \"Slovak\": [\"Slovakia\": \"sk-SK\"],\n \"Slovenian\": [\"Slovenia\": \"sl-SI\"],\n \"Spanish\": [\"Chile\": \"es-CL\", \"Peru\": \"es-PE\", \"Spain\": \"es-ES\"],\n \"Swedish\": [\"Sweden\": \"sv-SE\"],\n \"Turkish\": [\"Turkey\": \"tr-TR\"],\n \"Ukrainian\": [\"Ukraine\": \"uk-UA\"]\n ]\n };\n \n return instance;\n}\n\n\/**\n * Simple utilities for manipulation\n *\/\n\ndef Utils_create() {\n def instance = [:];\n \n instance.toQueryString = { Map m ->\n \treturn m.collect { k, v -> \"${k}=${new URI(null, null, v.toString(), null)}\" }.sort().join(\"&\")\n }\n\n instance.toFlattenMap = { Map m ->\n \treturn m.collectEntries { k, v -> \n def flattened = [:]\n if (v instanceof Map) {\n instance.toFlattenMap(v).collectEntries { k1, v1 -> \n flattened << [ \"${v1}\": \"${k} - ${k1} (${v1})\"];\n } \n } else {\n flattened << [ \"${k}\": v ];\n }\n return flattened;\n } \n }\n\n instance.toLogger = { level, msg ->\n if (level && msg) {\n Integer levelIdx = LOG_LEVELS.indexOf(level);\n Integer setLevelIdx = LOG_LEVELS.indexOf(logLevel);\n if (setLevelIdx < 0) {\n setLevelIdx = LOG_LEVELS.indexOf(DEFAULT_LOG_LEVEL);\n }\n if (levelIdx <= setLevelIdx) {\n log.\"${level}\" \"${app.name} ${msg}\";\n }\n }\n }\n \n \/\/ Converts seconds to time hh:mm:ss\n instance.convertSecondsToTime = { sec ->\n long millis = sec * 1000\n long hours = java.util.concurrent.TimeUnit.MILLISECONDS.toHours(millis)\n long minutes = java.util.concurrent.TimeUnit.MILLISECONDS.toMinutes(millis) % java.util.concurrent.TimeUnit.HOURS.toMinutes(1)\n String timeString = String.format(\"%02dh:%02dm\", Math.abs(hours), Math.abs(minutes))\n return timeString\n }\n \n instance.extractInts = { String input ->\n return input.findAll( \/\\d+\/ )*.toInteger()\n }\n \n instance.convertErrorMessageTime = { String input ->\n Integer valueInteger = instance.extractInts(input).last()\n String valueStringConverted = instance.convertSecondsToTime(valueInteger)\n return input.replaceAll( valueInteger.toString() + \" seconds\", valueStringConverted )\n } \n \n instance.showHideNextButton = { show ->\n\t if(show) paragraph \"