Java tutorial
/** * created by: imustafa created on: Feb 27, 2007 11:28:54 AM $Id: GenUtil.java 2024 2011-05-23 08:21:09Z imustafa $ */ package com.lm.lic.manager.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.RoundingMode; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import java.util.TimeZone; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.util.StringUtils; import com.lm.lic.manager.hibernate.License; import com.lm.lic.manager.hibernate.QuickyProduct; import com.lm.lic.manager.hibernate.User; import com.lm.lic.manager.service.LoginService; /** * @author imustafa */ public class GenUtil extends StringUtils implements GenConst { public static final String CLASS_VERSION = "$Id: GenUtil.java 2024 2011-05-23 08:21:09Z imustafa $"; /** * Hexadecimal characters corresponding to each half byte value. */ private static final char[] HexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** * */ public GenUtil() { } /** * @param str * @return */ public static final String replaceWithEmptyIfNull(String str) { str = StringUtils.hasLength(str) ? str : EMPTY; return str; } /** * When multiple forms are present in a jsp, spring tends to supply values separated by comas ",". Clean them. * * @param prodDefKey * @return */ public static final String cleanUnwantedDuplicateComas(String prodDefKey) { String clean = GenConst.EMPTY; if (StringUtils.hasText(prodDefKey)) { String[] sl = StringUtils.commaDelimitedListToStringArray(prodDefKey); clean = sl[0]; } return clean; } /** * @param request * @param response * @throws ServletException * @throws IOException */ public static void toHell(HttpServletRequest request, HttpServletResponse response, String hellView) throws ServletException, IOException { javax.servlet.RequestDispatcher rd = request.getRequestDispatcher(hellView); rd.forward(request, response); } public static double roundToTwoDecimals(double d) { DecimalFormat twoDecimalFormatter = new DecimalFormat("#.##"); twoDecimalFormatter.setRoundingMode(RoundingMode.DOWN); return Double.valueOf(twoDecimalFormatter.format(d)); } /** * Converts an arbitrary array of bytes to ASCII hexadecimal string form, with two hex characters corresponding to each byte. * The length of the resultant string in characters will be twice the length of the specified array of bytes. * * @param bytes The array of bytes to convert to ASCII hex form. * @return An ASCII hexadecimal numeric string representing the specified array of bytes. */ public static final String toHexString(byte[] bytes) { StringBuffer sb = new StringBuffer(); int i; for (i = 0; i < bytes.length; i++) { sb.append(HexChars[bytes[i] >> 4 & 0xf]); sb.append(HexChars[bytes[i] & 0xf]); } return new String(sb); } /** * @param request */ @SuppressWarnings("unchecked") public static void debugRequestParams(HttpServletRequest request) { Enumeration<String> en = request.getParameterNames(); while (en.hasMoreElements()) { String p = en.nextElement(); String v = request.getParameter(p); System.out.println("\nPARAM: " + p); System.out.println("VALUE: " + v); } en = request.getHeaderNames(); while (en.hasMoreElements()) { String p = en.nextElement(); String v = request.getParameter(p); System.out.println("\nPHEADER: " + p); System.out.println("VALUE: " + v); } String qs = request.getQueryString(); System.out.println("QueryString: " + qs); String method = request.getMethod(); System.out.println("Method: " + method); } public static Date resetClientTimezone(HttpServletRequest request, Date date) { final TimeZone timeZone = TimeZone.getDefault(); final boolean daylight = timeZone.inDaylightTime(date); final Locale locale = request.getLocale(); String tzName = timeZone.getDisplayName(daylight, TimeZone.LONG, locale); // String countryCode = locale.getCountry(); // TimeZone ltz = TimeZone.getTimeZone(countryCode); // TimeZoneNameUtility.getZoneStrings(locale); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.setTimeZone(TimeZone.getTimeZone(tzName)); return cal.getTime(); } public static boolean isAscendingSortOrder(String orderDir) { boolean asc = false; if (orderDir.equals(ASC)) asc = true; return asc; } public static String removeAllOccurancesOfString(String unstripped, String charsToDelete) { String stripped = StringUtils.deleteAny(unstripped, charsToDelete); return stripped; } public static String upperCaseIfHasText(String text) { if (StringUtils.hasText(text)) text = text.toUpperCase(); return text; } /** * @param request * @return */ public static String extractLocaleLang(HttpServletRequest request) { Locale locale = request.getLocale(); String lang = locale.getLanguage(); return lang; } public static Timestamp timeNow() { return new Timestamp(System.currentTimeMillis()); } public static Timestamp timeNowPlusDaysAhead(int daysAhead) { Calendar cal = Calendar.getInstance(); int numDays = daysAhead + cal.get(Calendar.DAY_OF_YEAR); cal.set(Calendar.DAY_OF_YEAR, numDays); Timestamp ts = new Timestamp(cal.getTimeInMillis()); return ts; } /** * @param session */ public static void invalidateSession(HttpSession session) { if (session != null) { session.removeAttribute(GenUtil.LOGGED_IN_ATTRIBUTE); session.invalidate(); } } public static boolean isLoggedin(HttpServletRequest request) { User user = getLoggedinUser(request); boolean loggedin = user != null; return loggedin; } /** * Get the logged in user/role S * * @param request * @return */ public static User getLoggedinUser(ServletRequest request) { HttpServletRequest req = (HttpServletRequest) request; HttpSession session = req.getSession(true); User user = (User) session.getAttribute("user"); return user; } /** * @param mpc * @return */ public static String findLoggedinIsv(HttpServletRequest req, LoginService loginService) { User user = getLoggedinUser(req); String isvId = null; if (user != null) isvId = loginService.findUsertypeRoleId(user); return isvId; } /** * @param mpc * @return */ public static String findLoggedinAdmin(HttpServletRequest req, LoginService loginService) { User user = getLoggedinUser(req); String adminId = null; if (user != null) adminId = loginService.findUsertypeRoleId(user); return adminId; } /** * Extract the requestded uri/ resource in raw form befor the context path was appended to it. * * @param req * @return */ public static String extractRawUri(HttpServletRequest req) { String uri = req.getRequestURI(); String contextPath = req.getContextPath(); if (contextPath == null || contextPath.length() <= 0) return uri; int length = contextPath.length(); uri = uri.substring(length); return uri; } /** * Get the role of the logged in user * * @param request * @return */ public static String findRole(ServletRequest request) { User user = getLoggedinUser(request); String role = user.extractPrimaryRole(); return role; } /** * @param tameName String * @return paddedName String */ public static String padLRWithWhiteSpace(String tameName) { if (tameName == null) tameName = org.apache.commons.lang.StringUtils.EMPTY; String wildName = org.apache.commons.lang.StringUtils.EMPTY + tameName + org.apache.commons.lang.StringUtils.EMPTY; return wildName; } /** * @return */ public String convertStrListToComSep(List<String> extra) { if (extra == null) return GenUtil.EMPTY; StringBuilder extraEmails = new StringBuilder(GenUtil.EMPTY); for (String ex : extra) { extraEmails.append(ex).append(GenUtil.COMA); } return extraEmails.toString(); } /** * @param session */ public static void invalidateSession(LoginService loginService, HttpSession session) { if (session != null) { User user = (User) session.getAttribute("user"); if (user != null) loginService.makeUserLoggedOut(user, session); session.removeAttribute(GenUtil.LOGGED_IN_ATTRIBUTE); session.invalidate(); } } public static void addProductUnderManagement(HttpServletRequest request, String prodId) { HttpSession session = request.getSession(false); session.setAttribute("prodId", prodId); } public static void removeProductUnderManagement(HttpServletRequest request) { HttpSession session = request.getSession(false); session.removeAttribute("prodId"); } /** * @param request * @return */ public static String findProductUnderManagement(HttpServletRequest request) { HttpSession session = request.getSession(); String prodId = (String) session.getAttribute("prodId"); return prodId; } /** * @param first * @param second * @return String */ public static String chooseSecondIfHasText(String first, String second) { String choice = StringUtils.hasText(second) ? second : first; return choice; } public List<String> convertComSepStrToList(String extraEmails) { if (GenUtil.hasLength(extraEmails)) return null; List<String> emails = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(extraEmails, GenUtil.COMA, false); while (st.hasMoreTokens()) { emails.add(st.nextToken()); } return emails; } public static String chooseNotEmptyValue(String oldValue, String newValue) { String realValue = oldValue; if (!hasText(oldValue)) realValue = newValue; return realValue; } public static Object chooseSecondIfFirstIsNull(Object first, Object second) { Object chosen = first; if (first == null) chosen = second; return chosen; } public static String chooseSecondIfFirstIsNullOrEmpty(String first, String second) { String chosen = first; if (!StringUtils.hasText(first)) chosen = second; return chosen; } public static String senseImageFormat(byte[] icon) throws Exception { try { ByteArrayInputStream bais = new ByteArrayInputStream(icon); // Create an image input stream on the image ImageInputStream iis = ImageIO.createImageInputStream(bais); ImageIO.getReaderFormatNames(); // Find all image readers that recognize the image format Iterator<ImageReader> iter = ImageIO.getImageReaders(iis); if (!iter.hasNext()) { return null; } ImageReader reader = iter.next(); iis.close(); return reader.getFormatName(); } catch (IOException e) { } return null; } public static Integer calculateNumLicenses(Double payment, Double ppl) { payment *= 100; // make in pennies since price of licenses is in pennies Double numLics = payment / ppl; if (payment % ppl > 0) // generous numLics += 1; Integer nl = numLics.intValue(); return nl; } public static Double calculateLicensesCost(Integer numLics, Double licPrice) { Double cost = licPrice / 100 * numLics; return cost; } /** * @param extension * @return */ public static String determineMimeType(String extension) { String mimetype = null; if (extension.equals("txt")) { mimetype = "text/plain"; } else if (extension.equals("xml")) { mimetype = "text/xml"; } else if (extension.equals("java")) { mimetype = "text/x-java-source"; } else if (extension.equals("jar")) { mimetype = "application/java-archive"; } else if (extension.equals("tar")) { mimetype = "application/x-tar"; } else if (extension.equals("tar.gz") || extension.equals("tgz")) { mimetype = "application/x-tar-gz"; } else if (extension.equals("pdf")) { mimetype = "application/pdf"; } else if (extension.equals("zip")) { mimetype = "application/zip"; } else { mimetype = "application/octet-stream"; } return mimetype; } /** * Determine file extension * * @param filename * @return */ public static String determineFileType(String filename) { int lastDot = filename.lastIndexOf("."); String fileType = null; if (lastDot >= 0 && lastDot < filename.length() && filename != null) fileType = filename.substring(lastDot + 1); if (fileType == null || fileType.trim().length() == 0) fileType = "none"; return fileType; } public static byte[] extractBytesFromInputStream(InputStream is) throws IOException { long length = is.available(); if (length > Integer.MAX_VALUE) { return null; } byte[] bytes = new byte[(int) length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Malformed file"); } is.close(); return bytes; } /** * @param products * @return */ public static List<String> listIsvProductIds(List<QuickyProduct> products) { List<String> isvProductIds = new ArrayList<String>(products.size()); if (products == null || products.size() == 0) return isvProductIds; for (QuickyProduct p : products) isvProductIds.add(p.getIsvProductId()); return isvProductIds; } /** * @param products * @return */ public static List<String> listproductNames(List<QuickyProduct> products) { List<String> productNames = new ArrayList<String>(products.size()); if (products == null || products.size() == 0) return productNames; for (QuickyProduct p : products) productNames.add(p.getName()); return productNames; } /** * @param lics * @return */ public static String buildFormattedLicenseKeysOneLineEach(List<License> lics) { String keys = EMPTY; StringBuilder sb = new StringBuilder(); if (lics != null && lics.size() > 0) { for (License l : lics) sb.append(l.getLicKey()).append(CRLF).append(HTML_BREAK).append(CRLF); keys = sb.toString(); } return keys; } /** * @param lics * @return */ public static String formulateSpaceSepLicKeys(List<License> lics) { String keys = EMPTY; if (lics != null && lics.size() > 0) { StringBuilder sb = new StringBuilder(); for (License l : lics) sb.append(SPACE).append(l.getLicKey()); keys = sb.toString(); } return keys; } /** * @param lics * @return */ public static String formulateCrlfSepLicKeys(List<License> lics) { String keys = EMPTY; if (lics != null && lics.size() > 0) { StringBuilder sb = new StringBuilder(); for (License l : lics) sb.append(CRLF).append(l.getLicKey()); keys = sb.toString(); } return keys; } /** * @param request * @return */ public static String findDomain(HttpServletRequest request) { String domain = null; String remoteHost = request.getRemoteHost(); try { InetAddress inetAddress = Inet4Address.getByName(remoteHost); domain = inetAddress.getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } return domain; } /** * @param request * @return */ public static String findIpAddress(HttpServletRequest request) { String rip = request.getRemoteAddr(); return rip; } }