Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding snippets and testing tools #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions .github/tools/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>tools</artifactId>
<version>1.0.0</version>
<groupId>dev.playground</groupId>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<mainClass>dev.playground.tools.IndexJson</mainClass>
<junit.version>5.9.2</junit.version>
</properties>

<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>${mainClass}</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
</plugins>
</build>
</project>
43 changes: 43 additions & 0 deletions .github/tools/src/main/java/dev/playground/tools/IndexJson.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package dev.playground.tools;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;

public class IndexJson {

static final String rawGithubCDNPrefix = "https://raw.githubusercontent.com/java/playground-snippets/main/";

public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.err.println("USAGE:\n\t[program] <path-to-snippets-folder>");
System.exit(1);
}
var strPath = args[0];
var path = Path.of(strPath);
if (!path.toFile().exists()) {
System.err.printf("Directory %s does not exist!\nUSAGE:\n\t[program] <path-to-snippets-folder>\n", path);
System.exit(1);
}

String result;
try(var walker = Files.walk(path)) {
result = walker.filter(f -> !Files.isDirectory(f)).map(key -> {
var strKey = key.toString().replace(strPath + "/", "");
var strValue = rawGithubCDNPrefix + strKey;

return String.format("\t\"%s\": \"%s\"", strKey, strValue);
}).collect(Collectors.joining(",\n"));
}
var indexJsonContent = String.format("{\n%s\n}", result);
var indexJsonFilePath = Path.of(strPath, "index.json");
System.out.println(indexJsonFilePath);
Files.deleteIfExists(indexJsonFilePath);
indexJsonFilePath.toFile().createNewFile();

Files.writeString(indexJsonFilePath, indexJsonContent);
System.out.println(indexJsonContent);
}
}
4 changes: 4 additions & 0 deletions .github/tools/src/main/resources/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# DISCLAIMER


[snippets](snippets) is a symlink to a [root folder](../../../../../snippets).
3 changes: 3 additions & 0 deletions .github/tools/src/main/resources/snippets/hello-world.snippet
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
var name = "Duke";

System.out.println("Hello, " + name);
20 changes: 20 additions & 0 deletions .github/tools/src/main/resources/snippets/index.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"misc/simple-collection.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/misc/simple-collection.snippet",
"misc/func-interface.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/misc/func-interface.snippet",
"misc/functions-chaining.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/misc/functions-chaining.snippet",
"records/composing.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/records/composing.snippet",
"records/simple.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/records/simple.snippet",
"records/method-overriding.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/records/method-overriding.snippet",
"streams/filtering.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/streams/filtering.snippet",
"streams/stream-to-list.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/streams/stream-to-list.snippet",
"streams/text-block-to-stream.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/streams/text-block-to-stream.snippet",
"textblocks/formatting.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/textblocks/formatting.snippet",
"textblocks/simple.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/textblocks/simple.snippet",
"textblocks/record.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/textblocks/record.snippet",
"hello-world.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/hello-world.snippet",
"switch/expression.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/switch/expression.snippet",
"switch/pattern-matching.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/switch/pattern-matching.snippet",
"switch/statement.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/switch/statement.snippet",
"pattern-matching/record.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/pattern-matching/record.snippet",
"pattern-matching/switch.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/pattern-matching/switch.snippet"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
@FunctionalInterface
interface MyFunctionalInterface {
public int incrementByTwo(int a);
}

MyFunctionalInterface f = (num) -> num + 2;
var result = f.incrementByTwo(40);

System.out.println(result);
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
var strings = Arrays.asList("one", null, "three", "", "five", "six");

Function<String, String> handleNull = s -> s == null ? "": s;
Function<String, Integer> length = s -> s.length();
Function<String, Integer> handleNullThenLength = handleNull.andThen(length);

