Java tutorial
package com.webbfontaine.valuewebb.action.rimm; import com.webbfontaine.valuewebb.authentication.UserProperties; import com.webbfontaine.valuewebb.model.Company; import com.webbfontaine.valuewebb.model.MPRates; import com.webbfontaine.valuewebb.model.TtGen; import com.webbfontaine.valuewebb.model.constants.Constants; import com.webbfontaine.valuewebb.model.enums.TransportMode; import com.webbfontaine.valuewebb.model.rimm.*; import com.webbfontaine.valuewebb.model.util.DBUtils; import com.webbfontaine.valuewebb.model.util.Utils; import com.webbfontaine.valuewebb.props.ApplicationProperties; import com.webbfontaine.valuewebb.search.FinderState; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; 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.intercept.BypassInterceptors; import org.jboss.seam.log.Log; import org.jboss.seam.log.Logging; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.faces.model.SelectItem; import javax.persistence.NoResultException; import javax.persistence.Query; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.*; import static com.webbfontaine.valuewebb.action.fcvr.ColorConstants.*; /** * Copyrights 2002-2009 Webb Fontaine * Developer: Grisha Arzumanyan * Date: Oct 30, 2009 * This software is the proprietary information of Webb Fontaine. * Its use is subject to License terms. */ @Name("refSelect") @BypassInterceptors public class RefSelect implements Serializable, Constants { private static final long serialVersionUID = 1L; private static final Log LOGGER = Logging.getLog(RefSelect.class); @Factory(value = "selectYears", scope = ScopeType.EVENT) public List<SelectItem> selectYears() { List<SelectItem> items = new ArrayList(); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int year = calendar.get(Calendar.YEAR); for (int i = 2010; i <= year; ++i) { items.add(new SelectItem("" + i)); } return items; } @Factory(value = "selectMonths", scope = ScopeType.EVENT) public List<SelectItem> selectMonths() { List<SelectItem> items = new ArrayList(12); items.add(new SelectItem("01", "01 - " + Utils.translate("January"))); items.add(new SelectItem("02", "02 - " + Utils.translate("February"))); items.add(new SelectItem("03", "03 - " + Utils.translate("March"))); items.add(new SelectItem("04", "04 - " + Utils.translate("April"))); items.add(new SelectItem("05", "05 - " + Utils.translate("May"))); items.add(new SelectItem("06", "06 - " + Utils.translate("June"))); items.add(new SelectItem("07", "07 - " + Utils.translate("July"))); items.add(new SelectItem("08", "08 - " + Utils.translate("August"))); items.add(new SelectItem("09", "09 - " + Utils.translate("September"))); items.add(new SelectItem("10", "10 - " + Utils.translate("October"))); items.add(new SelectItem("11", "11 - " + Utils.translate("November"))); items.add(new SelectItem("12", "12 - " + Utils.translate("December"))); return items; } public List<SelectItem> getSelectivityColors() { List<SelectItem> selectivityColors = new ArrayList(9); selectivityColors.add(new SelectItem("")); if (GH.equals(Utils.getAppCountry())) { selectivityColors.add(new SelectItem(GREEN, Utils.translate(GREEN))); selectivityColors.add(new SelectItem(BLUE, Utils.translate(BLUE))); selectivityColors.add(new SelectItem(YELLOW_CEPS, Utils.translate(YELLOW_CEPS))); selectivityColors.add(new SelectItem(YELLOW_SCANNING, Utils.translate(YELLOW_SCANNING))); selectivityColors.add(new SelectItem(RED_CEPS, Utils.translate(RED_CEPS))); selectivityColors.add(new SelectItem(RED_GSB, Utils.translate(RED_GSB))); selectivityColors.add(new SelectItem(RED_GSB_FDB, Utils.translate(RED_GSB_FDB))); selectivityColors.add(new SelectItem(RED_FDB, Utils.translate(RED_FDB))); } else { selectivityColors .add(new SelectItem(RED_PHYSICAL_INSPECTION, Utils.translate(RED_PHYSICAL_INSPECTION))); } return selectivityColors; } public List<SelectItem> getContainerSize() { List<SelectItem> containerSize = new ArrayList(5); containerSize.add(new SelectItem("NOT STATED", Utils.translate("NOT STATED"))); containerSize.add(new SelectItem("10'")); containerSize.add(new SelectItem("20'")); containerSize.add(new SelectItem("40'")); containerSize.add(new SelectItem("45'")); return containerSize; } public List<SelectItem> getYesNoUndefined() { List<SelectItem> yesNoUndefined = new ArrayList(3); yesNoUndefined.add(new SelectItem("")); yesNoUndefined.add(new SelectItem("Yes", Utils.translate("Yes"))); yesNoUndefined.add(new SelectItem("No", Utils.translate("No"))); return yesNoUndefined; } @Factory(value = "refSelectYesNo", scope = ScopeType.EVENT) public List<SelectItem> getYesNoCepsUndefined() { List<SelectItem> yesNoCepsUndefined = new ArrayList(4); yesNoCepsUndefined.add(new SelectItem("")); if (GH.equals(Utils.getAppCountry())) { yesNoCepsUndefined.add(new SelectItem("0", "0 - " + Utils.translate("No"))); yesNoCepsUndefined.add(new SelectItem("1", "1 - " + Utils.translate("Yes"))); yesNoCepsUndefined.add(new SelectItem("2", "2 - " + Utils.translate("CEPS"))); } else { yesNoCepsUndefined.add(new SelectItem("0", "0 - " + Utils.translate("QUAP"))); yesNoCepsUndefined.add(new SelectItem("1", "1 - " + Utils.translate("QUAG"))); } return yesNoCepsUndefined; } public List<SelectItem> getFullPartialUndefined() { List<SelectItem> fullPartialUndefined = new ArrayList(3); fullPartialUndefined.add(new SelectItem(null, "")); fullPartialUndefined.add(new SelectItem(Boolean.TRUE, Utils.translate("Partial"))); fullPartialUndefined.add(new SelectItem(Boolean.FALSE, Utils.translate("Full"))); return fullPartialUndefined; } @Factory(value = "refSelectSource", scope = ScopeType.EVENT) public List<SelectItem> getSource() { List<SelectItem> sourceItems = new ArrayList(15); sourceItems.add(new SelectItem("")); sourceItems.add(new SelectItem("BDT01", Utils.translate("BDT01") + " - " + Utils.translate("Base on Data of previous transactions of exporter and importer"))); sourceItems.add(new SelectItem("BDT02", Utils.translate("BDT02") + " - " + Utils.translate("Base on Data of previous transaction of Identical goods with in 90 days"))); sourceItems.add(new SelectItem("BDT03", Utils.translate("BDT03") + " - " + Utils.translate("Base on data of previous transaction of Similar goods with in 90 days"))); sourceItems.add(new SelectItem("BDT04", Utils.translate("BDT04") + " - " + Utils.translate("Base on data of previous transaction of Identical goods of more than 90 days"))); sourceItems.add(new SelectItem("BDT05", Utils.translate("BDT05") + " - " + Utils.translate("Base on data of previous transaction of similar goods of more than 90 days"))); sourceItems.add(new SelectItem("BDT06", Utils.translate("BDT06") + " - " + Utils.translate( "Base on data of previous transaction of Identical goods from other importing country"))); sourceItems.add(new SelectItem("BDT07", Utils.translate("BDT07") + " - " + Utils .translate("Base on data of previous transaction of Similar goods from other importing country"))); sourceItems.add( new SelectItem("NTD", Utils.translate("NTD") + " - " + Utils.translate("Non Transactional Data"))); sourceItems.add(new SelectItem("BWF01", Utils.translate("BWF01") + " - " + Utils.translate("Base on Webb Fontaine Compiled Price Research from Exporter"))); sourceItems.add(new SelectItem("BWF02", Utils.translate("BWF02") + " - " + Utils .translate("Base on Webb Fontaine Compiled Price Research of Identical goods with in 90 days"))); sourceItems.add(new SelectItem("BWF03", Utils.translate("BWF03") + " - " + Utils .translate("Base on Webb Fontaine Compiled Price Research of Similar goods with in 90 days"))); sourceItems.add(new SelectItem("BWF04", Utils.translate("BWF04") + " - " + Utils .translate("Base on Webb Fontaine Compiled Price Research of Identical goods more than 90 days"))); sourceItems.add(new SelectItem("BWF05", Utils.translate("BWF05") + " - " + Utils .translate("Base on Webb Fontaine Compiled Price Research of Similar goods more than 90 days"))); sourceItems.add(new SelectItem("BIP", Utils.translate("BIP") + " - " + Utils.translate("Base on Internet Price Research(webpage should be included)"))); return sourceItems; } public String getDscByCode(String code, String refName) { List<SelectItem> refList = selectReferenceData(refName); return getDscOfHardcodedRef(code, refList); } public static String getDscOfHardcodedRef(String code, List<SelectItem> list) { for (int i = 0; i < list.size(); i++) { SelectItem selectItem = list.get(i); if (selectItem.getValue().equals(code)) { return selectItem.getLabel(); } } return null; } @Factory(value = "selectTradeLevel", scope = ScopeType.EVENT) public List<SelectItem> selectTradeLevel() { return selectReferenceDataForCachedEntities("TradeLevel", false, false, false, null); } @Factory(value = "selectPriceRating", scope = ScopeType.EVENT) public List<SelectItem> selectPriceRating() { return selectReferenceDataForCachedEntities("PriceRating", true, false, true, cod); } public List<SelectItem> getCountryOfSupply() { List retval; if (GH.equals(ApplicationProperties.getAppCountry())) { List countryOfSupplyItems = new ArrayList(30); countryOfSupplyItems.add(new SelectItem("")); countryOfSupplyItems .add(new SelectItem("BF", Utils.translate("BF") + " - " + Utils.translate("Burkina Faso"))); countryOfSupplyItems .add(new SelectItem("CA", Utils.translate("CA") + " - " + Utils.translate("Canada"))); countryOfSupplyItems .add(new SelectItem("CH", Utils.translate("CH") + " - " + Utils.translate("Switzerland"))); countryOfSupplyItems .add(new SelectItem("CK", Utils.translate("CK") + " - " + Utils.translate("Cook Islands"))); countryOfSupplyItems .add(new SelectItem("CZ", Utils.translate("CZ") + " - " + Utils.translate("Czech Republic"))); countryOfSupplyItems .add(new SelectItem("DK", Utils.translate("DK") + " - " + Utils.translate("Denmark"))); countryOfSupplyItems .add(new SelectItem("EG", Utils.translate("EG") + " - " + Utils.translate("Egypt"))); countryOfSupplyItems .add(new SelectItem("ES", Utils.translate("ES") + " - " + Utils.translate("Spain"))); countryOfSupplyItems .add(new SelectItem("ET", Utils.translate("ET") + " - " + Utils.translate("Ethiopia"))); countryOfSupplyItems .add(new SelectItem("FO", Utils.translate("FO") + " - " + Utils.translate("Faroe Islands"))); countryOfSupplyItems .add(new SelectItem("GM", Utils.translate("GM") + " - " + Utils.translate("Gambia"))); countryOfSupplyItems .add(new SelectItem("HU", Utils.translate("HU") + " - " + Utils.translate("Hungary"))); countryOfSupplyItems .add(new SelectItem("IE", Utils.translate("IE") + " - " + Utils.translate("Ireland"))); countryOfSupplyItems .add(new SelectItem("KE", Utils.translate("KE") + " - " + Utils.translate("Kenya"))); countryOfSupplyItems.add(new SelectItem("KP", Utils.translate("KP") + " - " + Utils.translate("Korea, Democratic People's Republic of"))); countryOfSupplyItems .add(new SelectItem("KW", Utils.translate("KW") + " - " + Utils.translate("Kuwait"))); countryOfSupplyItems .add(new SelectItem("LK", Utils.translate("LK") + " - " + Utils.translate("Sri Lanka"))); countryOfSupplyItems .add(new SelectItem("MA", Utils.translate("MA") + " - " + Utils.translate("Morocco"))); countryOfSupplyItems.add(new SelectItem("ML", Utils.translate("ML") + " - " + Utils.translate("Mali"))); countryOfSupplyItems .add(new SelectItem("NG", Utils.translate("NG") + " - " + Utils.translate("Nigeria"))); countryOfSupplyItems .add(new SelectItem("NZ", Utils.translate("NZ") + " - " + Utils.translate("New Zealand"))); countryOfSupplyItems.add(new SelectItem("PE", Utils.translate("PE") + " - " + Utils.translate("Peru"))); countryOfSupplyItems .add(new SelectItem("PY", Utils.translate("PY") + " - " + Utils.translate("Paraguay"))); countryOfSupplyItems .add(new SelectItem("QA", Utils.translate("QA") + " - " + Utils.translate("Qatar"))); countryOfSupplyItems .add(new SelectItem("SE", Utils.translate("SE") + " - " + Utils.translate("Sweden"))); countryOfSupplyItems .add(new SelectItem("SN", Utils.translate("SN") + " - " + Utils.translate("Senegal"))); countryOfSupplyItems .add(new SelectItem("VN", Utils.translate("VN") + " - " + Utils.translate("Vietnam"))); countryOfSupplyItems .add(new SelectItem("ZM", Utils.translate("ZM") + " - " + Utils.translate("Zambia"))); retval = countryOfSupplyItems; } else { retval = selectCountry(); } return retval; } @Factory(value = "selectPortOfDischarge", scope = ScopeType.EVENT) public List<SelectItem> getPortsOfDischarge() { List portsOfDischarge = new ArrayList(); portsOfDischarge.add(new SelectItem("")); if (GH.equals(Utils.getAppCountry())) { List<RimmPort> portsOfDischargeForGH = Utils.createDirectNamedQuery("getPortOfDischargeForGH") .getResultList(); for (RimmPort portOfDischarge : portsOfDischargeForGH) { portsOfDischarge .add(new SelectItem(portOfDischarge.getCod(), Utils.translate(portOfDischarge.getCod()) + " - " + Utils.translate(portOfDischarge.getDscFr()))); } } else { List<String> portsOfDischargeForCI = Utils.createDirectNamedQuery("getPortOfDischargeForCI") .getResultList(); for (String portOfDischarge : portsOfDischargeForCI) { portsOfDischarge.add(new SelectItem(portOfDischarge)); } } return portsOfDischarge; } @Factory(value = "refSelectValuationMethod", scope = ScopeType.EVENT) public List<SelectItem> getValuationMethod() { List<SelectItem> valuationMethodItems = new ArrayList(7); valuationMethodItems.add(new SelectItem("")); valuationMethodItems .add(new SelectItem("1", "1 - " + Utils.translate("Transaction Value of the Imported Goods"))); valuationMethodItems .add(new SelectItem("2", "2 - " + Utils.translate("Transaction Value of Identical Goods"))); valuationMethodItems.add(new SelectItem("3", "3 - " + Utils.translate("Transaction of Similar Goods"))); valuationMethodItems.add(new SelectItem("4", "4 - " + Utils.translate("Deductive method"))); valuationMethodItems.add(new SelectItem("5", "5 - " + Utils.translate("Computed Value"))); valuationMethodItems.add(new SelectItem("6", "6 - " + Utils.translate("Fallback method"))); return valuationMethodItems; } public List getValuationMethodForMP() { List valuationMethodItemsForMP = new ArrayList<>(5); valuationMethodItemsForMP.add(new SelectItem("")); valuationMethodItemsForMP.add(new SelectItem("4", "4 - " + Utils.translate("Deductive method"))); valuationMethodItemsForMP.add(new SelectItem("6", "6 - " + Utils.translate("Fallback method"))); valuationMethodItemsForMP.add(new SelectItem("V", "V - " + Utils.translate("FOB Other"))); valuationMethodItemsForMP.add(new SelectItem("X", "X - " + Utils.translate("Retail Other"))); return valuationMethodItemsForMP; } public List getCriteriaAction() { List criteriaAction = new ArrayList(2); criteriaAction.add(new SelectItem("MAIL ACTION", Utils.translate("MAIL ACTION"))); criteriaAction.add(new SelectItem("SMS ACTION", Utils.translate("SMS ACTION"))); return criteriaAction; } public List getRuleType() { List ruleType = new ArrayList(3); ruleType.add(new SelectItem("")); ruleType.add(new SelectItem("Global Level", Utils.translate("Global Level"))); ruleType.add(new SelectItem("Item Level", Utils.translate("Item Level"))); return ruleType; } public List<SelectItem> getRuleRank() { List ruleRank = new ArrayList(21); ruleRank.add(new SelectItem(null)); for (int i = 1; i <= 20; i++) { ruleRank.add(new SelectItem(i)); } return ruleRank; } public RimmTar hsCodeToTar(String cod) { if (StringUtils.isEmpty(cod)) { return null; } return Utils.getEntityManager().find(RimmTar.class, cod); } public List<SelectItem> selectSourceOfPrice() { return selectReferenceDataForCachedEntities("SourceOfPrice", true, false, false, cod); } public List<SelectItem> selectSourceRating() { return selectReferenceDataForCachedEntities("SourceRating", true, false, true, cod); } @Factory(value = "selectGHPorts", scope = ScopeType.EVENT) public List<SelectItem> selectGHPorts() { List<SelectItem> ports = selectReferenceDataForCachedEntities("RimmPort", true, false, false, dsc); List<SelectItem> ghPorts = new ArrayList<SelectItem>(); ghPorts.add(new SelectItem("ALL", Utils.translate("ALL"))); ghPorts.add(new SelectItem("GHTEM", "Tema")); ghPorts.add(new SelectItem("GHTKD", "Takoradi")); for (SelectItem port : ports) { if (port.getValue().toString().startsWith(GH) && !port.getValue().toString().equals("GHTEM") && !port.getValue().toString().equals("GHTKD")) { ghPorts.add(port); } } return ghPorts; } @Factory(value = "selectRimmDocType", scope = ScopeType.EVENT) public List<SelectItem> selectRimmDocType() { return selectReferenceDataForCachedEntities("RimmDocType", true, true, false, dsc); } @Factory(value = "selectCountry", scope = ScopeType.EVENT) public List<SelectItem> selectCountry() { return selectReferenceDataForCachedEntities("Country", true, false, true, cod); } @Factory(value = "selectCurrency", scope = ScopeType.EVENT) public List<SelectItem> selectCurrency() { return selectReferenceDataForCachedEntities("Currency", false, false, false, cod); } @Factory(value = "selectRimmMot", scope = ScopeType.EVENT) public List<SelectItem> selectRimmMot() { return selectReferenceDataForCachedEntities("RimmMot", true, false, false, dsc); } @Factory(value = "selectRimmMotWithoutEmptyLine", scope = ScopeType.EVENT) public List<SelectItem> selectRimmMotWithoutEmptyLine() { List<SelectItem> rimmMots = selectReferenceDataForCachedEntities("RimmMot", true, false, false, dsc); rimmMots.remove(0); // todo: looks like better not to return empty option by Factories and let h:select add it if needed (nig) return rimmMots; } @Factory(value = "selectCountryOfSupplyWithoutEmptyLine", scope = ScopeType.EVENT) public List<SelectItem> selectCountryOfSupplyWithoutEmptyLine() { List<SelectItem> countryOfSupplyList = getCountryOfSupply(); countryOfSupplyList.remove(0); // todo: looks like better not to return empty option by Factories and let h:select add it if needed (nig) return countryOfSupplyList; } @Factory(value = "selectCtnType", scope = ScopeType.EVENT) public List<SelectItem> selectCtnType() { return selectReferenceDataForCachedEntities("RimmCtn", true, true, false, dsc); } @Factory(value = "selectCtnSize", scope = ScopeType.EVENT) public List<SelectItem> selectCtnSize() { List<SelectItem> items = new ArrayList<SelectItem>(); items.add(new SelectItem("", "")); items.add(new SelectItem("NOT STATED", Utils.translate("NOT STATED"))); items.add(new SelectItem("10'")); items.add(new SelectItem("20'")); items.add(new SelectItem("40'")); items.add(new SelectItem("45'")); return items; } @Factory(value = "selectRimmValop", scope = ScopeType.EVENT) public List<SelectItem> selectRimmValop() { return selectReferenceDataForCachedEntities("RimmValop", true, false, true, cod); } @Factory(value = "selectRimmIncoterm", scope = ScopeType.EVENT) public List<SelectItem> selectRimmIncoterm() { return selectReferenceDataForCachedEntities("RimmIncoterm", false, false, false, cod); } @Factory(value = "selectRimmMop", scope = ScopeType.EVENT) public List<SelectItem> selectRimmMop() { return selectReferenceDataForCachedEntities("RimmMop", true, false, false, dsc); } @Factory(value = "selectRimmUnit", scope = ScopeType.EVENT) public List<SelectItem> selectRimmUnit() { return selectReferenceDataForCachedEntities("RimmUnit", false, false, true, cod); } @Factory(value = "selectFoundRimmUnit", scope = ScopeType.EVENT) public List<SelectItem> selectFoundRimmUnit() { String sql = "select cod from RIMM_UNIT where fd = 'F' order by cod"; Query query = Utils.getEntityManager().createNativeQuery(sql); List refs = query.getResultList(); List<SelectItem> items = new ArrayList<SelectItem>(); items.add(new SelectItem("", "")); for (Object ref : refs) { SelectItem item; item = new SelectItem(ref, ref.toString()); items.add(item); } return items; } public static String getDataForGcnet(String findWhat, String from, String key, String keyValue) { Connection connection = Utils.getSQLConnection(); ResultSet rs = null; PreparedStatement preparedStatement = null; try { String sql = "select " + findWhat + " from " + from + " where " + key + " = ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, keyValue); rs = preparedStatement.executeQuery(); if (rs.next()) { return rs.getString(findWhat); } } catch (SQLException e) { LOGGER.error(e, ""); } finally { DBUtils.closeResources(rs, preparedStatement, connection); } return null; } @Factory(value = "selectRimmPack", scope = ScopeType.EVENT) public List<SelectItem> selectRimmPack() { return selectReferenceDataForCachedEntities("RimmPack", true, false, true, cod); } @Factory(value = "selectT001Manufacturer", scope = ScopeType.EVENT) public List<SelectItem> selectT001Manufacturer() { FinderState finderState = FinderState.getInstance(); if (finderState != null && finderState.isT001ManufacturerActive()) { return selectRefData("T001Manufacturer", true, false, false, dsc); } else { return null; } } @Factory(value = "selectT002Manufacturer", scope = ScopeType.EVENT) public List<SelectItem> selectT002Manufacturer() { FinderState finderState = FinderState.getInstance(); if (finderState != null && finderState.isT002ManufacturerActive()) { return selectRefData("T002Manufacturer", true, false, false, dsc); } else { return null; } } @Factory(value = "selectT001Brand", scope = ScopeType.EVENT) public List<SelectItem> selectT001Brand() { FinderState finderState = FinderState.getInstance(); if (finderState != null && finderState.isT001BrandActive()) { return selectRefData("T001Brand", true, false, false, dsc); } else { return null; } } @Factory(value = "selectT002Brand", scope = ScopeType.EVENT) public List<SelectItem> selectT002Brand() { FinderState finderState = FinderState.getInstance(); if (finderState != null && finderState.isT002BrandActive()) { return selectRefData("T002Brand", true, false, false, dsc); } else { return null; } } /** * @param refName name of ref Class * @param retrieveDsc true: description is shown, see <code>showCodWithDsc</code> parameter also * @param sortColumn cod/dsc * @param storeDsc should description be saved instead of code? * @param showCodWithDsc true: user sees cod and desription with separator, 'false': only description. <code>retrieveDsc</code> should be true for this. * @return content for combo */ public List<SelectItem> selectRefData(String refName, boolean retrieveDsc, boolean storeDsc, boolean showCodWithDsc, String sortColumn) { return selectRefData(refName, retrieveDsc, storeDsc, showCodWithDsc, sortColumn, false); } /** * Note, that result data is cached! So better not to call this method if big result is expected. * <p/> * "...if you query for entities and decide to enable caching, make sure you also ENABLED regular second-level * caching for these entities..." (Java Persistence With Hibernate, Revised Edition of Hibernate In Action) * * @see #selectRefData(String, boolean, boolean, boolean, String) */ public List<SelectItem> selectReferenceDataForCachedEntities(String refName, boolean retrieveDsc, boolean storeDsc, boolean showCodWithDsc, String sortColumn) { return selectRefData(refName, retrieveDsc, storeDsc, showCodWithDsc, sortColumn, true); } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) List<SelectItem> selectRefData(String refName, boolean retrieveDsc, boolean storeDsc, boolean showCodWithDsc, String sortColumn, boolean isCacheEnabled) { List refs = selectRefData(refName, retrieveDsc, sortColumn, isCacheEnabled); List<SelectItem> items = new ArrayList(); items.add(new SelectItem("")); for (Object ref : refs) { SelectItem item; if (retrieveDsc) { String cod = (String) ((Object[]) ref)[0]; String dsc = (String) ((Object[]) ref)[1]; String dscLocale; if (FR.equals(Utils.getLanguage())) { dscLocale = (String) ((Object[]) ref)[2]; if (dscLocale == null) { LOGGER.warn( "French translation is not set for ref {0}, value {1}. Will try to translate then english value would be used.", refName, ((Object[]) ref)[0]); dscLocale = Utils.translate(dsc); } } else { dscLocale = enToEnTranslationRequired(refName) ? Utils.translate(dsc) : dsc; } String itemLabel = showCodWithDsc ? cod + " - " + dscLocale : dscLocale; String itemValue = storeDsc ? dsc : cod; item = new SelectItem(itemValue, itemLabel); } else { item = new SelectItem(ref, Utils.translate(ref.toString())); } items.add(item); } return items; } private static boolean enToEnTranslationRequired(String refName) { return Utils.getAppCountry().equals(CI) && "RimmDocType".equals(refName); } public List selectRefData(String refName, boolean retrieveDsc, String sortColumn, boolean isCacheEnabled) { String sql = "select ref.cod " + (retrieveDsc ? ", ref.dsc, ref.dscFr " : "") + " from " + refName + " ref "; if (sortColumn != null) { sql += " order by ref." + sortColumn; } Query query = Utils.getEntityManager().createQuery(sql); if (isCacheEnabled) { query.setHint("org.hibernate.cacheable", true); } return query.getResultList(); } public List<SelectItem> selectReferenceData(String refName) { if (refName.equals("Currency") || refName.equals("RimmUnit") || refName.equals("RimmIncoterm")) { return selectRefData(refName, false, false, false, cod); } if (refName.equals("RimmValop")) { return selectRefData(refName, true, false, true, cod); } if (refName.equals("RimmMop") || refName.equals("RimmMot") || refName.equals("RimmDocType")) { return selectRefData(refName, true, false, false, dsc); } if (isRimmTable(refName)) { return selectRefData(refName, true, false, true, dsc); } return selectRefData(refName, true, false, false, dsc); } private boolean isRimmTable(String name) { return (name.equals("Country") || name.equals("Currency") || name.startsWith("Rimm")); } public String getRefDsc(String refQuery, String cod, Boolean isCodeWithDescription) { if (cod == null || cod.equals("")) { return ""; } Query query = Utils.getEntityManager().createNamedQuery(refQuery); // query.setHint("org.hibernate.cacheable", true); //this is already set in orm.xml query.setParameter("cod", cod); try { if (FR.equals(Utils.getLanguage())) { return isCodeWithDescription ? cod + " - " + ((RefEntry) query.getSingleResult()).getDscFr() : ((RefEntry) query.getSingleResult()).getDscFr(); } else { return isCodeWithDescription ? cod + " - " + ((RefEntry) query.getSingleResult()).getDsc() : ((RefEntry) query.getSingleResult()).getDsc(); } } catch (NoResultException e) { LOGGER.warn("No entry found for ref '#0' with given code '#1'", e, refQuery, cod); } catch (Exception e) { LOGGER.error("Error searching ref '#0' for key value '#1'", e, refQuery, cod); } return null; } //see TemplatePanel.java for usage public String getRefDscForTemplate(String refName, String cod) { if (cod == null || cod.equals("")) { return ""; } String sql = "select ref.dsc from " + refName + " ref where ref.cod = :cod"; Query query = Utils.getEntityManager().createQuery(sql); query.setParameter("cod", cod); try { return (String) query.getSingleResult(); } catch (NoResultException e) { LOGGER.warn("No entry found for ref '#0' with given code '#1'", e, refName, cod); } catch (Exception e) { LOGGER.error("Error searching ref '#0' for key value '#1'", e, refName, cod); } return null; } public String getCountryName(String cod) { if (cod == null || cod.equals("")) { return null; } String sql = "select rimmCty from Country rimmCty where rimmCty.cod = :cod"; Query query = Utils.getEntityManager().createQuery(sql); query.setHint("org.hibernate.cacheable", true); query.setParameter("cod", cod); try { Country country = (Country) query.getSingleResult(); return country.getDsc(); } catch (NoResultException e) { LOGGER.warn("No country found with given code '#0'", cod, e); } catch (Exception e) { LOGGER.error("Error searching country '#0'", cod, e); } return null; } /** * Tries to retrieve existed profile from database - by name. * * @param expName name of the company * @return existed profile or null if profile with company's Name does not exist * @throws Exception if malformed company passed to check */ public TtGen retrieveExporter(String expName) throws Exception { List ttGen = Utils.getEntityManager() .createQuery("select ttGen from TtGen ttGen where ttGen.expNam = :nam order by ttGen.id desc") .setParameter("nam", expName).getResultList(); if (ttGen.size() != 0) { return (TtGen) ttGen.get(0); } return null; } public CompanyData loadCompany(CompanyType companyType, String code) { CompanyData company = null; if (!StringUtils.isEmpty(code)) { String beanName; switch (companyType) { case APPLICANT: beanName = Utils.getAppCountry().equals(CI) ? RimmDec.class.getSimpleName() : Company.class.getSimpleName(); break; case IMPORTER: beanName = Company.class.getSimpleName(); break; default: throw new RuntimeException("Unknown Company type: " + companyType); } List companies = selectEntityByTin(beanName, code); if (!companies.isEmpty()) { company = (CompanyData) companies.get(0); } } return company; } public List selectEntityByTin(String refName, Object value) { String sql; sql = "select entity from " + refName + " entity where entity.tin = :tin"; Query query = Utils.createDirectQuery(sql); query.setParameter("tin", value); return query.getResultList(); } /** * Retrieves Rate object for requested currency and date * * @param forDate null means today. Every value is truncated - seconds, minutes, hours are removed. * @param currency requested currency * @return {@link com.webbfontaine.valuewebb.model.rimm.Rate#EMPTY_INSTANCE} object if rate does not exist for currency */ public Rate getRate(Date forDate, String currency) { if (Utils.getNationalCurrencyName().equals(currency)) { return getNationalCurrencyRate(); } if (forDate == null || currency == null) { return Rate.EMPTY_INSTANCE; } Query query = Utils.getEntityManager().createNamedQuery("rateByCurrencyAndDate"); query.setHint("org.hibernate.cacheable", false); query.setParameter("cod", currency); query.setParameter("date", DateUtils.truncate(forDate, Calendar.DAY_OF_MONTH)); try { return (Rate) query.getSingleResult(); } catch (Exception e) { LOGGER.warn("Rate for currency [{0}] couldn't be obtained", currency); } return Rate.EMPTY_INSTANCE; } private static Rate getNationalCurrencyRate() { Rate ghcRate = new Rate(); ghcRate.setCod(Utils.getNationalCurrencyName()); ghcRate.setExch(BigDecimal.ONE); ghcRate.setRef(1); return ghcRate; } public String getTarSupCod(String cod) { if (cod == null || cod.equals("")) { return null; } String sql = "select su1 from RimmTar rimmTar where rimmTar.cod = :cod"; Query query = Utils.getEntityManager().createQuery(sql); query.setParameter("cod", cod); try { return (String) query.getSingleResult(); } catch (NoResultException e) { LOGGER.warn("No tariff found with given code '#0'", cod, e); } catch (Exception e) { LOGGER.error("Error searching tariff '#0'", cod, e); } return null; } public MPRates getMPRates(Date date) { MPRates retVal = null; Query query = Utils.getEntityManager().createNamedQuery("mpratesByDate"); query.setHint("org.hibernate.cacheable", true); query.setParameter("date", date); try { retVal = (MPRates) query.getSingleResult(); } catch (NoResultException e) { LOGGER.warn("No MPRates found with given date '#0'", date, e); } catch (Exception e) { LOGGER.error("Error searching MPRates '#0'", date, e); } return retVal; } public List<RimmTar> autocompleteComm(Object hsCode) { int pos = 2; if (hsCode == null) { hsCode = ""; // otherwise concat will not work } else { pos = hsCode.toString().length(); } String sql = "select rimmTar from RimmTar rimmTar where substr(rimmTar.cod,1,:pos) = :id"; Query query = Utils.getEntityManager().createQuery(sql); query.setParameter("pos", pos); query.setParameter("id", hsCode); return query.getResultList(); } public List<SelectItem> autocompleteIdf(Object idf) { List idfNumbersList = new ArrayList<>(); int pos = 2; if (idf == null) { idf = ""; // otherwise concat will not work } else { pos = idf.toString().length(); } Connection connection = Utils.getSQLConnection(); ResultSet rs = null; PreparedStatement preparedStatement = null; String sql = "select idf_number, idf_date from idf, idf_details where LOADED_DETAILS = 1 and substr(idf_number,1,?) = ? and (used is null or used = 0) and idf.idf_details_id = idf_details.id"; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, pos); preparedStatement.setString(2, idf.toString()); rs = preparedStatement.executeQuery(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); while (rs.next()) { String idfDate = sdf.format(rs.getDate("IDF_DATE")); idfNumbersList.add(new SelectItem(rs.getString("IDF_NUMBER"), idfDate)); } } catch (SQLException e) { LOGGER.error(e, ""); } finally { DBUtils.closeResources(rs, preparedStatement, connection); } return idfNumbersList; } public List autocompleteExpNam(Object exporterName) { int pos = 1; if (exporterName == null) { exporterName = ""; // otherwise concat will not work } else { pos = exporterName.toString().length(); } String sql = "select distinct ttGen.expNam " + "from com.webbfontaine.valuewebb.model.TtGen ttGen where upper(substr(ttGen.expNam,1,:pos)) = :id"; Query query = Utils.getEntityManager().createQuery(sql); query.setParameter("pos", pos); query.setParameter("id", ((String) exporterName).toUpperCase()); return query.getResultList(); } public List autocompleteTradeLevel(Object tradeLevel) { List tradeLevels = selectRefData("TradeLevel", false, null, true); if (tradeLevel != null) { List filteredTradeLevels = new ArrayList(tradeLevels.size()); for (Object filteredTradeLevel : tradeLevels) { if (filteredTradeLevel.toString().startsWith(tradeLevel.toString())) { filteredTradeLevels.add(filteredTradeLevel); } } return filteredTradeLevels; } return tradeLevels; } public List autocompleteCriterion(Object criterionCode) { int pos = 2; if (criterionCode == null) { criterionCode = ""; // otherwise concat will not work } else { pos = criterionCode.toString().length(); } String sql = "select criteria from Criteria criteria where substr(criteria.code,1,:pos) = :id"; Query query = Utils.getEntityManager().createQuery(sql); query.setParameter("pos", pos); query.setParameter("id", criterionCode); return query.getResultList(); } @Factory(value = "applicantTins", scope = ScopeType.EVENT) public List<SelectItem> getTINs() { UserProperties userProperties = (UserProperties) Component.getInstance(UserProperties.class, ScopeType.SESSION, true); if (StringUtils.trimToNull(userProperties.getTIN()) == null) { return Collections.EMPTY_LIST; } String[] tinsStr = userProperties.getTIN().split(","); List<SelectItem> tins = new ArrayList(tinsStr.length + 1); tins.add(new SelectItem("")); for (String tin : tinsStr) { tins.add(new SelectItem(tin)); } return tins; } public List<SopVm> getSourceOfPriceVMCodePairs() { Query query = Utils.getEntityManager().createQuery("select sopVm from SopVm sopVm"); query.setHint("org.hibernate.readOnly", Boolean.TRUE); query.setHint("org.hibernate.cacheable", true); return query.getResultList(); } public List<SelectItem> getVMs(String sourceOfPriceCode) { List<SelectItem> valuationMethods = new ArrayList<SelectItem>(); List<SopVm> listOfSourceOfPriceVMCodes = getSourceOfPriceVMCodePairs(); for (SopVm sopVm : listOfSourceOfPriceVMCodes) { if (sopVm.getSop().equals(sourceOfPriceCode)) { valuationMethods.add(new SelectItem(sopVm.getVm())); } } return valuationMethods; } public List<SopVm> getSopVMs(String sourceOfPriceCode) { List<SopVm> sopVMs = new ArrayList(); List<SopVm> listOfSourceOfPriceVMCodes = getSourceOfPriceVMCodePairs(); for (SopVm sopVm : listOfSourceOfPriceVMCodes) { if (sopVm.getSop().equals(sourceOfPriceCode)) { sopVMs.add(sopVm); } } return sopVMs; } public static RefSelect getInstance() { return (RefSelect) Component.getInstance(RefSelect.class, true); } public static String getCriterionTypeDescription(SelectItem[] criteriaTypes, Integer typeCode) { for (SelectItem criterionType : criteriaTypes) { if (criterionType.getValue().equals(typeCode)) { return criterionType.getLabel(); } } return null; } public List<SelectItem> getInspectionResult() { List<SelectItem> inspectionResult = new ArrayList(5); inspectionResult.add(new SelectItem(Integer.toString(NO_INSP_OR_RES_UNKNOWN), "INSPECTION RESULT: " + Utils.translate("No Inspection or Results Unknown"))); inspectionResult.add(new SelectItem(Integer.toString(INSP_NO_IRREG_DETECTED), "INSPECTION RESULT: " + Utils.translate("Inspection - No Irregularity Detected(Compliant Inspection)"))); inspectionResult.add(new SelectItem(Integer.toString(IID_FOB_2), "INSPECTION RESULT: " + Utils.translate("Inspection - Irregularity Detected - FOB Uplift Value USD25000"))); inspectionResult.add(new SelectItem(Integer.toString(IID_FOB_1), "INSPECTION RESULT: " + Utils.translate( "Inspection - Irregularity Detected - FOB Uplift Value per Transaction USD001 but < USD25000"))); return inspectionResult; } @Factory("modeOfTransports") public List<SelectItem> getModeOfTransports() { List<SelectItem> mots = new ArrayList(5); mots.add(new SelectItem("-1", " ")); for (TransportMode tm : TransportMode.values()) { mots.add(new SelectItem(tm.getId(), tm.toString())); } return mots; } }