Source

sandbox / webnotepad / src / main / webapp / WEB-INF / groovy / notepad.groovy

Full commit
// A Groovylet that process Web NotePad form.
// By Zemian Deng 08/05/2012 <saltnlight5@gmail.com>

// Util methods
def log(msg) {
	System.out.println(msg) 
}
def newFilename() {
	return "${new java.text.SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date())}.markdown"
}

// Init and check notes directory
notesDir = new File(System.properties['notesDir'] ?: "${System.properties['user.home']}/notes")
if (!notesDir.exists()) {
	notesDir.mkdirs()
	log("Created $notesDir directory.")
}

// Process notes form
noteFilename = params['noteFilename'] ?: newFilename()
notes = ''
msg = ''
searchText = ''
noteFiles = notesDir.listFiles().sort()
searchResults = [:]
if (request.method == 'GET' && params['e'] != null) {
	noteFilename = params['e']
	file = new File(notesDir, noteFilename)
	notes = file.text
} else if (request.method == 'POST') {
	action = params['action']
	if (action == 'Save') {
		notes = params['notes']
		if (notes.trim() != '') {
			file = new File(notesDir, noteFilename)
			log("Saving new note: $file")
			file.write(notes)
			noteFiles = notesDir.listFiles().sort()
		} else {
			msg = 'Notes is empty. Nothing is saved.'
		}
	} else if (action == 'New') {
		noteFilename = newFilename()
		notes = ''
	} else if (action == 'Search') {
		searchText = params['searchText']
		if (searchText != '') {
			noteFiles.each{ file ->
				file.eachLine{ line ->
					if (line.find(searchText)) {
						lines = searchResults[file.name]
						if (lines == null) {
							lines = []
							searchResults[file.name] = lines
						}
						lines.add(line)
					}
				}
			}
		}
	}
}
htmlNotes = new com.petebevin.markdown.MarkdownProcessor().markdown(notes)

// Save attributes for view
request['msg'] = msg
request['noteFilename'] = noteFilename
request['notes'] = notes
request['htmlNotes'] = htmlNotes
request['noteFiles'] = noteFiles
request['searchText'] = searchText
request['searchResults'] = searchResults

// Done
forward("notepad.html")