spring-boot-logogradle-logo
console

Create Gradle Spring Boot project with SPRING INITIALIZR

I chose Groovy language for the project, but if you want Java, text below with little changes also helps you.

Edit build.gradle and add to it bootRun section

buildscript {
	ext {
		springBootVersion = '1.3.1.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
	baseName = 'myapp'
	version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenCentral()
}


dependencies {
	compile('org.codehaus.groovy:groovy')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}

task wrapper(type: Wrapper) {
	gradleVersion = '2.9'
}

// this code split parameters and allow us use parameters in our application
bootRun {
	if ( project.hasProperty('args') ) {
		args project.args.split('\\s+')
	}
}

create MyController class

@Controller
class MyController implements CommandLineRunner {

	private Logger logger = LoggerFactory.getLogger(this.getClass())

	@Override
	void run(String... args) throws Exception {
		if(!args) {
			logger.warn("You must pass at least one parametr.")
			logger.warn("Example: bootRun -Pargs=\"arg1 arg2 arg3\"") 
		}
		// print parameters which we sent from command line
		args.each{ arg -> 
			logger.info(arg)
		} 
	} 
}

Run application
gradle bootRun -Pargs=”arg1 arg2 arg3″

First off all you could find out some plugins https://grails.org/plugins/search?q=mongo

But if you need you could use another method:

1. Edit BuildConfig.groovy
add string like this: compile ‘org.mongodb:mongo-java-driver:3.0.3’ to dependencies section

dependencies {
        //...
	compile 'org.mongodb:mongo-java-driver:3.0.3'
    }

2. Edit Config.groovy

mongodb.uri = "mongodb://username:password@your.mongodb.server/yourDataBaseName"
mongodb.database = "yourDataBaseName"

3. Add to resources.groovy

beans = {
	mongoClientURI(MongoClientURI) { bean ->
		bean.constructorArgs = [grailsApplication.config.mongodb.uri.toString()]
	}
	mongoClient(MongoClient) { bean ->
		bean.constructorArgs = [ref(mongoClientURI)]
		bean.destroyMethod = 'close'
	}
	mongoDb(mongoClient: 'getDB') { bean ->
		bean.constructorArgs = [grailsApplication.config.mongodb.database.toString()]
	}
}

4. Add to any controller (in my case MyController)

package mypackage

import com.mongodb.DB

class MyController {

	DB mongoDb

	def users() {

		def collection = mongoDb.getCollection('myCollection')

		collection.insert(new BasicDBObject(['name':'Piter']))
		
		def users = collection.find(new BasicDBObject(['name':'Piter'])).toArray()
		
		render (contentType: 'application/json', text: JSON.serialize(users))
	}

	def user() {

		def userId = params.userId
		
		def collection = mongoDb.getCollection('myCollection')
		
		def user = collection.findOne(new BasicDBObject(['_id': new ObjectId(userId)]))
		
		render (contentType: 'application/json', text: JSON.serialize(user))
	}

}

I have some view (“basicView.gsp”) and want to pass other view content (“_someTemplate.gsp”) to this view to javascript variable (“template”).

basicView.gsp:

<html>
<head>
...
</head>
<body>
...
<script>
var template = '${raw(include(view:"myTemplates/_someTemplate.gsp").replaceAll('\n',''))}';
</script>
</body>
</html>

_someTemplate.gsp:

<div>
<h1>Some header</h1>
<p>Lorem ipsum dolor sit...</p>
</div>

Resulted html:

<html>
<head>
...
</head>
<body>
...
<script>
var template = '<div><h1>Some header</h1><p>Lorem ipsum dolor sit...</p></div>';
</script>
</body>
</html>

Details:

  • java 1.7.0_25
  • grails 2.4.5
  • vaadin plugin 7.5.2

Create Grails app in ItelliJ IDEA 14 as in this manual –
https://vaadin.com/wiki/-/wiki/Main/Vaadin+on+Grails+-+Create+project+in+IntelliJ+IDEA
But use only 1. and 2. points.

After 2. point use next suggestions:

add to BuildConfig.groovy:
to dependencies – runtime ‘org.hibernate:hibernate-validator:5.1.1.Final’
to plugings – compile “:vaadin:7.5.2”
click Apply Grails changes to IDEA project structure

run – grails vaadin-quickstart

Next couple steps:

Screenshot 2015-08-26 23.25.28

Screenshot 2015-08-26 23.29.08

press “+” and select Grails:

Screenshot 2015-08-26 23.30.51

Screenshot 2015-08-26 23.30.51(2)

Screenshot 2015-08-26 23.30.52

select “your app” in Module:

Screenshot 2015-08-26 23.30.52(2)

change name on “your app name”:

Screenshot 2015-08-26 23.30.52(3)

result:

Screenshot 2015-08-26 23.30.52(4)

Thats all.

def someMap = [
           'phones':['iPhone','Galaxy','Nexus'],
           'laptops':['HP','MacBook','Samsung'],
           'tablets':['Galaxy Tab','iPad','Asus'],
           ]

someMap.eachWithIndex{ k, v, index -> println "${k}:${v} - ${index}" }


Result:
phones:[iPhone, Galaxy, Nexus] – 0
laptops:[HP, MacBook, Samsung] – 1
tablets:[Galaxy Tab, iPad, Asus] – 2

def map = [a:"cc", b: "dd"]
println "map - " + map
println "map.keySet() - " + map.keySet()
println "map.values() - " + map.values()
println "map.entrySet() - " + map.entrySet()
println "map.entrySet().key - " + map.entrySet().key
println "map.entrySet().value - " + map.entrySet().value


Result:
map – [a:cc, b:dd]
map.keySet() – [a, b]
map.values() – [cc, dd]
map.entrySet() – [a=cc, b=dd]
map.entrySet().key – [a, b]
map.entrySet().value – [cc, dd]