8 min read

Java Snippets #1

Mallim

Table of Contents

Eclipse

Google Guava

Joiner, Splitter, Precondition

Collections of tutorials on Google Guava

Other JDBC Clients

SQL Style Guideline

Interesting ideas:

  • Use != over <>
  • Column names should be snake_case
  • Avoid aliasing tables
  • Take advantage of lateral column aliasing
  • Grouping columns should go first
  • Always have a CTE named final

Common MySQL Queries

http://www.artfulsoftware.com/infotree/queries.php

can also think of it as a SQL cheatsheet

8 Bulk Update Methods in Oracle

http://www.orafaq.com/node/2450

  • Explicit Cursor Loop
  • Implicit Cursor Loop
  • UPDATE with nested SET subquery
  • BULK COLLECT / FORALL UPDATE
  • Updateable Join View
  • MERGE
  • Parallel DML MERGE
  • Parallel PL/SQL

How to skip SSL validation in RestTemplate?

@Bean can be declared in a @Component

NativeCriteria

Yes, Spring Boot 2 can be deployed to WAS 8.5...

Spring Standalone ApplicationRunner Example

Collections of articles on Spring Data /Hibernate

5 ways to customize Spring MVC JSON/XML output

Download a Large File Through a Spring RestTemplate

  • Download Without Resume
  • Download with Pause and Resume

Spring Boot RestController @RequestPart

Given

@RequestMapping(value="/upload",method=RequestMethod.POST)
public YourResponse uploadDocument( @RequestPart("meta-data") @Valid YourJson metadata,
                                    @RequestPart("file-data") MultipartFile incomingFile )

Then the multipart/mixed message to send is :

POST [http://{base_url}/upload](http://192.168.190.39:8080/document/upload/94671261-faa8-11e4-a578-7542d0ebc4e4) HTTP/1.1 Content-Type: multipart/mixed; boundary=ABC123Boundary Content-Length: 83746 {{NEW_LINE} --ABC123Boundary Content-Disposition: form-data; name="meta-data" Content-Type: application/json; charset=UTF-8 Content-Transfer-Encoding: 8bit {{NEW_LINE} { "id": 1, ... } {{NEW_LINE} --ABC123Boundary Content-Disposition: form-data; name="file-data"; filename="sdasdfa" Content-Type: application/octet-stream Content-Transfer-Encoding: 8bit {{NEW_LINE} binary-stream of file content {{NEW_LINE} --ABC123Boundary--

Spring Boot Concurrency Basics

https://www.e4developer.com/2018/03/30/introduction-to-concurrency-in-spring-boot/

  • server.tomcat.max-threads (default is 200)
  • @EnableAsync, @Async, CompletableFuture<>

Good to always keep in mind:

Spring Services and Controllers are Singletons by default.

Spring Data JPA @Query(native=true)

PipelinR

A lightweight command processing pipeline for Java.

@RequestMapping("/members")
public String post(@RequestBody BecomeAMember command) {
    return pipeline.send(command);
}

---

@Component
static class Handler implements Command.Handler<BecomeAMember, String> {
    @Override
    public String handle(BecomeAMember $) {
      var member = new Member(new Email($.email, blacklist));
      members.save(member);
      return member.id();
    }
}

Command Pattern

The @Command in Axon Framework is quite a sleek thing to use if you want to adopt Command pattern in your application. Alternatively, you may consulte the links below for other options:

  return serviceExecutor.execute(AddProductToCartCommand.class, request)
          .map(Response::ok)
          .subscribeOn(Schedulers.elastic());

Gatling, DeferredResult

Snippets

Lombok, Jackson and even Mybatis

Lombok immutable classes with builder that can be serialized and deserialized by Jackson.

@Data
@Setter(AccessLevel.NONE)
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Clazz {
  private String field;
}

https://stackoverflow.com/a/56127205/970200

ExecutorService - 10 tips and tricks

Generating QR Codes With Secure Hashes Using Java

ObjectMapper, CsvSchema, CsvMapper

Flux publishOn and then eg to save user

Got the idea from Developing Reactive applications with Reactive Streams and Java 8 by Brian Clozel, Sébastien Deleuze

Flux.publishOn( Scheduler.elastic() )
    .doOnNext( user -> BlockRepository.saveUser( user ) ).then()

Defer a Flux's blocking method

Got the idea from Developing Reactive applications with Reactive Streams and Java 8 by Brian Clozel, Sébastien Deleuze

Flux.defer( () -> Flux.iteratable( BlockRepository.findAllUsers() ) )
    .subscribeOn( Scheduler.elastic() )

Refactoring with Loops and Collection Pipelines

https://martinfowler.com/articles/refactoring-pipelines.html

  public List<String> twitterHandles(List<Author> authors, String company) {
    return authors.stream()
            .filter(a -> a.getCompany().equals(company))
            .map(a -> a.getTwitterHandle())
            .filter(h -> null != h)
            .collect(toList());
  }

Assert an Exception is Thrown in JUnit 4 and 5

@Test
public void whenDerivedExceptionThrown_thenAssertionSucceds() {
    String test = null;
    assertThrows(RuntimeException.class, () -> {
        test.length();
    });
}

Java Strings, Generics, Collections, Exceptions, Enums and Annotations Best Practices

Interesting Libraries

java-uuid-generator

Java Uuid Generator (JUG) is a library for generating all (3) types of UUIDs on Java.

https://github.com/cowtowncoder/java-uuid-generator

Tablesaw

Tablesaw - is a Java dataframe similar to Pandas in Python. That is why I notice it.

SQL Tableasw Example
WHERE Table result = t.where(nc1.isGreaterThan(4));
ORDER BY Table sorted = table.sort("foo", "bar", "bam");
GROUP BY Table summary = table.summarize("sales", mean, sum, min, max).by("province", "status");

JSONB

Randoop

Randoop - Automatic unit test generation for Java. Only if you simply just want coverage for tons of Java classes which I normally just start from something small first.

Life outside Spring Security

  • jCasbin - An authorization library that supports access control models like ACL, RBAC, ABAC in Java

which reminds me of

  • OACC - Java Application Security Framework.

Logging supplementary - Logbook

  • Logbook - An extensible Java library for HTTP request and response logging. Worth taking note on this point: Logbook puts a big emphasis on logging the actual request/response body that was sent over the wire. The Apache HttpClient, among the following alternatives, is the only technology to support that.