Jan 6 2020

POJOs Made Easy with Project Lombok

Every Java application has some sort of bean or Plain Old Java Object (POJO) to hold and manage state. Because of good Object Oriented Programming (OOP) principles we encapsulate field access with getter and setter methods. Most modern IDEs allow you to quickly create getters and getters. You can often find a Generate option under the Code menu from your favorite IDE. But generating getters and setters produces a lot of unnecessary boilerplate code.

With Project Lombok, you can reduce all that boilerplate getter and setter code with a few annotations.

The following bit of code will produce a Java class with the necessary getters and setters to access all the defined fields.

package com.juixe.core.pojo;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@ToString @EqualsAndHashCode
@Getter @Setter
public class Person {
   private Long id;
   private String firstName;
   private String lastName;
}

Given the Person class above, you can start coding the following.

   Person p = new Person();
   p.setFirstName("Boingo");
   p.setLastName("API");
   p.setId(1000l);

The getter and setter methods are added to the bytecode for the Person class by Project Lombok through the annotations. If you remove one of the annotations, like the @Setter annotation, then the setters methods will be deleted.

We just saw how a few annotation can generate getters, setters, equals, hashCode, and toString methods for simple Java classes. If you want all these methods generated for you, automatically, you can just use the @Data annotation like the following.

package com.juixe.core.pojo;

import lombok.Data;

@Data
public class Person {
   private Long id;
   private String firstName;
   private String lastName;
}

There is also a @Value annotation that is similar to @Data except that it is intended for immutable objects, so it doesn’t generate any setter methods.


Jan 2 2020

Human JSON

JSON is a versatile format to define data. I read and write JSON all the time but as a subset of JavaScript, it has a few limitations, most notably the lack of support for comments. Enter HJSON, or Human JSON. HJSON makes quotes around object names optional, it makes quotes around strings optional as well, it adds support for multi-line strings, and allows you to add comments in a number of ways. The following is valid HJSON.

{
  // use #, // or /**/ comments,
  // omit quotes for keys
  key: 1
  // omit quotes for strings
  contains: everything on this line
  // omit commas at the end of a line
  cool: {
    foo: 1
    bar: 2
  }
  // allow trailing commas
  list: [
    1,
    2,
  ]
  // and use multiline strings
  realist:
    '''
    My half empty glass,
    I will fill your empty half.
    Now you are half full.
    '''
}

There is an implementation of HJSON for most popular languages, like Java, Python, Go, Python, etc. I’ve used the hjson-java library to read HJSON file and converted it to JSON in a few lines.


Dec 27 2019

Create a HTTP Server in Java

Here is a quick tutorial on how to create a local embedded HTTP server in Java to serve JSON data. The whole code in less than 30 lines on Java.

package com.juixe.json.server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;

public class JSONServer implements HttpHandler {

    public static void main(String[] args) throws IOException  {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/data", new JSONServer());
        server.setExecutor(null);
        server.start();
    }

    @Override
    public void handle(HttpExchange he) throws IOException {
        String response = "{\"message\": \"Hello, HTTP Client\"}";

        he.getResponseHeaders().set("Content-Type", "application/json;charset=UTF-8");
        he.sendResponseHeaders(200, response.length());
        he.getResponseBody().write(response.getBytes());
        he.close();
    }
}

The HttpServer and HttpHandler classes are part of the JRE, so no additional libraries are required. Java also includes a HttpsServer which supports SSL. In the HttpHandler, you can return any data but for this example we are returning a simple JSON response.


Sep 25 2019

Oracle OpenWorld 2019 Overview

The following is a short list of tools, libraries, and projects that I found interesting at Oracle OpenWorld 2019.

  • Oracle APEX – Rapid Application Development framework built on top of Oracle’s database.  With little code, build CRUD application around database tables or even excel documents.
  • Oracle Jet – Oracle’s JavaScript Extension Toolkit (JET) for building mobile and desktop web applications.
  • WeaveWorks Sock Shop – Microservice sample app, like Java Pet Store.
  • Micronaut – Full-stack polyglot framework for building microservice and serverless applications.
  • Helidon – Collection of Java libraries for developing microservices.
  • JHipster – Generate, develop, and deploy Spring Boot + Angular/React/Veue web applications and microservices
  • OpenAPI – API description format for REST APIs. Formerly known as Swagger, used to help to design, build, document, and consume REST APIs.
  • Moby Project – Open framework to assemble specialized container systems.
  • Eclipse Vert.x – Reactive tool-kit
  • Eclipse Theia – Cloud IDE platform, runs on Docker
  • Eclipse Che – Kubernetes native IDE, allowing you to code, build, test and run applications exactly as they run on production from any machine.
  • Eclipse MicroProfile – Specification to define a microservice application platform that is portable across multiple runtimes and vendors.
  • Eclipse CodeWind – Container support in Eclipse IDE, Eclipse Che, and VS Code.
  • Docker Kitematic – GUI application to run Docker containers.

