java ยท reference

Java Cool Tricks And Tips

This is a blog post where I’ll be collecting some cool Java tricks I keep forgetting about.

Logging

Enable http client / web services dumping

-Dlogging.level.org.apache.http=DEBUG
-Dlogging.level.org.springframework.ws.client.MessageTracing=TRACE

Testing log messages

// setup
StringWriter logCapture = new StringWriter();
WriterAppender logCaptureAppender = WriterAppender.createAppender(null, null, logCapture, "debug", false, true);
((org.apache.logging.log4j.core.Logger)LogManager.getLogger(MyTestClass.class)).addAppender(logCaptureAppender);
logCaptureAppender.start();
// test
...
// verify
BufferedReader reader = new BufferedReader(new StringReader(logCapture.getBuffer().toString()));
Assert.assertEquals("log line one", reader.readLine());
Assert.assertEquals("something else", reader.readLine());
// teardown
logCaptureAppender.stop();
((org.apache.logging.log4j.core.Logger)LogManager.getLogger(MyTestClass.class)).removeAppender(logCaptureAppender);

Setting custom log level

Configurator.setLevel(MyAwesomeClass.class.getName(), Level.DEBUG);

Maven

Download artifact manually

mvn -s ../Projects/rh/workspace/settings.xml org.apache.maven.plugins:maven-dependency-plugin:2.1:get  -DrepoUrl=http://repo1.maven.org/maven2/  -Dartifact=com.google.protobuf:protobuf-java:2.4.1    

Download source jars

mvn dependency:get -Dartifact=com.whatever:artifactname:versionNumber:jar:sources

Full debug

mvn -X

Sort pom

alias sortpom='mvn com.google.code.sortpom:maven-sortpom-plugin:sort -Dsort.nrOfIndentSpace=4 -Dsort.sortPlugins=groupId,artifactId -Dsort.sortDependencies=scope,artifactId -Dsort.sortProperties=true

Maven clean up after failed download

delete m2e-lastUpdated.properties files

OWASP check

mvn clean org.owasp:dependency-check-maven:check

Include git.properties in the jar

    <build>
        <plugins>
            <plugin>
                <groupId>pl.project13.maven</groupId>
                <artifactId>git-commit-id-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>revision</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <offline>true</offline>
                    <failOnNoGitDirectory>false</failOnNoGitDirectory>
                    <failOnUnableToExtractRepoInfo>false</failOnUnableToExtractRepoInfo>
                    <verbose>true</verbose>
                    <dateFormat>yyyy-MM-dd'T'HH:mm:ssZ</dateFormat>
                    <generateGitPropertiesFile>true</generateGitPropertiesFile>
                    <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
                </configuration>
            </plugin>
     ...
        </plugins>
    </build>

JVM

Crashdump disassembly

Copy paste hex bytes of assembly code into this script:

echo $'.text\n' >1.s; echo "48 8b 17 74 ..." | tr ' ' "\n" | while read f; do echo ".byte 0x"$f; done >> 1.s

then run:

as 1.s
objdump --adjust-vma=0x000000006da0307a -d a.out

I/O

Read file from classpath

try (var in = Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.txt")) {
    properties.load(in);
}

Concurrency

Concurrent map with lazy initialised values

Map<String, Long> lazyMap = new ConcurrentHashMap<>();

// get/init function
Long getCachedValue(String key) {
    lazyMap.computeIfAbsent(key, Util::someCreateMethodForKeyReturningLong);
}

Concurrent map with counters

Map<String, Long> counterMap = new ConcurrentHashMap<>();

// update function
void update(String key) {
    counterMap.merge(key, 1L, Long::sum);
}

Instrumentation

Determine memory consumption

    com.sun.management.ThreadMXBean threadManager = ((com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean());
    long l1 =  threadManager.getThreadAllocatedBytes(Thread.currentThread().getId());
    // do some stuff
    long l2 = threadManager.getThreadAllocatedBytes(Thread.currentThread().getId());
    // getThreadAllocatedBytes memory overhead is 48 bytes per call.
    System.out.println(l2 - l1 - 48);
Published:
comments powered by Disqus