/******************************************************************************* * Copyright 2014 Miami-Dade County * * 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.sharegov.cirm.utils; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.net.URL; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import javax.xml.bind.DatatypeConverter; import javax.xml.datatype.DatatypeFactory; import mjson.Json; public class GenUtilsMod { public static final String TIMETASK_NOTRANS_MARKER = "NOTRANS"; private static final ThreadLocal<SimpleDateFormat> ISO_DATE_FORMATS = new ThreadLocal<SimpleDateFormat>(); public static final String isoDatePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; public static String readString(Reader reader) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader b = new BufferedReader(reader); for (String l = b.readLine(); l != null; l = b.readLine()) sb.append(l); return sb.toString(); } public static String serializeAsString(Object x) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(x); out.close(); return DatatypeConverter.printBase64Binary(bos.toByteArray()); } catch (Exception ex) { throw new RuntimeException(ex); } } public static Object deserializeFromString(String x) { try { byte[] A = DatatypeConverter.parseBase64Binary(x); ByteArrayInputStream bin = new ByteArrayInputStream(A); ObjectInputStream in = new ObjectInputStream(bin); return in.readObject(); } catch (Exception t) { throw new RuntimeException(t); } } public static String readTextFile(File f) { try { FileReader reader = new FileReader(f); StringBuilder sb = new StringBuilder(); try { char[] buf = new char[4096]; for (int cnt = reader.read(buf); cnt > -1; cnt = reader.read(buf)) sb.append(buf, 0, cnt); } finally { reader.close(); } return sb.toString(); } catch (IOException ex) { throw new RuntimeException(ex); } } private static volatile boolean dbgLevelTracing = false; public static boolean dbg() { return dbgLevelTracing; } public static void dbg(boolean newdbgLevelTracing) { dbgLevelTracing = newdbgLevelTracing; } public static Json ok() { return Json.object("ok", true); } public static void pagination(Json paginationJson, Json paginationCriteria) { int currentPage = paginationCriteria.at("currentPage").asInteger(); int itemsPerPage = paginationCriteria.at("itemsPerPage").asInteger(); int minValue = ((currentPage - 1) * itemsPerPage) + 1; int maxValue = (minValue - 1) + itemsPerPage; paginationJson.set("minValue", minValue); paginationJson.set("maxValue", maxValue); } public static String trim(String str) { if (str == null || str.equals("null") || str.equals(null)) return "N/A"; else return str.trim(); } public static Json ko(String error) { return Json.object("ok", false, "error", error); } public static byte[] getBytesFromFile(File file) throws IOException { return getBytesFromStream(new FileInputStream(file), true); } // Returns the contents of the file in a byte array. public static byte[] getBytesFromStream(InputStream is, boolean close) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { byte[] A = new byte[4096]; // Read in the bytes for (int cnt = is.read(A); cnt > -1; cnt = is.read(A)) out.write(A, 0, cnt); return out.toByteArray(); // Close the input stream and return bytes } finally { if (close) is.close(); } } /** * Return the string representation of a Json structure that is normalized * so that two Json's will yield the same string representation iff they are * equal. This is done simply by stringify-ing Json objects with the * properties ordered by name. The other Json types already have an * unambiguous unique format. */ public static String normalizeAsString(Json data) { if (!data.isObject()) return data.toString(); StringBuilder sb = new StringBuilder("{"); ArrayList<String> props = new ArrayList<String>(data.asJsonMap() .keySet()); Collections.sort(props); for (int i = 0; i < props.size(); i++) { String p = props.get(i); sb.append("\"" + p + "\":" + normalizeAsString(data.at(p))); if (i < props.size() - 1) sb.append(","); } sb.append("}"); return sb.toString(); } public static String readTextResource(String resource) { InputStream in = GenUtilsMod.class.getResourceAsStream(resource); if (in == null) return null; else try { return new String(getBytesFromStream(in, true)); } catch (IOException e) { throw new RuntimeException(e); } } private static Pattern whiteSpacePattern = Pattern.compile(".*\\s+.*"); public static boolean containsWhiteSpace(String value) { return whiteSpacePattern.matcher(value).matches(); } public static <T> Set<T> set(T... elements) { HashSet<T> S = new HashSet<T>(); for (T x : elements) S.add(x); return S; } private static DatatypeFactory xmlDatatypeFactory; public static java.util.Date parseDate(String s) { try { SimpleDateFormat myDateFormat = ISO_DATE_FORMATS.get(); if (myDateFormat == null) { myDateFormat = new SimpleDateFormat(isoDatePattern); ISO_DATE_FORMATS.set(myDateFormat); } return myDateFormat.parse(s); } catch (ParseException ex) { throw new RuntimeException(ex); } } public static String formatDate(java.util.Date d) { SimpleDateFormat myDateFormat = ISO_DATE_FORMATS.get(); if (myDateFormat == null) { myDateFormat = new SimpleDateFormat(isoDatePattern); ISO_DATE_FORMATS.set(myDateFormat); } return myDateFormat.format(d); } /** * This method returns the timestamp in the given format. * In case of null timestamp and exceptions return "N/A" */ public static String formatDate(Timestamp ts, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); try { if (ts == null) return "N/A"; else return sdf.format(ts); } catch (Exception e) { return "N/A"; } } }