May 29 2012

Formatting an Integer to String in Java

There are times when you need to format a integer or double value into a String, with the comma for values larger than a thousand. If you need to format a numeric value correctly based on the local formatting rules for numbers use the NumberFormat class. Different locales have different formatting rules, for example in France they use the comma as a decimal point where in the United States the comma is used for delimiting large numbers.

double val = 123456.78;
System.out.println(val); // 123456.78

// Use default locale to format string
String localFormat = NumberFormat.getNumberInstance().format(val);
System.out.println(localFormat); // 123,456.78
		
String frenchFormat = NumberFormat.getNumberInstance(Locale.FRANCE).format(val);
System.out.println(frenchFormat); // 123 456,78

Mar 19 2012

Retweet February 2012

From time to time I just blast tweets about software development, project planning, team dynamics, or whatever else comes to mind. Here is a synopsis of recent tweets and rants. If you want to follow the conversation follow me at techknow and/or juixe.

Software Development

  • Kids lunch snacks sound like Java interfaces, Uncrustables and Lunchables.
  • 99% of software is hardcoded defaults.
  • Software will shape the future.
  • I don’t count lines of code.
  • Code less, debug even less.
  • Every few years JavaScript goes through a renewed renaissance.
  • Sometimes life does not compute. #dividebyzeroerror

Team Leadership

  • Success is a dish best served with champagne.
  • Don’t let circumstance beyond your control control you.
  • Just because it’s widely accepted that Steve Jobs was difficult to work with and a genius doesnt mean you have to be difficult to work with.
  • Negativity is like cholesterol, to much of it can kill you.
  • Most important lesson in my life: Learn to appreciate what you have and do not agonize about what you don’t.
  • Corporate titles mean nothing, that is why I put Chief Creative Business Developer Principal Program Scientist on my business card.
  • The biggest lesson one can learn is to listen.
  • The universe doesn’t hate you, it doesn’t even know you exist.
  • Try harder. Do better. Go further. Think Bigger.
  • Forget stopping to smell the flowers, I stop to reach for the stars.

Product Placement

  • I’m going to start a search engine for ego searches and call it egoogle.
  • Google is a giant keyword router in the cloud.
  • Android uses food related codenames for its different versions, such as ice cream sandwhich. I hear next release will be named leftovers.
  • Why is Gingerbread still the most popular/common version of Android In new phones? It’s like two releases behind latest version.
  • I think it is safe to say that G+ is a successful flop. I would compare it more to MySpace than Facebook.
  • Missing Feature: I wouldn’t be surprised if the Kindle reader would allow you to tweet a quote right from an eBook.
  • If Apple would design single family homes it would cost over $1 million and only be 800 sq/ft but I would want one really bad.
  • iPhone or iMole: whatever data or contact or image you have on your iPhone some hacker, service, API, law enforcement, or app will access.
  • In today’s day and age, no person should be executed for tweeting and no person should have to go to jail for downloading a song.
  • Blue Ivy Carter sounds more like a brand name of vodka or energy drink put out by Jay-Z than the name of his kid.

Cash Angels

  • Who needs $3 million to run a WordPress-powered tech blog? At these valuations my blog is definitely worth $10 million.
  • Silicon Valley entrepreneurs are modern day alchemists turning virtual goods into real cold hard cash, IPOs into billions.
  • A frothy market is a tasty market.
  • The future is in crowd financing.
  • It’s raining stock options in Silicon Valley. #makeitrain
  • All the people of Palo Alto rejoice at news of Facebook IPO, in a few months their rents will go up 30%.
  • To much Facebook IPO analysis on my feed. If you aren’t a preferred investor you ain’t making money.
  • 1. _________. 2. $#%#%$*(&. 3. ?????? 4. Profit.

Question

  • Can software refactor the world?
  • How can people wave their constitutional rights be agreeing to a terms of service they didn’t read or understand?
  • Breyer’s or Dreyer’s?
  • Who will be the Bill Gates and Steve Jobs of 3D printing?
  • Forget “where’s the beef,” where’s the 100 Mbps broadband?
  • Who is Waldo?
  • If corporations are people does it mean a man can marry a corporation?

Equations

  • Principles > Politics
  • Generous > Gorgeous
  • Cheddar > Chatter
  • Worrier < Warrior
  • Sex On Fire > Heart On Fire