Java tutorial
package com.webbfontaine.valuewebb.model.util; import com.google.common.base.Throwables; import com.webbfontaine.valuewebb.action.SimpleDocumentHome; import com.webbfontaine.valuewebb.model.Props; import com.webbfontaine.valuewebb.model.TtRisk; import com.webbfontaine.valuewebb.model.constants.Constants; import com.webbfontaine.valuewebb.props.ApplicationProperties; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.hibernate.CacheMode; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Factory; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.intercept.BypassInterceptors; import org.jboss.seam.faces.Redirect; import org.jboss.seam.international.LocaleSelector; import org.jboss.seam.international.Messages; import org.jboss.seam.log.Log; import org.jboss.seam.log.Logging; import org.jboss.seam.util.Naming; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; import javax.servlet.ServletOutputStream; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.sql.*; import java.text.*; import java.util.*; import java.util.Date; import java.util.regex.Pattern; import static com.webbfontaine.valuewebb.model.constants.Constants.*; import static com.webbfontaine.valuewebb.model.constants.Messages.DOCUMENT_IS_LOCKED; import static com.webbfontaine.valuewebb.report.WorkingPeriod.WORKING_MINUTES_IN_ADAY; /** * Copyrights 2002-2010 Webb Fontaine * This software is the proprietary information of Webb Fontaine. * Its use is subject to License terms. * User: nigiyan * Date: Mar 24, 2010 */ @Name("utils") @Scope(ScopeType.APPLICATION) @BypassInterceptors public class Utils { private static final Log LOGGER = Logging.getLog(Utils.class); public static final long MILLIS_IN_DAY = 1000 * 3600 * 24; public static final long MILLIS_IN_HOUR = 1000 * 3600; public static final long MILLIS_IN_MINUTE = 1000 * 60; private static final Pattern UNDERLINE_DELIMITER = Pattern.compile("_"); public static RoundingMode getRoundingMode() { String roundingMode = ApplicationProperties.getRoundingMode(); if ("HALF_UP".equals(roundingMode) || roundingMode == null) { return RoundingMode.HALF_UP; } if ("HALF_DOWN".equals(roundingMode)) { return RoundingMode.HALF_DOWN; } throw new IllegalArgumentException(String.format("Unsupported rounding mode: %s", roundingMode)); } public static BigDecimal divide(BigDecimal dividend, BigDecimal divisor, int scale) { BigDecimal retVal; if (dividend.doubleValue() == 0) { retVal = dividend; } else { if (divisor == null || divisor.doubleValue() == 0) { LOGGER.debug("Division by zero, result will be 'null' !!!"); retVal = null; } else { retVal = dividend.divide(divisor, scale, getRoundingMode()); } } return retVal; } /** * multiplication is done in ordinar way and rounded and scaled after. <br/> * <b>if you're going to multiply and then divide</b> then use BigDecimal.multiply and then Utils.divide since it will round and scale for you. */ public static BigDecimal multiplyWithRS(BigDecimal m1, BigDecimal m2, int scale) { if (m1 == null || m2 == null) { return null; } return m1.multiply(m2).setScale(scale, getRoundingMode()); } public static Date getTomorrowDate() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 1); //For tomorrow return DateUtils.truncate(calendar.getTime(), Calendar.DATE); } @Factory(value = "currentPage", scope = ScopeType.PAGE) public String getCurrentPage() { return FacesContext.getCurrentInstance().getViewRoot().getViewId(); } /** * @return current view id, null if no Faces Context */ public static String currentPage() { String viewId = ""; if (FacesContext.getCurrentInstance() != null) { viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId(); } return viewId; } @Factory(value = "homePage", scope = ScopeType.PAGE) public static Boolean isHomePage() { return FacesContext.getCurrentInstance().getViewRoot().getViewId().contains("home.xhtml"); } public static String fieldToGetter(String field) { String getterName = field.substring(0, 1).toUpperCase() + field.substring(1); return "get" + getterName; } public static String fieldToId(String fieldName, String formName) { /*switch (formName) { case TT_FORM: return TT_FORM + ':' + fieldName; case PD_FORM: return PD_FORM + ':' + fieldName; case CRITERIA_FORM: return CRITERIA_FORM + ':' + fieldName; case TAXATION_RULE_FORM: return TAXATION_RULE_FORM + ':' + fieldName; } if (SPDM_FORM.equals(formName.split("_")[0])) { return formName + ':' + fieldName + '_' + COMPILE.split(formName)[1]; } LOGGER.warn("This field [{0}] does not exist on form [{1}]", fieldName, formName);*/ return null; } public static String getFieldName(String fieldId) { FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot root = context.getViewRoot(); UIComponent uiComponent = findComponent(root, fieldId); String retVal = null; if (uiComponent == null) { LOGGER.debug("There is no component with id {0}", fieldId); } else { String clientId = uiComponent.getClientId(context); if ((retVal = (String) uiComponent.getAttributes().get("title")) == null) { if ((retVal = (String) uiComponent.getAttributes().get("label")) == null) { LOGGER.debug("Name (title or label) for element with id: {0} does not exist", clientId); } } } return retVal; } public static UIComponent findComponent(UIComponent c, String id) { if (id.equals(c.getId()) || id.equals(c.getClientId(FacesContext.getCurrentInstance()))) { return c; } Iterator<UIComponent> kids = c.getFacetsAndChildren(); while (kids.hasNext()) { UIComponent component = findComponent(kids.next(), id); if (component != null) { return component; } } return null; } public static String getColorValue(String color) { if (color != null) { String colorName = color.toLowerCase().split(" ")[0]; if ("green".equals(colorName)) { return "#7cfc00"; } if ("red".equals(colorName)) { return "#ff0000"; } if ("orange".equals(colorName)) { return "#ffA500"; } if ("yellow".equals(colorName)) { return "#ffff00"; } if ("blue".equals(colorName)) { return "#0000ff"; } if ("query".equals(colorName)) { return "#800080"; } } return "#ffffff"; } public static List<TtRisk> sortByColor(List<TtRisk> risks) { return RiskUtils.sortListByColor(risks); } public static int diffDays(Date startDate, Date endDate) { int numberOfDays = 0; Calendar startCalDate = Calendar.getInstance(); Calendar endCalDate = Calendar.getInstance(); startCalDate.setTime(startDate); endCalDate.setTime(endDate); if (startCalDate.get(Calendar.YEAR) == endCalDate.get(Calendar.YEAR)) { return endCalDate.get(Calendar.DAY_OF_YEAR) - startCalDate.get(Calendar.DAY_OF_YEAR) + 1; } for (int i = startCalDate.get(Calendar.YEAR) + 1; i <= (endCalDate.get(Calendar.YEAR) - 1); i++) { numberOfDays += isLeapYear(i) ? 366 : 365; } numberOfDays += daysNumberFromYearBeginning(endCalDate) + daysNumberUntilYearEnd(startCalDate) + 1; return numberOfDays; } public static boolean isLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } public static int daysNumberFromYearBeginning(Calendar cal) { return cal.get(Calendar.DAY_OF_YEAR); } public static String getLastDayOfMonth(String year, String month) { switch (month) { case "01": case "03": case "05": case "07": case "08": case "10": case "12": return "31"; case "04": case "06": case "09": case "11": return "30"; case "02": return isLeapYear(Integer.parseInt(year)) ? "29" : "28"; default: return "00"; } } public static String addOneMonth(String yearMonth) { if (yearMonth.substring(4).equals("12")) { return "" + (Integer.parseInt(yearMonth.substring(0, 4)) + 1) + "01"; } else { return "" + (Integer.parseInt(yearMonth) + 1); } } public static int daysNumberUntilYearEnd(Calendar cal) { int numberOfDaysInYear = isLeapYear(cal.get(Calendar.YEAR)) ? 366 : 365; return numberOfDaysInYear - cal.get(Calendar.DAY_OF_YEAR); } public static void sendBytes(byte[] bytes, String filename, String contentType) { if (bytes != null) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.addHeader("Content-disposition", "attachment; filename=" + filename); response.addHeader("Content-Length", String.valueOf(bytes.length)); ServletOutputStream os = null; try { os = response.getOutputStream(); os.write(bytes); os.flush(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException e) { LOGGER.error("Sending content failed {0}", filename, e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { LOGGER.error("Failed to close stream after sending", e); } } } } } public static BigDecimal getBD(BigDecimal val, BigDecimal defaultVal) { return val == null ? defaultVal : val; } /** * @return 0 if val is null */ public static BigDecimal getBD(BigDecimal val) { return val == null ? BigDecimal.ZERO : val; } public static String[] splitToParts(String str, Integer lenghtOfEachPart, Integer reqParts) { String[] strParts = new String[reqParts]; if ((str = StringUtils.trimToNull(str)) == null) { return strParts; } String[] splitRes = str.split("(?<=\\G.{" + lenghtOfEachPart + "})"); for (int i = 0; i < strParts.length && i < splitRes.length; i++) { strParts[i] = splitRes[i]; } return strParts; } /** * @param string 123;456;7 * @param delimiter e.g. ; * @return '123','456','7' */ public static String stringToStringArray(String string, String delimiter) { String strArray = ""; String[] tins = string.split(delimiter); for (int i = 0; i < tins.length; i++) { strArray += "'" + tins[i] + "'"; if (i != tins.length - 1) { strArray += ","; } } return strArray; } public static String toWords(CharSequence str) { StringBuilder res = new StringBuilder(str.length()); for (int i = 0; i < str.length(); i++) { Character ch = str.charAt(i); if (Character.isUpperCase(ch)) { res.append(' ').append(ch); } else { res.append(ch); } } char c = Character.toUpperCase(res.charAt(0)); res.replace(0, 1, new String(new char[] { c })); return res.toString(); } public static int daysBetween(Date from, Date to) { return (int) ((to.getTime() - from.getTime()) / (1000 * 60 * 60 * 24)); } public static String convertNumberToMonth(String numOfMonth) { if (StringUtils.isEmpty(numOfMonth)) { return ""; } return DateFormatSymbols.getInstance().getMonths()[Integer.parseInt(numOfMonth) - 1]; } public static Connection getSQLConnection(String name) { InitialContext initContext; try { initContext = new InitialContext(); DataSource dataSource = (DataSource) initContext.lookup(name); return dataSource.getConnection(); } catch (NamingException e) { LOGGER.error("", e); } catch (SQLException e) { LOGGER.error("", e); } return null; } public static Connection getSQLConnection() { return getSQLConnection("valuewebbDatasource"); } public static String convertIntegerToString(String number) { if (number.length() < 4) { return number; } else { return convertIntegerToString(number.substring(0, number.length() - 3)) + ',' + number.substring(number.length() - 3); } } public static PropertyDescriptor[] getBeanProperties(Class _class) { try { BeanInfo bi = Introspector.getBeanInfo(_class); return bi.getPropertyDescriptors(); } catch (IntrospectionException e) { LOGGER.error("", e); } return null; } public static boolean isFacesContext() { return FacesContext.getCurrentInstance() != null; } public static List<Object[]> transformToList(ResultSet rs) throws SQLException { ResultSetMetaData rsMetaData = rs.getMetaData(); int numberOfColumns = rsMetaData.getColumnCount(); List<Object[]> result = new ArrayList<>(numberOfColumns); while (rs.next()) { Object[] row = new Object[numberOfColumns]; for (int i = 0; i < numberOfColumns; i++) { if (rsMetaData.getColumnType(i + 1) == Types.TIMESTAMP) { row[i] = rs.getDate(i + 1); } else { row[i] = rs.getObject(i + 1); } } result.add(row); } return result; } public static String getDefaultYear() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int month = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); if (month == 0) { return "" + (year - 1); } else { return "" + year; } } public static String getDefaultMonth() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int month = calendar.get(Calendar.MONTH); if (month == 0) { return "12"; } else { return (month < 10 ? "0" + month : "" + month); } } public static boolean isEditPage() { return isEditPage(FacesContext.getCurrentInstance().getViewRoot().getViewId()); } private static boolean isEditPage(String viewid) { return viewid != null && viewid.toLowerCase().contains("edit"); } public static String getAppCountry() { String applicationCountry = ApplicationProperties.getAppCountry(); if (GH.equals(applicationCountry)) { return GH; } else if (CI.equals(applicationCountry)) { return CI; } LOGGER.warn("Unsupported country: {}", applicationCountry); throw new IllegalArgumentException(String.format("Unsupported country: %s", applicationCountry)); } public static String translate(String string) { return Messages.instance().get(string); } public static String getLanguage() { return LocaleSelector.instance().getLanguage(); } public static String getIdfStringDependsOnCountryVersion() { return CI.equals(getAppCountry()) ? "DAI" : "IDF"; } public static String resolveStyleName(String extension) { String name; switch (StringUtils.trimToEmpty(extension).toLowerCase()) { case "pdf": name = "attDocPDF"; break; case "xls": case "xlsx": name = "attDocSheet"; break; case "doc": case "docx": case "odt": name = "attDocWRD"; break; case "jpg": case "jpeg": case "gif": case "png": name = "attDocIMG"; break; default: name = "attDocDEF"; } return name; } /** * @return FCVR Number prefix for Application country * @throws RuntimeException if Application country is unknown */ public static String getFCVRNumberPrefix() throws RuntimeException { String prefix; if (ApplicationProperties.getAppCountry().equals(GH)) { prefix = "WFG"; } else { if (ApplicationProperties.getAppCountry().equals(CI)) { prefix = "RCS"; } else { throw new RuntimeException("Application country is unknown"); } } return prefix; } public static EntityManager getEntityManager() { return (EntityManager) Component.getInstance("entityManager"); } public static Query createDirectQuery(String sql) { return setDirectRead(getEntityManager().createQuery(sql)); } public static Query createDirectNamedQuery(String sql) { return setDirectRead(getEntityManager().createNamedQuery(sql)); } public static EntityManager createEntityManager() { return getEntityManagerFactory().createEntityManager(); } public static EntityManagerFactory getEntityManagerFactory() { InitialContext context = getInitialContext(); try { return (EntityManagerFactory) context.lookup("java:/ValueWebbEntityManagerFactory"); } catch (NamingException e) { throw Throwables.propagate(e); } } private static InitialContext getInitialContext() { try { return Naming.getInitialContext(); } catch (NamingException e) { throw new RuntimeException(e); } } public static String getNationalCurrencyName() { String nationalCurrencyName = ""; if (ApplicationProperties.getAppCountry().equals(CI)) { nationalCurrencyName = XOF; } else { if (ApplicationProperties.getAppCountry().equals(GH)) { nationalCurrencyName = GHC; } } return nationalCurrencyName; } public static String getFobLabel() { return translate(FOB) + ' ' + getNationalCurrencyName(); } public static String dateToLocaleString(Date date) { String toStringDate; if (date == null) { toStringDate = ""; } else { DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, LocaleSelector.instance().getLocale()); toStringDate = dateFormat.format(date); } return toStringDate; } public static Date localeStringToDate(String date) throws ParseException { if (StringUtils.trimToEmpty(date).isEmpty()) { return null; } DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, LocaleSelector.instance().getLocale()); return dateFormat.parse(date); } public static Query setReadOnlyFlag(Query query, boolean value) { return query.setHint("org.hibernate.readOnly", value); } public static Query setCacheableFlag(Query query, boolean value) { return query.setHint("org.hibernate.cacheable", value); } public static Query setCacheBypass(Query query) { return query.setHint("org.hibernate.cacheMode", CacheMode.IGNORE); } public static Query setDirectRead(Query query) { Query resultQuery = setCacheableFlag(query, false); resultQuery = setCacheBypass(resultQuery); return setReadOnlyFlag(resultQuery, true); } public static String getAsString(Number number, String pattern) { if (number == null) { return ""; } DecimalFormat decimalFormat = (DecimalFormat) NumberFormat .getNumberInstance(LocaleSelector.instance().getLocale()); decimalFormat.applyPattern(pattern); return decimalFormat.format(number); } public static void setLocale(String language) { String notEmptyLanguage = StringUtils.defaultIfEmpty(StringUtils.trimToEmpty(language), EN).replaceAll("'", ""); if (Constants.FR.equals(notEmptyLanguage)) { LocaleSelector.instance().setLocale(Locale.FRENCH); } else { if (Constants.EN.equals(notEmptyLanguage)) { LocaleSelector.instance().setLocale(Locale.ENGLISH); } else { LOGGER.warn("There is no support for locale {0}. English will be set.", notEmptyLanguage); LocaleSelector.instance().setLocale(Locale.ENGLISH); } } } public static String convertProcessingTimeFromLongToString(Long processingTime) { return processingTime / WORKING_MINUTES_IN_ADAY + " " + translate("day(s)") + ", " + processingTime % WORKING_MINUTES_IN_ADAY / 60 + " " + translate("hour(s)") + ", " + processingTime % WORKING_MINUTES_IN_ADAY % 60 + " " + translate("minute(s)"); } public static Calendar setCalendarData(Calendar date, int hour, int minute) { date.set(Calendar.HOUR_OF_DAY, hour); date.set(Calendar.MINUTE, minute); date.set(Calendar.SECOND, 0); date.set(Calendar.MILLISECOND, 0); return date; } public static Props loadProps() { return getEntityManager().find(Props.class, (long) 1); } public static String docIsLockedMessage(String forOperation) { return translate("Operation") + " '" + translate(forOperation) + "' " + translate("is prohibited") + ". " + translate(DOCUMENT_IS_LOCKED); } public static SimpleDocumentHome buildSimpleDocumentHome(final String docName, final Object docId) { return new SimpleDocumentHome() { @Override public Object getRequestedId() { return docId; } @Override public String getDocName() { return docName; } @Override protected boolean validateDocument() { return false; } @Override protected void postValidate() { } @Override public boolean isFieldEditable(String component) { return false; } @Override protected void initDocument() { } @Override protected Object parseId(Object id) { return id; } }; } public static boolean renderInitialCriteriaAddition() { String page = currentPage(); return !(page.contains("PdEdit") || page.contains("SPD")); } public static List emptyCollection() { return Collections.EMPTY_LIST; } public static String getRequestParameter(String name) { FacesContext facesContext = FacesContext.getCurrentInstance(); ServletRequest request = (ServletRequest) facesContext.getExternalContext().getRequest(); return request.getParameter(name); } public static List<String> splitIntoIntervals(int number, int intervalSize) { List<String> pages = new ArrayList<>(number / intervalSize); for (int i = 1; i <= number; i++) { if (i % intervalSize == 0) { pages.add((i - intervalSize) + 1 + "-" + i); } } if (number % intervalSize != 0) { pages.add((number / intervalSize) * intervalSize + 1 + "-" + number); } return pages; } public boolean returnToCapturedView() { Redirect redirect = Redirect.instance(); String viewId = redirect.getViewId(); //return to captured view if non edit page return redirect.getViewId() != null && !isEditPage(viewId) && redirect.returnToCapturedView(); } }