Java tutorial
/* Copyright 2014 Wassim Akachi - itmanwuiso.com 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 com.itmanwuiso.checksums.dao; import java.util.Map.Entry; import org.json.simple.JSONObject; import com.itmanwuiso.checksums.HashResult; public class Formatter { @SuppressWarnings("unchecked") public JSONObject resultToJson(HashResult result) { JSONObject back = new JSONObject(); if (null == result) { return back; } back.put("filePath", result.getFilePath()); back.put("fileSize", new Long(result.getFileSize())); JSONObject hashes = new JSONObject(); if (null != result.getHashes() && !result.getHashes().isEmpty()) { for (Entry<String, byte[]> e : result.getHashes().entrySet()) { hashes.put(e.getKey(), bytesToString(e.getValue())); } } back.put("hashes", hashes); return back; } public String byteToString(byte b) { return String.format("%02x", (b & 0xFF)).toUpperCase(); // return String.format("%02x", b).toUpperCase(); } public String bytesToString(byte[] bs) { if (null == bs || bs.length == 0) return ""; StringBuilder string = new StringBuilder(); for (byte b : bs) { string.append(byteToString(b)); } return string.toString(); } public static String byteToStr(byte b) { return String.format("%02x", (b & 0xFF)).toUpperCase(); // return String.format("%02x", b).toUpperCase(); } public static String bytesToStr(byte[] bs) { if (null == bs || bs.length == 0) return ""; StringBuilder string = new StringBuilder(); for (byte b : bs) { string.append(byteToStr(b)); } return string.toString(); } }