Samples with their output
The console programs of the package: the source, and what each one prints when it runs.
The output below comes from running the programs (ringdoc build --refresh runs them again). The programs of ecosystem download their packages from Maven Central the first time.
A first program: a static method, an object, a constant#
samples/UsingJava/introduction/01_hello.ring
samples/UsingJava/introduction/01_hello.ring
# Hello from Java: a static method, an object and a field
load "java.ring"
using {
"java.lang"
}
? Math.max(3,9) # 9: a static method
oSB = new StringBuilder("Hello")
oSB.append(", Ring!")
? oSB.toString() # Hello, Ring!
? oSB.length() # 12
? Integer.MAX_VALUE # 2147483647: a constant
? jVersion() # the version of the JDK that runs the program
# System.out is a Java object too
System.out.@println("printed by Java's System.out")9
Hello, Ring!
12
2147483647
21.0.8
printed by Java's System.outStrings and text#
samples/UsingJava/introduction/02_strings.ring
samples/UsingJava/introduction/02_strings.ring
# The String and StringBuilder classes of Java
load "java.ring"
using {
"java.lang"
}
oText = new String("Ring and Java")
? oText.toUpperCase() # RING AND JAVA
? oText.length() # 13
? oText.indexOf("and") # 5
? oText.substring(5) # and Java
? oText.substring([5,8]) # and: the other version of substring has two values (name_2)
? oText.replace("Java","Ring") # Ring and Ring
? oText.contains("Java") # 1
? oText.split(" ").toList() # a Java array as a Ring list
? String.join("-",["a","b","c"]) # a-b-c: a Ring list for a Java array
? String.format(["%s has %d letters",["Ring",4]])
? String.format(["%08.3f",[3.14159]]) # 0003.142
# Unicode text is UTF-8 in Ring and UTF-16 in Java: the conversion is automatic
oArabic = new String("مرحبا")
? oArabic.length() # 5 letters (not the bytes)RING AND JAVA
13
5
and Java
and
Ring and Ring
1
Ring
and
Java
a-b-c
Ring has 4 letters
0003.142
5Collections#
samples/UsingJava/introduction/03_collections.ring
samples/UsingJava/introduction/03_collections.ring
# Lists, maps and sets of java.util
load "java.ring"
using {
"java.lang"
"java.util"
}
oList = new ArrayList
oList.add("pear")
oList.add("apple")
oList.add("fig")
(new Collections).sort(oList)
? oList.toString() # [apple, fig, pear]
? oList.@get(0) # apple: get is a word of Ring, so the method is @get
? oList.size()
? oList.toList() # a Ring list
oMap = new HashMap
oMap.@put("one",1)
oMap.@put("two",2)
? oMap.@get("two") # 2
? oMap.containsKey("one") # 1
aPairs = oMap.toList() # a list of [key, value]
for aPair in aPairs
? aPair[1] + " = " + aPair[2]
next
oSet = new TreeSet([5,1,3,1,5]) # a Ring list becomes a Java collection
? oSet.toString() # [1, 3, 5]
# an object can be used in a for loop with toList()
aLetters = new ArrayList(["x","y"]).toList()
for x in aLetters
? x
next[apple, fig, pear]
apple
3
apple
fig
pear
2
1
one = 1
two = 2
[1, 3, 5]
x
yDates and times#
samples/UsingJava/introduction/04_time.ring
samples/UsingJava/introduction/04_time.ring
# Dates and times: java.time
load "java.ring"
using {
"java.time"
"java.time.format"
"java.time.temporal"
}
oDate = (new LocalDate).of(2024,2,29)
? oDate.toString() # 2024-02-29
? oDate.plusDays(1).toString() # 2024-03-01
? oDate.getDayOfWeek().toString() # THURSDAY
? oDate.isLeapYear() # 1
oFormat = (new DateTimeFormatter).ofPattern("EEEE, d MMMM yyyy")
? oDate.format(oFormat) # Thursday, 29 February 2024
oPeriod = (new Period).between(oDate,(new LocalDate).of(2025,1,1))
? "" + oPeriod.getMonths() + " months and " + oPeriod.getDays() + " days"
oDuration = (new Duration).ofMinutes(135)
? "" + oDuration.toHours() + " hours " + (oDuration.toMinutes() % 60) + " minutes"
? (new ChronoUnit).DAYS.between(oDate,(new LocalDate).of(2024,12,25)) # days until Christmas2024-02-29
2024-03-01
THURSDAY
1
Thursday, 29 February 2024
10 months and 3 days
2 hours 15 minutes
300Files#
samples/UsingJava/introduction/05_files.ring
samples/UsingJava/introduction/05_files.ring
# Files and paths with java.nio.file and java.io
load "java.ring"
using {
"java.lang"
"java.io"
"java.nio.file"
}
oFiles = new Files
oPath = oFiles.createTempFile(["ringjava",".txt",[]])
? "temp file: " + oPath.getFileName().toString()
oFiles.writeString([oPath,"first line" + nl + "second line" + nl + "third line",[]])
? oFiles.size(oPath)
? oFiles.readString(oPath)
aLines = oFiles.readAllLines(oPath).toList()
for cLine in aLines
? "> " + cLine
next
oWriter = new PrintWriter(new FileWriter(oPath.toString()))
oWriter.@println("written with a PrintWriter")
oWriter.close()
oReader = new BufferedReader(new FileReader(oPath.toString()))
? oReader.readLine()
oReader.close()
oFiles.delete(oPath)
? oFiles.exists(oPath,[]) # 0temp file: ringjava16354424994725327323.txt
33
first line
second line
third line
> first line
> second line
> third line
written with a PrintWriter
0Ring functions that Java calls#
samples/UsingJava/introduction/06_callbacks.ring
samples/UsingJava/introduction/06_callbacks.ring
# Ring code that Java runs: a Comparator, a Predicate and a Function written as Ring functions
load "java.ring"
using {
"java.util"
"java.util.function"
}
oNames = new ArrayList(["Mahmoud","Ali","Fatima","Sam"])
oNames.sort("byLength")
? oNames.toString() # [Ali, Sam, Fatima, Mahmoud]
# Ring code in a text: aJavaArgs has the arguments of Java, xJavaResult is the answer
oNames.sort("xJavaResult = len(aJavaArgs[2]) - len(aJavaArgs[1])")
? oNames.toString() # the longest first
# a stream with Ring functions
oStream = oNames.stream()
? oStream.filter("startsWithA").count() # names that start with A
oSquares = (new Arrays).asList([1,2,3,4]).stream().map("square")
? oSquares.toList() # [1, 4, 9, 16]
func byLength aArgs
return len(aArgs[1]) - len(aArgs[2])
func startsWithA aArgs
return left(aArgs[1],1) = "A"
func square aArgs
return aArgs[1] * aArgs[1][Ali, Sam, Fatima, Mahmoud]
[Mahmoud, Fatima, Ali, Sam]
1
1
4
9
16Threads#
samples/UsingJava/introduction/07_threads.ring
samples/UsingJava/introduction/07_threads.ring
# Threads: Java threads call Ring callbacks while the program waits in jJoin(), jSleep() or jPump()
load "java.ring"
using {
"java.lang"
"java.util.concurrent"
"java.util.concurrent.atomic"
}
oCounter = new AtomicInteger(0)
aThreads = []
for i = 1 to 3
oThread = new Thread(jCallback("work"))
oThread.start()
aThreads + oThread
next
for oThread in aThreads
jJoin(oThread)
next
? "counter = " + oCounter.@get() # 3
# an executor with a pool of threads
oPool = (new Executors).newFixedThreadPool(2)
oFuture = oPool.submit("compute")
jWaitUntil("futureDone",5000)
? "future = " + oFuture.@get()
oPool.shutdown()
func work aArgs
oCounter.incrementAndGet()
func compute aArgs
return 6 * 7
func futureDone
return oFuture.isDone()counter = 3
future = 42The dynamic API#
samples/UsingJava/introduction/08_dynamic.ring
samples/UsingJava/introduction/08_dynamic.ring
# The dynamic API: no generated classes and no using { } needed
load "java.ring"
oList = jNew("java.util.ArrayList",[])
oList.callMethod("add",["Ring"])
oList.callMethod("add",["Java"])
? oList.toString()
? jStatic("java.lang.Math","max",[7,3])
? jGetStatic("java.lang.Integer","MAX_VALUE")
oMath = jClass("java.lang.Math") # a class: its static methods and fields
? oMath.callStatic("sqrt",[144])
? oMath.getStatic("PI")
# the members of a class
aMembers = jDescribe("java.lang.Math")
for cMember in aMembers
if substr(cMember,"static method public static double java.lang.Math.s") > 0
? cMember
ok
next
# a Java array, a typed value and the null reference
oArray = jArray("java.lang.String",["b","c","a"])
(jClass("java.util.Arrays")).callStatic("sort",[oArray])
? oArray.toList()
? jIsNull(jNull())[Ring, Java]
7
2147483647
12
3.14
static method public static double java.lang.Math.scalb(double,int)
static method public static double java.lang.Math.signum(double)
static method public static double java.lang.Math.sin(double)
static method public static double java.lang.Math.sinh(double)
static method public static double java.lang.Math.sqrt(double)
a
b
c
1Queries#
samples/UsingJava/introduction/09_query.ring
samples/UsingJava/introduction/09_query.ring
# jQuery: filter, sort, group and total a list (or any Java collection) with one chain
load "java.ring"
using {
"java.util"
}
aPeople = [
["Ali","Cairo",31],
["Sara","Dubai",27],
["Omar","Cairo",45],
["Lina","Riyadh",38],
["Zaid","Dubai",19]
]
# the code is Ring text: x is the item (a second value is y)
? "Over 25, by age, oldest first:"
for aPerson in jQuery(aPeople).filter("x[3] > 25").sortByDesc("x[3]").toList()
? " " + aPerson[1] + " (" + aPerson[3] + ")"
next
? "Names: " + jQuery(aPeople).sortBy("x[1]").map("x[1]").join(", ")
? "Average age: " + jQuery(aPeople).average("x[3]")
? "Oldest: " + jQuery(aPeople).sortByDesc("x[3]").first()[1]
? "By city:"
for aGroup in jQuery(aPeople).sortBy("x[2]").groupBy("x[2]").toList()
? " " + aGroup[1] + ": " + jQuery(aGroup[2]).map("x[1]").join(", ")
next
# a Java collection is a source too
oList = new ArrayList
oList.add("pear")
oList.add("fig")
oList.add("apple")
? jQuery(oList).sortBy("len(x)").join(" < ")
? jQuery(jRange(1,10)).filter("x % 2 = 0").map("x * x").join(" ")Over 25, by age, oldest first:
Omar (45)
Lina (38)
Ali (31)
Sara (27)
Names: Ali, Lina, Omar, Sara, Zaid
Average age: 32
Oldest: Omar
By city:
Cairo: Ali, Omar
Dubai: Sara, Zaid
Riyadh: Lina
fig < pear < apple
4 16 36 64 100A database with H2#
samples/UsingJava/ecosystem/01_h2_database.ring
samples/UsingJava/ecosystem/01_h2_database.ring
# A database from Ring: the H2 database (a jar from Maven Central) through JDBC. The first run downloads the jar (about 2.5 MB) to ~/.ringjava/maven.
load "java.ring"
jMaven("com.h2database:h2:2.2.224")
oDb = jSqlConnect("jdbc:h2:mem:demo")
jSqlScript(oDb,"
create table language (id int primary key, name varchar(40), released int);
insert into language values (1, 'Ring', 2016);
insert into language values (2, 'Java', 1995);
insert into language values (3, 'C', 1972)
")
? "Languages older than 2000:"
aRows = jSqlQuery(oDb,"select * from language where released < ? order by released",[2000])
for aRow in aRows
? " " + aRow[:id] + " " + aRow[:name] + " " + aRow[:released]
next
jSqlExec(oDb,"update language set released = ? where name = ?",[2015,"Ring"])
? "Ring since " + jSqlValue(oDb,"select released from language where name = ?",["Ring"])
? "rows: " + jSqlValue(oDb,"select count(*) from language",[])
oDb.close()Languages older than 2000:
3 C 1972
2 Java 1995
Ring since 2015
rows: 3JSON with Jackson#
samples/UsingJava/ecosystem/02_json_jackson.ring
samples/UsingJava/ecosystem/02_json_jackson.ring
# JSON with Jackson. jackson-databind and its dependencies (core, annotations) come from Maven Central: jMavenClasses finds them all and makes the Ring classes.
load "java.ring"
jMavenClasses("com.fasterxml.jackson.core:jackson-databind:2.17.0",["com.fasterxml.jackson.databind"])
using {
"com.fasterxml.jackson.databind"
"java.util"
}
oMapper = new ObjectMapper
cJson = '{ "name": "RingJava", "tags": ["ring", "java"], "version": { "major": 1, "minor": 0 } }'
oTree = oMapper.readTree(cJson)
? oTree.@get("name").asText(NULL)
? oTree.@get("version").@get("minor").asInt(NULL)
aTags = oTree.@get("tags").toList()
for oTag in aTags
? "tag: " + oTag.asText(NULL)
next
# a Java Map -> JSON text
oMap = new LinkedHashMap
oMap.@put("language","Ring")
oMap.@put("year",2016)
? oMapper.writeValueAsString(oMap)RingJava
0
tag: ring
tag: java
{"language":"Ring","year":2016}commons-lang3 and jsoup#
samples/UsingJava/ecosystem/03_commons_and_jsoup.ring
samples/UsingJava/ecosystem/03_commons_and_jsoup.ring
# Two libraries from Maven Central: Apache Commons Lang (used through the dynamic API) and jsoup, HTML parsing (with its Ring classes)
load "java.ring"
jMaven("org.apache.commons:commons-lang3:3.14.0")
cStringUtils = "org.apache.commons.lang3.StringUtils"
? jStatic(cStringUtils,"capitalize",["ring and java"])
? jStatic(cStringUtils,"reverse",["RingJava"])
? jStatic(cStringUtils,"leftPad",["7",3,"0"])
? jStatic(cStringUtils,"isNumeric",["12345"])
jMavenClasses("org.jsoup:jsoup:1.17.2",["org.jsoup","org.jsoup.nodes","org.jsoup.select"])
using {
"org.jsoup"
"org.jsoup.nodes"
"org.jsoup.select"
}
oDoc = (new Jsoup).parse("<html><body><h1>Title</h1><a href='/one'>One</a><a href='/two'>Two</a></body></html>")
? oDoc.select("h1").text()
aLinks = oDoc.select("a").toList()
for oLink in aLinks
? oLink.text(NULL) + " -> " + oLink.attr("href")
nextRing and java
avaJgniR
007
1
Title
One -> /one
Two -> /twoRing classes of a jar#
samples/UsingJava/ecosystem/04_generated_classes.ring
samples/UsingJava/ecosystem/04_generated_classes.ring
# The Ring classes of a Maven package: jMavenClasses makes them once (they are kept in the cache) and loads them, so the classes are used with new
load "java.ring"
jMavenClasses("org.apache.commons:commons-lang3:3.14.0",["org.apache.commons.lang3"])
using {
"org.apache.commons.lang3"
}
oUtils = new StringUtils
? oUtils.center(["Ring",11,"*"])
? oUtils.repeat(["ab",3])
? oUtils.abbreviate(["RingJava lets Ring use Java",15])***Ring****
ababab
RingJava let...A web server#
samples/UsingJava/introduction/10_web.ring: a server and a client in one program (see Web server).
A REST API#
samples/UsingJava/ecosystem/07_rest_api.ring
samples/UsingJava/ecosystem/07_rest_api.ring
# A small REST API: JavaDatabase keeps the notes (H2, in memory) and JavaWebServer answers the requests; the program also calls its own API.
# The first run downloads the H2 jar (about 2.5 MB) to ~/.ringjava/maven.
load "java.ring"
jMaven("com.h2database:h2:2.2.224")
oDatabase = new JavaDatabase("jdbc:h2:mem:notes",[
["Notes",[ ["Id","int",1], ["Title","string",0,[["required",1]]], ["Done","int",0,[["default",0]]] ]]
])
oServer = new JavaWebServer(0)
oServer.onGet("/notes","listNotes")
oServer.onGet("/notes/:id","showNote")
oServer.onPost("/notes","addNote")
oServer.onPut("/notes/:id","finishNote")
oServer.onDelete("/notes/:id","deleteNote")
cBase = oServer.url()
? jHttpPost(cBase + "/notes","Write the documentation","text/plain")[2]
? jHttpPost(cBase + "/notes","Test on Linux","text/plain")[2]
? jHttpPost(cBase + "/notes","Publish the package","text/plain")[2]
? jHttpSend("PUT",cBase + "/notes/2","","")[2]
? jHttpSend("DELETE",cBase + "/notes/3","","")[2]
? jHttpGet(cBase + "/notes")[2]
? jHttpGet(cBase + "/notes/1")[2]
? jHttpGet(cBase + "/notes/9")[1]
oServer.close()
oDatabase.close()
func noteJson aRow
return [["id",jDbValue(aRow,"id")],["title",jDbValue(aRow,"title")],["done",jDbValue(aRow,"done")]]
func listNotes oRequest
aNotes = []
for aRow in oDatabase.query("Notes",[["orderby",[["Id","asc"]]]])
aNotes + noteJson(aRow)
next
return jWebJson(aNotes)
func showNote oRequest
aRow = oDatabase.byKey("Notes",0 + oRequest.param("id"))
if len(aRow) = 0
return [404,"text/plain","no such note"]
ok
return jWebJson(noteJson(aRow))
func addNote oRequest
nId = oDatabase.insert("Notes",[["Title",oRequest.body()]])
return [201,"text/plain","created note " + nId]
func finishNote oRequest
oDatabase.update("Notes",0 + oRequest.param("id"),[["Done",1]])
return "finished"
func deleteNote oRequest
oDatabase.remove("Notes",0 + oRequest.param("id"))
return "deleted"created note 1
created note 2
created note 3
finished
deleted
[{"id":1,"title":"Write the documentation","done":0},{"id":2,"title":"Test on Linux","done":1}]
{"id":1,"title":"Write the documentation","done":0}
404A SQLite file#
samples/UsingJava/ecosystem/06_sqlite_file.ring
samples/UsingJava/ecosystem/06_sqlite_file.ring
# SQLite in a file, with the sqlite-jdbc driver from Maven Central (it carries the native SQLite library inside its jar)
load "java.ring"
jMaven("org.xerial:sqlite-jdbc:3.45.1.0")
cFile = currentdir() + "/demo.db"
oDb = jSqlConnect("jdbc:sqlite:" + cFile)
jSqlExec(oDb,"create table if not exists note (id integer primary key, title text, stars real)",[])
jSqlExec(oDb,"delete from note",[])
jSqlExec(oDb,"insert into note (title, stars) values (?, ?)",["First note",4.5])
jSqlExec(oDb,"insert into note (title, stars) values (?, ?)",["Second note",3])
aRows = jSqlQuery(oDb,"select * from note order by id",[])
for aRow in aRows
? "" + aRow[:id] + " " + aRow[:title] + " " + aRow[:stars]
next
? "average: " + jSqlValue(oDb,"select avg(stars) from note",[])
oDb.close()
remove(cFile)SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
1 First note 4.50
2 Second note 3
average: 3.75