Jim Cheung

Java at Work

Gradle Projects

Load resource

Properties prop = new Properties();

Add Oracle JDBC jar

repositories {
    flatDir {
        dirs 'libs'
dependencies {
    compile name: 'ojdbc6'

quick java project scaffolding

gradle init --type java-library


  1. use application plugin:
    apply plugin: 'application'
    mainClassName = "com.example.Class"
run with `gradle run`
  1. use JavaExec:
    task execute(type:JavaExec) {
        main = mainClass
        classpath = sourceSets.main.runtimeClasspath
run with `gradle -PmainClass=com.example.Class execute` 
  1. also use application plugin, but only build once:
    > gradle installApp
    > java -cp "build/install/example/lib/*" com.example.Class

note, use quotes " and * not *.jar


read file in java 8

Stream<String> lines = Files.lines(Paths.get("filename.txt"));

read directory

    new File(".")
        .listFiles((f, n) -> n.endsWith(".java"))

parse json

ObjectMapper mapper = new ObjectMapper();
JsonNode jn = mapper.readTree(ClassLoader.getSystemResourceAsStream("album.json")).get("data");

Album[] albums = mapper.readValue(jn, Album[].class);

for(Album a : albums) {

for unknown structure, use something like this

mapper.readValue(json, new TypeReference<HashMap>(){});

add custom ssl cert

(under os x yosemite)

get the cert

openssl s_client -connect example.com:443 < /dev/null > public.crt

import it

sudo keytool -import -alias example.com -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -file public.crt

default password: changeit