for (String string : strings) {
System.out.println(string + " -> length = " + handleNullThenLength.apply(string));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Collection<String> numbers = new ArrayList<>();
numbers.add("one");
numbers.add("two");
numbers.add("three");
numbers.remove("two");
System.out.println(numbers);
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
record Point(int x, int y) {
public boolean equals(Object other) {
return other instanceof Point otherPoint &&
this.x == otherPoint.x && this.y == otherPoint.y;
}
}

Point p1 = new Point(0, 0);
Point p2 = new Point(1, 1);
Point p3 = new Point(0, 0);
System.out.println("p1 equals object? " + p1.equals(new Object()));
System.out.println("p1 equals p2? " + p1.equals(p2));
System.out.println("p1 equals p3? " + p1.equals(p3));
System.out.println("p2 equals p3? " + p2.equals(p3));
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
record Point(int x, int y) {}

record Circle(Point center, int radius) {
public Circle {
if (radius < 0) throw new IllegalArgumentException("Radius cant be null");
}
}

ToDoubleFunction<Object> surface = object ->
switch(object) {
case null -> throw new AssertionError("Object is null");
case Circle(Point p, int radius) when radius == 0 -> 0d;
case Circle(Point p, int radius) -> Math.PI*radius*radius;
case Object notACircle -> throw new AssertionError("Object is not a circle");
};

Circle c1 = new Circle(new Point(0, 0), 0);
Circle c2 = new Circle(new Point(1, 1), 1);

System.out.println("Surface of " + c1 + " = " + surface.applyAsDouble(c1));
System.out.println("Surface of " + c2 + " = " + surface.applyAsDouble(c2));
surface.applyAsDouble(null);
surface.applyAsDouble("Not a circle!");
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
record Population(int population) {}
record City(String name, Population population) {
// static methods are allowed in records
public static City of(String name, int p) {
var population = new Population(p);
return new City(name, population);
}
}

var paris = City.of("Paris", 2_161);
System.out.println(paris);
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
record City(String name) {

public boolean equals(Object other) {
return other instanceof City(String name) &&
this.name.equalsIgnoreCase(name);
}

public int hashCode() {
return name != null ? name.toUpperCase().hashCode() : 0;
}
}

var paris1 = new City("Paris");
var paris2 = new City("paris");
var paris3 = new City("PARIS");
System.out.println("1 == 2 ? " + paris1.equals(paris2));
System.out.println("2 == 3 ? " + paris2.equals(paris3));
System.out.println("1 == 3 ? " + paris1.equals(paris3));
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
record Player(String last, String first, int level) {}
var jane = new Player("Doe", "Jane", 42);
System.out.println(jane);
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
List<String> cities =
Arrays.asList("Shenzhen", "Brussels", "Taipei", "Buenos Aires", "Sydney", "Bristol");

cities.stream()
.filter(s -> s.startsWith("B"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Stream<String> stream = Stream.of("Shenzhen", "Brussels", "Taipei", "Buenos Aires", "Sydney", "Bristol");

List<String> cities = stream.sorted().collect(Collectors.toList());

System.out.println(cities);
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
var cities = """
San Francisco
Casablanca
Antwerp
New Delhi
Osaka
""";

Stream<String> lines = cities.lines();

System.out.println(lines.toList());
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }

Day day = Day.SUNDAY;
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};

System.out.println(numLetters);
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
var result = switch ("Lorem Ipsum") {
case null -> "Oops";
case "Foo", "Bar" -> "Great";
default -> "Ok!";
};
System.out.println(result);
21 changes: 21 additions & 0 deletions .github/tools/src/main/resources/snippets/switch/statement.snippet
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }
var numberOfChar = 0;

switch(Day.MONDAY) {
case MONDAY: case FRIDAY: case SUNDAY:
numberOfChar = 6;
break;
case TUESDAY:
numberOfChar = 7;
break;
case WEDNESDAY:
numberOfChar = 9;
break;
case THURSDAY: case SATURDAY:
numberOfChar = 8;
break;
default:
throw new IllegalArgumentException();
}

System.out.println(numberOfChar);
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
var message = """
{"name" : "%s", "language" : "Java"}
""";
System.out.println(message.formatted("Duke"));
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
record City(String name, int population) {

public static City of(String line) {
int indexOfLastSpace = line.lastIndexOf(' ');
var name = line.substring(0, indexOfLastSpace);
var population = Integer.parseInt(line.substring(indexOfLastSpace + 1));
return new City(name, population);
}
}

String cities = """
New York 8343
London 8982
Paris 2161
Bangaluru 8474
Singapore 5454
Tokyo 13960
""";

var cityList = cities.lines().map(City::of).toList();
cityList.forEach(System.out::println);
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
String cities = """
New York \s
Paris \s
Bangalore \s
Singapore \s
Tokyo \s
""";

cities.lines().map(line -> "|" + line + "|").forEach(System.out::println);
Loading