org.ScripterRon.BitcoinMonitor.Utils.java Source code

Java tutorial

Introduction

Here is the source code for org.ScripterRon.BitcoinMonitor.Utils.java

Source

/*
 * Copyright 2014 Ronald Hoffman.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.ScripterRon.BitcoinMonitor;

import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Utility methods
 */
public class Utils {

    /** Hex conversion alphabet */
    private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * Parse a hex string and return the decoded bytes
     *
     * @param       hex                     String to parse
     * @return                              Decoded bytes
     * @throws      NumberFormatException   String contains an invalid hex character
     */
    public static byte[] parseHexString(String hex) throws NumberFormatException {
        if ((hex.length() & 0x01) == 1)
            throw new NumberFormatException("Hex string length is not a multiple of 2");
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            int char1 = hex.charAt(i * 2);
            char1 = (char1 > 0x60 ? char1 - 0x57 : char1 - 0x30);
            int char2 = hex.charAt(i * 2 + 1);
            char2 = (char2 > 0x60 ? char2 - 0x57 : char2 - 0x30);
            if (char1 < 0 || char2 < 0 || char1 > 15 || char2 > 15)
                throw new NumberFormatException("Invalid hex number: " + hex);
            bytes[i] = (byte) ((char1 << 4) + char2);
        }
        return bytes;
    }

    /**
     * Convert a byte array to a hex string
     *
     * @param       bytes                   Bytes to encode
     * @return                              Hex string
     */
    public static String toHexString(byte[] bytes) {
        char[] chars = new char[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            chars[i * 2] = hexChars[((bytes[i] >> 4) & 0xF)];
            chars[i * 2 + 1] = hexChars[(bytes[i] & 0xF)];
        }
        return String.valueOf(chars);
    }

    /**
     * Create a formatted string for a JSON response
     *
     * @param       response                The JSON response
     * @return                              Formatted string
     */
    public static String formatJSON(Response response) {
        StringBuilder builder = new StringBuilder(256);
        formatJSON(builder, "", response);
        return new String(builder);
    }

    /**
     * Create a formatted string for a JSON structure
     *
     * @param       builder                 String builder
     * @param       indent                  Output indentation
     * @param       object                  The JSON object
     */
    private static void formatJSON(StringBuilder builder, String indent, JSONAware object) {
        String itemIndent = indent + "  ";
        if (object instanceof JSONArray) {
            JSONArray array = (JSONArray) object;
            builder.append(indent).append("[\n");
            array.stream().forEach((value) -> {
                if (value == null) {
                    builder.append(itemIndent).append("null").append('\n');
                } else if (value instanceof Boolean) {
                    builder.append(itemIndent).append((Boolean) value ? "true\n" : "false\n");
                } else if (value instanceof Long) {
                    builder.append(itemIndent).append(((Long) value).toString()).append('\n');
                } else if (value instanceof Double) {
                    builder.append(itemIndent).append(((Double) value).toString()).append('\n');
                } else if (value instanceof String) {
                    builder.append(itemIndent).append('"').append((String) value).append("\"\n");
                } else if (value instanceof JSONAware) {
                    builder.append('\n');
                    formatJSON(builder, itemIndent + "  ", (JSONAware) value);
                } else {
                    builder.append(itemIndent).append("Unknown\n");
                }
            });
            builder.append(indent).append("]\n");
        } else {
            builder.append(indent).append("{\n");
            JSONObject map = (JSONObject) object;
            Iterator<Map.Entry> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = it.next();
                builder.append(itemIndent).append("\"").append((String) entry.getKey()).append("\": ");
                Object value = entry.getValue();
                if (value == null) {
                    builder.append("null").append('\n');
                } else if (value instanceof Boolean) {
                    builder.append((Boolean) value ? "true\n" : "false\n");
                } else if (value instanceof Long) {
                    builder.append(((Long) value).toString()).append('\n');
                } else if (value instanceof Double) {
                    builder.append(((Double) value).toString()).append('\n');
                } else if (value instanceof String) {
                    builder.append('"').append((String) value).append("\"\n");
                } else if (value instanceof JSONAware) {
                    builder.append('\n');
                    formatJSON(builder, itemIndent + "  ", (JSONAware) value);
                } else {
                    builder.append("Unknown\n");
                }
            }
            builder.append(indent).append("}\n");
        }
    }
}