RingJavafor Ring

A CSV report

Java reads and writes the files, jQuery groups and totals the rows.

What you will learn#

The program#

samples/UsingJava/tutorials/ch26_csv_report.ring
# Tutorial 26: a CSV report - Java reads and writes the files, jQuery groups and totals the rows
load "java.ring"

using {
	"java.io"
	"java.nio.file"
}

Files = new Files

# 1. a CSV file in a temporary folder, written with java.nio.file
oFolder = Files.createTempDirectory(["report",[]])
oSales = oFolder.resolve("sales.csv")
cCsv = "region,product,units,price" + nl +
	"North,Book,3,30" + nl +
	"South,Course,1,120" + nl +
	"North,Course,2,120" + nl +
	"East,Book,5,30" + nl +
	"South,Book,4,30" + nl +
	"East,Coffee,10,4"
Files.writeString([oSales,cCsv,[]])

# 2. read it back, line by line, into a list of rows (the first line has the names of the columns)
aLines = Files.readAllLines(oSales).toList()
aRows = []
for nAt = 2 to len(aLines)
	aParts = str2list(substr(aLines[nAt],",",nl))
	aRows + [aParts[1],aParts[2],0 + aParts[3],0 + aParts[4]]
next
? "" + len(aRows) + " rows"

# 3. totals with jQuery: x[3] * x[4] is units times price
? "revenue " + jQuery(aRows).sum("x[3] * x[4]")
? "best sale " + jQuery(aRows).sortByDesc("x[3] * x[4]").first()[2]

# 4. a group for each region with its total, biggest first
aByRegion = jQuery(aRows).groupBy("x[1]").map("[x[1], jQuery(x[2]).sum('x[3] * x[4]')]").sortByDesc("x[2]").toList()
for aGroup in aByRegion
	? aGroup[1] + ": " + aGroup[2]
next

# 5. the report is written with Java too
aReport = [ "Revenue by region" ]
for aGroup in aByRegion
	aReport + (aGroup[1] + ";" + aGroup[2])
next
oReport = oFolder.resolve("report.txt")
Files.writeString([oReport,jQuery(aReport).join(nl),[]])
? "report: " + len(Files.readAllLines(oReport).toList()) + " lines"

# 6. clean up
Files.delete(oSales)
Files.delete(oReport)
Files.delete(oFolder)
? "folder is gone: " + (not Files.exists(oFolder,[]))
Output
6 rows
revenue 760
best sale Course
North: 330
South: 240
East: 190
report: 4 lines
folder is gone: 1

How it works#

Files.readAllLines gives a Java list that toList() turns into a Ring list of texts. Each line is split at the commas and the numbers are converted with 0 + text. After that everything is Ring: groupBy("x[1]") gives [region, rows] pairs and the map that follows totals each group with a second jQuery. Java writes the report again with Files.writeString.

Exercises#

  1. Add the average price of each product.
  2. Write the report as a CSV file too.
  3. Read a file that has a header line you did not expect and show a clear error.

Next#

Images

RingJava - use Java classes and methods from Ring programs.