[Improvement] Learn Java through simple tool creation

theme

Last time, Java version of the simple tool "Key-value store saved in local JSON file" written in Golang. As a series product, I originally wrote and compared programs with the same content in multiple languages "Learn while comparing each programming language through simple tool creation" Improved version from.

Trial Index

--Part 1: Learn while comparing each programming language through simple tool creation --Part 2: [Improvement] Learn Ruby through simple tool creation --Part 3: [Improvement] Learn Python3 through simple tool creation --Part 4: [Improvement] Learn Golang through simple tool creation --The 5th: [Improvement] Learn Java through simple tool creation --Part 6: [Improvement] Learn Scala through simple tool creation

Implementation / operation check terminal

#Language version

$ java -version
openjdk version "1.8.0_202"
OpenJDK Runtime Environment (build 1.8.0_202-20190206132807.buildslave.jdk8u-src-tar--b08)
OpenJDK GraalVM CE 1.0.0-rc14 (build 25.202-b08-jvmci-0.56, mixed mode)

IDE - IntelliJ IDEA

IntelliJ IDEA 2019.2 (Ultimate Edition)
Build #IU-192.5728.98, built on July 23, 2019

Practice

Requirements

A console app that has the ability to save text information in a JSON file in key-value format when the app is launched. The specifications are the same as in Part 1 except that they were held on-memory, so see below for details. https://qiita.com/sky0621/items/32c87aed41cb1c3c67ff#要件

Total amount of sauce

https://github.com/sky0621/book_java/tree/v0.2.0

Commentary

All source files

Java source Description
Main.java App launch entry point
StoreInfo.java Store to store key-value information(JSON file)Handles information about.
Currently, only "file name" is retained
Commands.java Manages commands such as acquiring, saving, and deleting information from key-value stores.
The effects of increasing or decreasing commands are closed to this source.
Command.java Common interface for each command
SaveCommand.java Responsible for storing key value information.
GetCommand.java Responsible for acquiring value for the specified key.
ListCommand.java Responsible for the acquisition of all key value information.
RemoveCommand.java Responsible for deleting the value for the specified key.
ClearCommand.java Responsible for deleting all key value information.
HelpCommand.java Responsible for displaying help information.
EndCommand.java Responsible for terminating the app.

[Main.java] App launch entry point

[Main.java]


import java.util.Scanner;

public class Main {
    public static void main(String... args) {
        Commands commands = new Commands(new StoreInfo("store.json"));

        System.out.println("Start!");
        while (true) {
            Scanner s = new Scanner(System.in);
            String cmd = s.nextLine();
            commands.exec(cmd.split(" "));
        }
    }
}

[StoreInfo.java] Management of store information

[StoreInfo.java]


import org.apache.commons.lang3.StringUtils;

public class StoreInfo {
    private static final String DEFAULT_STORE_NAME = "store.json";

    private String storeName;

    public StoreInfo(String storeName) {
        if (StringUtils.isEmpty(storeName)) {
            this.storeName = DEFAULT_STORE_NAME;
        } else {
            this.storeName = storeName;
        }
    }

    public String getName() {
        return this.storeName;
    }
}

[Commands.java] Management of each command

[Commands.java]


import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Commands {
    private Map<String, Command> commands;

    public Commands(StoreInfo storeInfo) {
        commands = new HashMap<>();
        commands.put("end", new EndCommand());
        commands.put("help", new HelpCommand());
        commands.put("clear", new ClearCommand(storeInfo));
        commands.put("save", new SaveCommand(storeInfo));
        commands.put("get", new GetCommand(storeInfo));
        commands.put("remove", new RemoveCommand(storeInfo));
        commands.put("list", new ListCommand(storeInfo));

        if (!new File(storeInfo.getName()).exists()) {
            commands.get("clear").exec(null);
        }
    }

    public void exec(String[] cmds) {
        if (cmds == null || cmds.length < 1) {
            System.out.println("no target");
            return;
        }

        List<String> cmdList = Arrays.asList(cmds);
        String[] args = cmdList.subList(1, cmdList.size()).toArray(new String[0]);
        this.commands.get(cmds[0]).exec(args);
    }
}

[Command.java] Parent class for each command

[Command.java]


public interface Command {
    void exec(String[] args);
}

Each command class

For each command, we do the same except that the store information has changed from an on-memory hash to JSON. (So I will omit the explanation.)

■ Save

[SaveCommand.java]


import com.google.gson.Gson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class SaveCommand implements Command {
    private StoreInfo storeInfo;

    public SaveCommand(StoreInfo storeInfo) {
        this.storeInfo = storeInfo;
    }

    @Override
    public void exec(String[] args) {
        if (args == null || args.length != 2) {
            System.out.println("not valid");
            return;
        }

        Gson gson = new Gson();
        Path p = Paths.get(this.storeInfo.getName());
        try {
            Map<String, String> now = gson.fromJson(Files.readAllLines(p).get(0), HashMap.class);
            now.put(args[0], args[1]);
            Files.write(p, gson.toJson(now).getBytes());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

■ Acquired 1 case

[GetCommand.java]


import com.google.gson.Gson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class GetCommand implements Command {
    private StoreInfo storeInfo;

    public GetCommand(StoreInfo storeInfo) {
        this.storeInfo = storeInfo;
    }

    @Override
    public void exec(String[] args) {
        if (args == null || args.length != 1) {
            System.out.println("not valid");
            return;
        }

        Path p = Paths.get(this.storeInfo.getName());
        try {
            Map<String, String> now = new Gson().fromJson(Files.readAllLines(p).get(0), HashMap.class);
            System.out.println(now.get(args[0]));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

■ Acquire all cases

[ListCommand.java]


import com.google.gson.Gson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class ListCommand implements Command {
    private StoreInfo storeInfo;

    public ListCommand(StoreInfo storeInfo) {
        this.storeInfo = storeInfo;
    }

    @Override
    public void exec(String[] args) {
        Path p = Paths.get(this.storeInfo.getName());
        try {
            Map<String, String> now = new Gson().fromJson(Files.readAllLines(p).get(0), HashMap.class);
            System.out.println("\"key\",\"value\"");
            now.forEach((k, v) -> System.out.printf("\"%s\",\"%s\"\n", k, v));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

■ Delete one

[RemoveCommand.java]


import com.google.gson.Gson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class RemoveCommand implements Command {
    private StoreInfo storeInfo;

    public RemoveCommand(StoreInfo storeInfo) {
        this.storeInfo = storeInfo;
    }

    @Override
    public void exec(String[] args) {
        if (args == null || args.length != 1) {
            System.out.println("not valid");
            return;
        }

        Gson gson = new Gson();
        Path p = Paths.get(this.storeInfo.getName());
        try {
            Map<String, String> now = gson.fromJson(Files.readAllLines(p).get(0), HashMap.class);
            now.remove(args[0]);
            Files.write(p, gson.toJson(now).getBytes());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

■ Delete all

[ClearCommand.java]


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ClearCommand implements Command {
    private StoreInfo storeInfo;

    public ClearCommand(StoreInfo storeInfo) {
        this.storeInfo = storeInfo;
    }

    @Override
    public void exec(String[] args) {
        try {
            Files.write(Paths.get(storeInfo.getName()), "{}".getBytes());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

■ Help

[HelpCommand.java]


public class HelpCommand implements Command {
    @Override
    public void exec(String[] args) {
        String msg = "\n" +
                "[usage]\n" +
                "This command manages character string information in key-value format.\n" +
                "The following subcommands are available.\n" +
                "\n" +
                "save   ...Pass the key and value and save.\n" +
                "get    ...Pass the key to display the value.\n" +
                "remove ...Pass the key and delete the value.\n" +
                "list   ...Lists the saved contents.\n" +
                "clear  ...Initializes the saved contents.\n" +
                "help   ...Help information (same as this content) is displayed.\n" +
                "end    ...Exit the app.\n" +
                "\n";
        System.out.println(msg);
    }
}

■ End of application

[EndCommand.java]


public class EndCommand implements Command {
    @Override
    public void exec(String[] args) {
        System.out.println("End!");
        System.exit(-1);
    }
}

Summary

I realized that it was getting more and more messy ...

Recommended Posts

[Improvement] Learn Java through simple tool creation
java file creation
java directory creation
Eclipse ~ Java project creation ~
Arthas Java Diagnostic Tool
Java Discord Bot creation
[Java] Calculator program creation 1