Java at Work

Gradle Projects

Load resource

Properties prop = new Properties();
prop.load(ClassLoader.getSystemResourceAsStream("foo.properties"));

Add Oracle JDBC jar

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

quick java project scaffolding

gradle init --type java-library

run

  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

Snippets

read file in java 8

Stream<String> lines = Files.lines(Paths.get("filename.txt"));
lines.forEach(System.out::println);
lines.close();

read directory

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

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) {
    System.out.println(a);
}

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

Search Blog: