Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package jugorders
import scala.io.Source
import java.io.{FileOutputStream, OutputStreamWriter, BufferedWriter, File}
import scala.xml.XML
/**
* @author Matt Hicks <matt@outr.com>
*/
object JUGOrders {
var orders = List.empty[Order]
var order: Order = _
var orderLine: OrderLine = _
def main(args: Array[String]): Unit = {
val source = Source.fromFile(new File("orders.txt"))
try {
source.getLines().foreach(processLine)
} finally {
source.close()
}
if (order != null) {
orders = order :: orders
}
orders = orders.reverse
val output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("order-lines.csv"))))
try {
orders.foreach {
case order => {
order.lines.foreach {
case line => {
output.write(s"${line.orderNumber}, ${line.description}, ${line.lineNumber}, ${line.product}, ${line.quantity}\r\n")
}
}
}
}
} finally {
output.flush()
output.close()
}
}
val OrderRegex = """[(]order [(]orderNumber (\d*)[)]""".r
val QuantityRegex = """.*[(]quantity (\d*)[)]""".r
val ProductRegex = """.*[(]product "(.*)"[)]""".r
val DescriptionRegex = """.*[(]description "(.*)"[)]""".r
val LineNumberRegex = """.*[(]line-number (\d*)"[)]""".r
def processLine(line: String) = line match {
case OrderRegex(orderNumber) => {
if (orderLine != null) {
order = order.copy(lines = orderLine :: order.lines)
}
if (order != null) {
orders = order :: orders
}
order = Order(orderNumber.toInt)
}
case _ if line.contains("order-line") => {
if (orderLine != null) {
order = order.copy(lines = orderLine :: order.lines)
}
orderLine = OrderLine(order.number)
}
case QuantityRegex(quantity) => orderLine = orderLine.copy(quantity = quantity.toInt)
case ProductRegex(product) => orderLine = orderLine.copy(product = product)
case DescriptionRegex(description) => orderLine = orderLine.copy(description = description)
case LineNumberRegex(lineNumber) => orderLine = orderLine.copy(lineNumber = lineNumber.toInt)
case _ => //println(s"Ignoring: $line")
}
}
case class Order(number: Int, lines: List[OrderLine] = Nil)
case class OrderLine(orderNumber: Int,
quantity: Int = -1,
product: String = null,
description: String = null,
lineNumber: Int = -1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.