94 lines
2.3 KiB
Java
94 lines
2.3 KiB
Java
package mineplex.serverdata;
|
|
|
|
import redis.clients.jedis.Jedis;
|
|
import redis.clients.jedis.JedisPool;
|
|
import redis.clients.jedis.JedisPoolConfig;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.GsonBuilder;
|
|
|
|
/**
|
|
* Utility offers various necessary utility-based methods for use in Mineplex.ServerData.
|
|
* @author Ty
|
|
*
|
|
*/
|
|
public class Utility
|
|
{
|
|
|
|
// The Gson instance used to serialize/deserialize objects in JSON form.
|
|
private static Gson _gson = new GsonBuilder().create();
|
|
public static Gson getGson() { return _gson; }
|
|
|
|
// Public static jedis pool for interacting with central default jedis repo.
|
|
private static JedisPool _jedisPool;
|
|
|
|
/**
|
|
* @param object - the (non-null) object to serialize
|
|
* @return the serialized form of {@code object}.
|
|
*/
|
|
public static String serialize(Object object)
|
|
{
|
|
return _gson.toJson(object);
|
|
}
|
|
|
|
/**
|
|
* @param serializedData - the serialized data to be deserialized
|
|
* @param type - the resulting class type of the object to be deserialized
|
|
* @return the deserialized form of {@code serializedData} for class {@code type}.
|
|
*/
|
|
public static <T> T deserialize(String serializedData, Class<T> type)
|
|
{
|
|
return _gson.fromJson(serializedData, type);
|
|
}
|
|
|
|
/**
|
|
* @param delimiter - the delimiter character used to separate the concatenated elements
|
|
* @param elements - the set of string elements to be concatenated and returned.
|
|
* @return the concatenated string of all {@code elements} separated by the {@code delimiter}.
|
|
*/
|
|
public static String concatenate(char delimiter, String... elements)
|
|
{
|
|
int length = elements.length;
|
|
String result = length > 0 ? elements[0] : new String();
|
|
|
|
for (int i = 1; i < length; i++)
|
|
{
|
|
result += delimiter + elements[i];
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* @return the current timestamp (in milliseconds) fetched from the central jedis repository
|
|
* for synced timestamps.
|
|
*/
|
|
public static long currentTimeMillis()
|
|
{
|
|
long currentTime = 0;
|
|
Jedis jedis = getPool().getResource();
|
|
|
|
try
|
|
{
|
|
currentTime = Long.parseLong(jedis.time().get(0));
|
|
}
|
|
finally
|
|
{
|
|
getPool().returnResource(jedis);
|
|
}
|
|
|
|
return currentTime;
|
|
}
|
|
|
|
public static JedisPool getPool()
|
|
{
|
|
if (_jedisPool == null)
|
|
{
|
|
_jedisPool = new JedisPool(new JedisPoolConfig(),
|
|
ServerManager.DEFAULT_REDIS_HOST, ServerManager.DEFAULT_REDIS_PORT);
|
|
}
|
|
|
|
return _jedisPool;
|
|
}
|
|
}
|