caseclassDocumentStore(base: String) { privateval fileNameIndex = collection.concurrent.TrieMap[Long, Document]() privateval idCounter = newAtomicLong(0) // add a new document defadd(name: String, in: InputStream, contentType: Option[String], description: String): Long = { copyStream(in, newFileOutputStream(getFile(id))) val id = idCounter.getAndIncrement fileNameIndex(id) = Document(id, name, contentType, description) id } // return a sequence of all documents deflist: Seq[Document] = fileNameIndex.values.toSeq // return a document for a given ID deffindById(id: Long): Option[Document] = fileNameIndex.get(id) // return a file for a given ID defasFile(id: Long): File = newFile(f"$base/$id") // write a input stream to an output stream privatedefcopyStream(input: InputStream, output: OutputStream) { val buffer = Array.ofDim[Byte](1024) var bytesRead: Int = 0 while (bytesRead != -1){ bytesRead = input.read(buffer) if (bytesRead > 0) output.write(buffer, 0, bytesRead) } } }
classScalatraBootstrapextendsLifeCycle{ overridedefinit(context: ServletContext) { val store = DocumentStore("data") store.add("strategy.jpg", newFileInputStream(newFile("data/strategy")), Some("image/jpeg"), "bulletproof business strategy") store.add("manual.pdf", newFileInputStream(newFile("data/manual.pdf")), Some("application/pdf"), "the manual about foos") val app = newDocumentsApp(store) context.mount(app, "/*") } }