Copyright (c) 2014 FeedHenry Ltd, All Rights Reserved.
Please refer to your contract with FeedHenry for the software license agreement.
If you do not have a contract, you do not have a license to use...
If you think the Android project fh-android-sdk listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
package com.feedhenry.sdk.sync;
/*fromwww.java2s.com*/import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.json.fh.JSONArray;
import org.json.fh.JSONException;
import org.json.fh.JSONObject;
publicclass FHSyncUtils {
privatestaticfinalchar[] DIGITS = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
publicstatic JSONArray sortObj(Object pObject) throws Exception {
JSONArray results = new JSONArray();
if (pObject instanceof JSONArray) {
results = new JSONArray();
JSONArray castedObj = (JSONArray) pObject;
for (int i = 0; i < castedObj.length(); i++) {
JSONObject obj = new JSONObject();
obj.put("key", i + "");
Object value = castedObj.get(i);
if (value instanceof JSONObject || value instanceof JSONArray) {
obj.put("value", sortObj(value));
} else {
obj.put("value", value);
}
results.put(obj);
}
} elseif (pObject instanceof JSONObject) {
JSONArray keys = ((JSONObject) pObject).names();
List<String> sortedKeys = sortNames(keys);
for (int i = 0; i < sortedKeys.size(); i++) {
JSONObject obj = new JSONObject();
String key = sortedKeys.get(i);
Object value = ((JSONObject) pObject).get(key);
obj.put("key", sortedKeys.get(i));
if (value instanceof JSONObject || value instanceof JSONArray) {
obj.put("value", sortObj(value));
} else {
obj.put("value", value);
}
results.put(obj);
}
} else {
thrownew Exception("object is not JSONObject or JSONArray");
}
return results;
}
publicstatic String generateObjectHash(Object pObject) {
String hashValue = "";
try {
JSONArray sorted = sortObj(pObject);
hashValue = generateHash(sorted.toString());
} catch (Exception e) {
e.printStackTrace();
}
return hashValue;
}
publicstatic String generateHash(String pText) throws Exception {
String hashValue = null;
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.reset();
md.update(pText.getBytes("ASCII"));
hashValue = encodeHex(md.digest());
return hashValue;
}
privatestatic String encodeHex(byte[] pData) {
int l = pData.length;
char[] out = newchar[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS[(0xF0 & pData[i]) >>> 4];
out[j++] = DIGITS[0x0F & pData[i]];
}
returnnew String(out);
}
privatestatic List<String> sortNames(JSONArray pNames) throws JSONException {
ArrayList<String> names = new ArrayList<String>();
if (null != pNames) {
for (int i = 0; i < pNames.length(); i++) {
names.add(pNames.getString(i));
}
Collections.sort(names);
}
return names;
}
}