Java librairies

Apache Commons

Commons CSV

Library to deal with CSV file parsing/writing. https://commons.apache.org/proper/commons-csv/

Usage

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
...
File csvFile = ...;
String newLine = System.getProperty("line.separator");
CSVFormat format = CSVFormat.EXCEL.withRecordSeparator(newLine).withDelimiter(';');
try (FileWriter fw = new FileWriter(csvFile); CSVPrinter cp = new CSVPrinter(fw, format)) {
     cp.printRecord(Arrays.asList("header1", "header2", "header3")); // Takes an Iterable<String>
     cp.printRecords(Arrays.asList(Arrays.asList("val11", "val12", "val13"), Arrays.asList("val21", "val22", "val23"))); // Takes an Iterable<Iterable<String>>
} catch (Exception e) { ... }

Log4j

Library to deal with logging. http://logging.apache.org/log4j/2.x/

Usage

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
...
private final static Logger LOGGER = LogManager.getLogger();
...
LOGGER.debug(String.format("Obtaining messages in interval [%s, %s]", startDate, endDate));

Ultimate configuration file

The logs are archived in a folder year-month, maximum 10 files of 50MB per day, zipped.

log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
 
	<Properties>
		<Property name="pattern">%d{Y-M-d HH:mm:ss.SSS} [%-6level] [%c{1}] %msg%n</Property>
		<Property name="logPath">logs/</Property>
		<Property name="maxSize">50MB</Property>
		<Property name="maxFiles">10</Property>
		<Property name="extension">.log.gz</Property> <!-- .log = non compressed, .log.gz = compressed -->
	</Properties>
 
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="${sys:pattern}" />
		</Console>
		<RollingRandomAccessFile name="WarnFile" fileName="${sys:logPath}warn.log"
			filePattern="${sys:logPath}$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i${sys:extension}">
			<PatternLayout pattern="${sys:pattern}" />
			<Policies>
				<OnStartupTriggeringPolicy />
				<TimeBasedTriggeringPolicy interval="1" modulate="true" />
				<SizeBasedTriggeringPolicy size="${sys:maxSize}" />
			</Policies>
			<DefaultRolloverStrategy max="${sys:maxFiles}" />
		</RollingRandomAccessFile>
		<RollingRandomAccessFile name="InfoFile" fileName="${sys:logPath}info.log"
			filePattern="${sys:logPath}$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i${sys:extension}">
			<PatternLayout pattern="${sys:pattern}" />
			<Policies>
				<OnStartupTriggeringPolicy />
				<TimeBasedTriggeringPolicy interval="1" modulate="true" />
				<SizeBasedTriggeringPolicy size="${sys:maxSize}" />
			</Policies>
			<DefaultRolloverStrategy max="${sys:maxFiles}" />
		</RollingRandomAccessFile>
		<RollingRandomAccessFile name="TraceFile" fileName="${sys:logPath}trace.log"
			filePattern="${sys:logPath}$${date:yyyy-MM}/trace-%d{yyyy-MM-dd}-%i${sys:extension}">
			<PatternLayout pattern="${sys:pattern}" />
			<Policies>
				<OnStartupTriggeringPolicy />
				<TimeBasedTriggeringPolicy interval="1" modulate="true" />
				<SizeBasedTriggeringPolicy size="${sys:maxSize}" />
			</Policies>
			<DefaultRolloverStrategy max="${sys:maxFiles}" />
		</RollingRandomAccessFile>
	</Appenders>
 
	<Loggers>
		<Root level="TRACE">
			<AppenderRef ref="Console" level="DEBUG" />
			<AppenderRef ref="WarnFile" level="WARN" />
			<AppenderRef ref="InfoFile" level="INFO" />
			<AppenderRef ref="TraceFile" level="TRACE" />
		</Root>
	</Loggers>
 
</Configuration>

Eclipse : Put this file in a resources/ folder at the root of your project, and add this folder as a Class Folder in Project Properties > Java Build Path > Librairies.

json-simple

Usage

String date = ((JSONObject) JSONValue.parse("{\"time\":1455279796,\"short\":false,\"forceseconds\":false}")).get("time").toString();

jsoup

Library to deal with HTML parsing. http://jsoup.org/

Usage

String loginPageHtml = "...";
Document loginPage = Jsoup.parse(loginPageHtml);
Elements inputs = loginPage.select("input");
for (Element input : inputs) {
	System.out.println(input.attr("name") + " = " + input.val());
}
Elements textElements = message.select("div[data-sigil=\"message-text\"]");

json-io

Library to read/write objects to json files. Can even serialize objects who are not implementing Serializable! https://github.com/jdereg/json-io

Ehcache

“Ehcache is an open source, standards-based cache that boosts performance, offloads your database, and simplifies scalability.” http://www.ehcache.org/

Getting started guide

Initialize a cache manager with a pre-configured cache (Long; String)

CacheManager cacheManager = CacheManagerBuilder
	.newCacheManagerBuilder()
	.withCache(
		"myCacheName",
		CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)))
	.build(true);

Initialize an empty cache manager and then declare a cache (Long; String)

CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder();
cacheManager.createCache(
	"myCacheName",
	CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)).build());
cacheManager.init();

Read / Write in cache

Cache<Long, String> cache = cacheManager.getCache("myCacheName", Long.class, String.class);
cache.put(1L, "world");
System.out.println("Hello " + cache.get(1L));

Delete caches

cacheManager.removeCache("myCacheName"); // remove one cache
cacheManager.close();                    // remove all caches

Heap + Off-heap + Persisted cache

Persistence location is configured both at manager and cache level.

CacheManager cacheManager = CacheManagerBuilder
	.newCacheManagerBuilder()
	.with(CacheManagerBuilder.persistence(new File(".") + File.separator + "persistenceFolder"))
	.withCache(
		"myPersistedCacheName",
		CacheConfigurationBuilder.newCacheConfigurationBuilder(
			Long.class,
			String.class,
			ResourcePoolsBuilder.newResourcePoolsBuilder()
				.heap(10, EntryUnit.ENTRIES)            // The first 10 entries are always in memory
				.offheap(1, MemoryUnit.MB)              // Then the next 1 MB of entries are off-heap (no GC, but slower I/O)
				.disk(10, MemoryUnit.MB, true)))        // Finally, 10 MB is persisted on disk. If the program is restarted gracefully, it's restored!
	.build(true);

Expiry

The entries are automatically removed after a while. Expiry is configured at cache level.

cacheManager.createCache(
	"myExpirableCacheName",
	CacheConfigurationBuilder
		.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100))
		.withExpiry(Expirations.timeToLiveExpiration(Duration.of(30, TimeUnit.SECONDS)))  // expires 30 seconds after it's creation
                .build());

If you use “.timeToIdleExpiration(…)” instead, the entry expires 30 seconds after its last access.

A custom expiration can be defined by extending the Expiry interface.

Initialize cache from XML configuration

Print/export