List of usage examples for java.lang Long equals
public boolean equals(Object obj)
From source file:com.viettel.logistic.wms.service.StockGoodsSerialServiceImpl.java
@Override public List<StockGoodsSerialStripDTO> getListStockGoodsSerialStrip(List<ConditionBean> lstCondition, int startRow, int maxRow, String sortType, String sortField) { List<StockGoodsSerialStripDTO> lstStockGoodsSerialStripDTO = new ArrayList<>(); StockGoodsSerialStripDTO stockGoodsSerialStripDTOSearch = new StockGoodsSerialStripDTO(); for (ConditionBean condition : lstCondition) { if (condition.getField().equalsIgnoreCase("fromSerial") && !StringUtils.isNullOrEmpty(condition.getValue())) { stockGoodsSerialStripDTOSearch.setFromSerial(condition.getValue()); }//from w ww .ja v a 2 s . co m // if (condition.getField().equalsIgnoreCase("toSerial") && !StringUtils.isNullOrEmpty(condition.getValue())) { stockGoodsSerialStripDTOSearch.setToSerial(condition.getValue()); } //custId if (condition.getField().equalsIgnoreCase("custId") && !StringUtils.isNullOrEmpty(condition.getValue())) { stockGoodsSerialStripDTOSearch.setCustId(condition.getValue()); } //goodsType if (condition.getField().equalsIgnoreCase("goodsType") && !StringUtils.isNullOrEmpty(condition.getValue())) { stockGoodsSerialStripDTOSearch.setGoodsType(condition.getValue()); } //goodsId if (condition.getField().equalsIgnoreCase("goodsId") && !StringUtils.isNullOrEmpty(condition.getValue())) { stockGoodsSerialStripDTOSearch.setGoodsId(condition.getValue()); } //ownerId if (condition.getField().equalsIgnoreCase("ownerId") && !StringUtils.isNullOrEmpty(condition.getValue())) { stockGoodsSerialStripDTOSearch.setOwnerId(condition.getValue()); } //status if (condition.getField().equalsIgnoreCase("status") && !StringUtils.isNullOrEmpty(condition.getValue())) { stockGoodsSerialStripDTOSearch.setStatus(condition.getValue()); } //status if (condition.getField().equalsIgnoreCase("goodsState") && !StringUtils.isNullOrEmpty(condition.getValue())) { stockGoodsSerialStripDTOSearch.setGoodsState(condition.getValue()); } } List<StockGoodsSerialStripDTO> lstFilterStockGoodsSerialStripDTO = new ArrayList<>(); // for (ConditionBean con : lstCondition) { // if (con.getType().equalsIgnoreCase(ParamUtils.TYPE_DATE)) { // con.setField(StringUtils.formatFunction("trunc", con.getField())); // } else if (con.getType().equalsIgnoreCase(ParamUtils.NUMBER)) { // con.setType(ParamUtils.TYPE_NUMBER); // } else if (con.getType().equalsIgnoreCase(ParamUtils.NUMBER_DOUBLE)) { // con.setType(ParamUtils.NUMBER_DOUBLE); // } else { // String value = ""; // if (con.getOperator().equalsIgnoreCase(ParamUtils.NAME_LIKE)) { // value = StringUtils.formatLike(con.getValue()); // con.setField(StringUtils.formatFunction("lower", con.getField())); // con.setValue(value.toLowerCase()); // } else { // value = con.getValue(); // con.setField(con.getField()); // con.setValue(value); // } // } // con.setOperator(StringUtils.convertTypeOperator(con.getOperator())); // } String fromSerial = ""; String toSerial = ""; Long quantity = 0L; Long quantityTotal = 0L; // ConditionBean removeCondition = new ConditionBean(); // //Lay gia tri from_serial, to_serial truyen vao // for (ConditionBean condition : lstCondition) { // if (condition.getField().equalsIgnoreCase("fromSerial") && !StringUtils.isNullOrEmpty(condition.getValue())) { // toSerial = condition.getValue(); // } // // // if (condition.getField().equalsIgnoreCase("toSerial") && !StringUtils.isNullOrEmpty(condition.getValue())) { // fromSerial = condition.getValue(); // } // // // if (condition.getField().equalsIgnoreCase("quantity") && !StringUtils.isNullOrEmpty(condition.getValue())) { // quantity = Long.parseLong(condition.getValue()); // removeCondition = condition; // } // } // lstCondition.remove(removeCondition); //Tim kiem serial //lstStockGoodsSerialStripDTO = stockGoodsSerialStripBusiness.searchByConditionBean(lstCondition, startRow, maxRow, sortType, sortField); // lstStockGoodsSerialStripDTO = stockGoodsSerialStripBusiness.searchByConditionBean(lstCondition, startRow, maxRow, "", "goodsId, custId,ownerId,ownerType,goodsId,goodsState,status,fromSerial"); lstStockGoodsSerialStripDTO = stockGoodsSerialStripBusiness2 .getListStockGoodsSerialStripExacly(stockGoodsSerialStripDTOSearch); StockGoodsSerialStripDTO firstStockGoodsSerialStripDTO; StockGoodsSerialStripDTO lastStockGoodsSerialStripDTO; // // //Neu khong truyen tham so from serial,to serial,quantity thi lay tat ca if (quantity.equals(0L) && StringUtils.isNullOrEmpty(fromSerial) && StringUtils.isNullOrEmpty(toSerial)) { return lstStockGoodsSerialStripDTO; } //Lay dai dai serial theo so luong int iIndex = 0; StockGoodsSerialStripDTO stockGoodsSerialStripDTO; if (lstStockGoodsSerialStripDTO != null && lstStockGoodsSerialStripDTO.size() > 0) { //Tim kiem theo so luong if (!quantity.equals(0L)) { //ChuDV // while (quantityTotal <= quantity && iIndex < lstStockGoodsSerialStripDTO.size()) { // stockGoodsSerialStripDTO = lstStockGoodsSerialStripDTO.get(iIndex); // quantityTotal = quantityTotal + Long.parseLong(stockGoodsSerialStripDTO.getQuantity()); // iIndex++; // lstFilterStockGoodsSerialStripDTO.add(stockGoodsSerialStripDTO); //} // //ThienNG1 edit by 10.06.2016 Begin while (quantityTotal < quantity && iIndex < lstStockGoodsSerialStripDTO.size()) { stockGoodsSerialStripDTO = lstStockGoodsSerialStripDTO.get(iIndex); quantityTotal = quantityTotal + Long.parseLong(stockGoodsSerialStripDTO.getQuantity()); iIndex++; lstFilterStockGoodsSerialStripDTO.add(stockGoodsSerialStripDTO); } //ThienNG1 edit by 10.06.2016 End } else {//Khong theo so luong lstFilterStockGoodsSerialStripDTO = lstStockGoodsSerialStripDTO; } } //Xu ly dai serial dau tien va cuoi cung theo tham so, from serial va to_serial truyen vao int iSize = lstFilterStockGoodsSerialStripDTO.size(); Long firstQuantity; Long lastQuantity; int lengthSerial = 0; String firstToSerial = ""; //ThienNG addBy 01.06.2015 String lastToSerial = ""; // if (lstFilterStockGoodsSerialStripDTO != null && lstFilterStockGoodsSerialStripDTO.size() > 0) { //Xu ly dai serial dau tien firstStockGoodsSerialStripDTO = lstFilterStockGoodsSerialStripDTO.get(0); lengthSerial = firstStockGoodsSerialStripDTO.getFromSerial().length(); if (!StringUtils.isNullOrEmpty(fromSerial) && Long.parseLong(fromSerial) > Long.parseLong(firstStockGoodsSerialStripDTO.getFromSerial())) { firstStockGoodsSerialStripDTO.setFromSerial(fromSerial); } if (!StringUtils.isNullOrEmpty(toSerial) && Double.parseDouble(toSerial) < Double .parseDouble(firstStockGoodsSerialStripDTO.getToSerial())) { firstStockGoodsSerialStripDTO.setToSerial(toSerial); } //Cap nhat lai so luong firstQuantity = Long.parseLong(firstStockGoodsSerialStripDTO.getToSerial()) - Long.parseLong(firstStockGoodsSerialStripDTO.getFromSerial()) + 1; //Chan du lieu tim theo so luong //ThienNG1 EditBy 18/06/2015 //them dieu kien khi khong tim kiem theo so luong (quantity = 0L) if (!quantity.equals(0L)) { if (firstQuantity > quantity) { firstQuantity = quantity; firstToSerial = Long.parseLong(firstStockGoodsSerialStripDTO.getFromSerial()) + quantity - 1 + ""; firstStockGoodsSerialStripDTO.setToSerial(DataUtil.lPad(firstToSerial, "0", lengthSerial)); } } //End firstStockGoodsSerialStripDTO.setQuantity(firstQuantity.toString()); //ThienNG1- Begin EditBy 18/06/2015 //update so luong khi khong tim kiem theo so luong if (quantity.equals(0L)) { Long amount = Long.parseLong(firstStockGoodsSerialStripDTO.getToSerial()) - Long.parseLong(firstStockGoodsSerialStripDTO.getFromSerial()) + 1; firstStockGoodsSerialStripDTO.setQuantity(amount.toString()); } //End // lstFilterStockGoodsSerialStripDTO.set(0, firstStockGoodsSerialStripDTO); //Xu ly dai serial cuoi cung if (iSize > 1) { lastStockGoodsSerialStripDTO = lstFilterStockGoodsSerialStripDTO.get(iSize - 1); if (!StringUtils.isNullOrEmpty(toSerial) && Double.parseDouble(toSerial) < Double .parseDouble(lastStockGoodsSerialStripDTO.getToSerial())) { lastStockGoodsSerialStripDTO.setToSerial(toSerial); //Cap nhat lai so luong lastQuantity = Long.parseLong(lastStockGoodsSerialStripDTO.getToSerial()) - Long.parseLong(lastStockGoodsSerialStripDTO.getFromSerial()) + 1; lastStockGoodsSerialStripDTO.setQuantity(lastQuantity.toString()); // lstFilterStockGoodsSerialStripDTO.set(iSize - 1, lastStockGoodsSerialStripDTO); } //Chan du lieu tim tho so luong if (quantityTotal > quantity) { //ThienNG1 addBy 01.06.2015 - begin Long amount = 0L; Long amountTotal = 0L; for (int i = 0; i < lstFilterStockGoodsSerialStripDTO.size() - 1; i++) { amountTotal += Long.parseLong(lstFilterStockGoodsSerialStripDTO.get(i).getQuantity()); } amount = quantity - amountTotal; lastToSerial = Long.parseLong(lstFilterStockGoodsSerialStripDTO.get(iSize - 1).getFromSerial()) + amount - 1 + ""; lastStockGoodsSerialStripDTO.setToSerial(DataUtil.lPad(lastToSerial, "0", lengthSerial)); lastStockGoodsSerialStripDTO.setQuantity(amount.toString()); //end } } } // return lstFilterStockGoodsSerialStripDTO; }
From source file:com.square.core.service.implementations.PersonnePhysiqueServiceImplementation.java
/** * Rcupre l'email de la personne./*w w w.j a va 2 s . c om*/ * @param personne la personne dont on souhaite rcuprer l'email * @param idNatureEmail la nature de l'email recherch * @return l'email trouv */ private Email getEmailPersonne(Personne personne, Long idNatureEmail) { Email emailRecherche = null; for (Email email : personne.getEmails()) { if (idNatureEmail.equals(email.getNature().getId()) && !email.isSupprime()) { emailRecherche = email; break; } } return emailRecherche; }
From source file:com.square.tarificateur.noyau.service.implementations.TarificateurEditiqueServiceImpl.java
/** * Cre la liste des bnficiaire partir d'une ligne de devis principal. * @param ligneDevisPrincipale la ligne de devis principale * @param listeIdsLignesSelectionnees la liste des identifiants de lignes slectionnes * @param listeIdsLignesSelectionnees la liste des identifiants des bnficiaires slectionns. * @param prospect le prospect//from w w w. j a v a 2 s . c o m * @param infosPersonneSquare le cache des infos de personnes Square * @return la liste des bnficiaires */ private List<BeneficiaireBADto> creerListeBeneficiaires(LigneDevis ligneDevisPrincipale, List<Long> listeIdsLignesSelectionnees, List<Long> listeIdsBenefsSelectionnes, Personne prospect, InfosPersonneSquareBean infosPersonneSquare) { // On stocke le lien familial de chaque bnficiaire avec le prospect dans une map final Map<Long, Long> mapLienFamilialBeneficiaires = new HashMap<Long, Long>(); for (Beneficiaire beneficiaireParcouru : prospect.getListeBeneficiaires()) { mapLienFamilialBeneficiaires.put(beneficiaireParcouru.getPersonneCible().getId(), beneficiaireParcouru.getLienFamilial().getId()); } final List<BeneficiaireBADto> listeBeneficiaires = new ArrayList<BeneficiaireBADto>(); // Map des valeurs de rgle de stage par bnficiaire final Map<Long, List<RegleValeur>> mapValeursReglesStageBeneficiaires = new HashMap<Long, List<RegleValeur>>(); final List<RegleValeur> listeValeursReglesStageProspect = new ArrayList<RegleValeur>(); // Rcupration de constantes final Integer idRegleStage = regleMappingService.getIdRegleStage(); final Integer idValeurRegleStageSmatis = regleMappingService.getIdValeurRegleStageSmatis(); final Long idLienConjoint = tarificateurSquareMappingService.getIdLienFamilialConjoint(); // Test si le produit de la ligne principale a un code de tarification "adherent" final Integer idProduit = ligneDevisPrincipale.getEidProduit(); final ProduitCriteresDto criteres = new ProduitCriteresDto(); criteres.setIdentifiantProduit(idProduit); final List<ProduitDto> listeProduits = produitService.getListeProduits(criteres); if (listeProduits == null || listeProduits.size() != 1) { throw new BusinessException(messageSourceUtil.get(MessageKeyUtil.PRODUIT_LIGNE_DEVIS_INTROUVABLE)); } final ProduitDto produitDto = listeProduits.get(0); if (produitDto.getModeTarification() != null && tarificateurMappingService.getConstanteIdModeTarificationAdherent() .equals(produitDto.getModeTarification().getIdentifiant())) { if (listeIdsBenefsSelectionnes != null && listeIdsBenefsSelectionnes.size() > 0) { for (Long idBeneficiaire : listeIdsBenefsSelectionnes) { final Beneficiaire beneficiaireProspect = beneficiaireDao .getBeneficiaireByCible(idBeneficiaire); if (beneficiaireProspect == null) { throw new BusinessException( messageSourceUtil.get(MessageKeyUtil.ERROR_BENEFICIAIRE_INEXISTANT)); } // Cration du bnficiaireBA final BeneficiaireBADto beneficiaireDevisDto = mapperBeneficiaire( beneficiaireProspect.getPersonneCible(), infosPersonneSquare); beneficiaireDevisDto.setIdBeneficiaire(beneficiaireProspect.getPersonneCible().getId()); // Test si c'est le conjoint if (beneficiaireProspect.getLienFamilial() != null && beneficiaireProspect.getLienFamilial().getId() != null && beneficiaireProspect.getLienFamilial().getId().equals(idLienConjoint)) { beneficiaireDevisDto.setIsConjoint(Boolean.TRUE); } // Ajout du bnficiaire la liste des bnficiaires du devis listeBeneficiaires.add(beneficiaireDevisDto); } } } else { // Ajout des bnficiaires du prospect partir des lignes lies de la ligne principale final List<Long> listeIdsBeneficiairesDejaPresents = new ArrayList<Long>(); // Parcours des lignes lies for (LigneDevisLiee ligneLiee : ligneDevisPrincipale.getListeLignesDevisLiees()) { final LigneDevis ligneDevisLiee = ligneLiee.getLigneDevisLiee(); // On ne prend en compte que les bnficiaires des lignes slectionnes if (listeIdsLignesSelectionnees.contains(ligneDevisLiee.getId())) { // Si c'est une ligne sur un bnficiaire : on l'ajoute la liste s'il n'est pas dj prsent final Personne beneficiaire = ligneDevisLiee.getBeneficiaire(); if (beneficiaire != null) { if (!listeIdsBeneficiairesDejaPresents.contains(beneficiaire.getId())) { // Ajout de l'id du bnficiaire la liste des bnficiaires dj prsents listeIdsBeneficiairesDejaPresents.add(beneficiaire.getId()); // Cration du bnficiaireBA final BeneficiaireBADto beneficiaireDevisDto = mapperBeneficiaire(beneficiaire, infosPersonneSquare); beneficiaireDevisDto.setIdBeneficiaire(beneficiaire.getId()); final Long idLienFamilial = mapLienFamilialBeneficiaires.get(beneficiaire.getId()); // Dtection du conjoint if (idLienFamilial != null && idLienFamilial.equals(idLienConjoint)) { beneficiaireDevisDto.setIsConjoint(Boolean.TRUE); } // Ajout du bnficiaire la liste des bnficiaires du devis listeBeneficiaires.add(beneficiaireDevisDto); } // Rcupration de la valeur de la rgle "Stage" List<RegleValeur> listeValeurReglesStageBeneficiaire = mapValeursReglesStageBeneficiaires .get(beneficiaire.getId()); if (listeValeurReglesStageBeneficiaire == null) { listeValeurReglesStageBeneficiaire = new ArrayList<RegleValeur>(); mapValeursReglesStageBeneficiaires.put(beneficiaire.getId(), listeValeurReglesStageBeneficiaire); } final RegleValeur regleValeur = getValeurRegleStageByLigneDevis(ligneDevisLiee, idRegleStage); if (regleValeur != null) { listeValeurReglesStageBeneficiaire.add(regleValeur); } } else { // Sinon c'est un prospect // Rcupration de la valeur de la rgle "Stage" final RegleValeur regleValeurStage = getValeurRegleStageByLigneDevis(ligneDevisLiee, idRegleStage); if (regleValeurStage != null) { listeValeursReglesStageProspect.add(regleValeurStage); } } } } // Ajout des dlais de stage des bnficiaires for (BeneficiaireBADto beneficiaireBADto : listeBeneficiaires) { final List<RegleValeur> listeValeursReglesStageBeneficiaire = mapValeursReglesStageBeneficiaires .get(beneficiaireBADto.getIdBeneficiaire()); beneficiaireBADto.setDelaiAttente(getDelaiStageByReglesValeurs(listeValeursReglesStageBeneficiaire, idValeurRegleStageSmatis)); } } // On ordonne les bnficiaires par date de naissance croissante // test si les date de naissance sont non nulles for (BeneficiaireBADto beneficiaireBADto : listeBeneficiaires) { if (beneficiaireBADto.getDateDeNaissance() == null) { throw new BusinessException( messageSourceUtil.get(MessageKeyUtil.ERROR_BENEFICIAIRE_DATE_NAISSANCE_NULLE)); } } // Cration d'un Comparator final Comparator<BeneficiaireBADto> comparator = new Comparator<BeneficiaireBADto>() { public int compare(BeneficiaireBADto o1, BeneficiaireBADto o2) { return ((BeneficiaireBADto) o1).getDateDeNaissance() .compareTo(((BeneficiaireBADto) o2).getDateDeNaissance()); } }; Collections.sort(listeBeneficiaires, comparator); logger.debug(messageSourceUtil.get(MessageKeyUtil.LOGGER_DEBUG_TAILLE_LISTE_BENEFICIAIRE, new String[] { String.valueOf(listeBeneficiaires.size()) })); // Ajout du prospect en tant que bnficiaire (en dbut de liste) final BeneficiaireBADto prospectBeneficiaireBA = mapperBeneficiaire(prospect, infosPersonneSquare); prospectBeneficiaireBA.setIdProspect(prospect.getId()); // Ajout de la valeur de rgle Stage de la ligne principale final RegleValeur regleValeurStage = getValeurRegleStageByLigneDevis(ligneDevisPrincipale, idRegleStage); if (regleValeurStage != null) { listeValeursReglesStageProspect.add(regleValeurStage); } // Ajout du dlai de stage au prospect prospectBeneficiaireBA.setDelaiAttente( getDelaiStageByReglesValeurs(listeValeursReglesStageProspect, idValeurRegleStageSmatis)); listeBeneficiaires.add(0, prospectBeneficiaireBA); return listeBeneficiaires; }
From source file:com.square.core.service.implementations.PersonnePhysiqueServiceImplementation.java
/** * Rcupre l'adresse d'une personne.//from w ww.j a v a 2 s .c o m * @param personne la personne * @param idNatureAdresse la nature de l'adresse recherche * @return l'adresse trouve */ private Adresse getAdressePersonne(Personne personne, Long idNatureAdresse) { Adresse adresseRecherchee = null; for (Adresse adresse : personne.getAdresses()) { if (idNatureAdresse.equals(adresse.getNature().getId()) && !adresse.isSupprime() && adresse.getDateFin() == null) { adresseRecherchee = adresse; break; } } return adresseRecherchee; }
From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java
private void mapRequestToObj(HashMap<String, Object> data, Class expectedClass, Object obj) throws Exception { if (obj == null) { throw new ApplicationException("mapRequestToObj called on NULL obj", "ERR9001"); }/*from w w w . j a v a2 s . com*/ try { Method versionMethod = expectedClass.getMethod("getVersion", (Class<?>[]) null); Long objVersion = (Long) versionMethod.invoke(obj, (Object[]) null); String clientVersion = (String) data.get("version"); if (objVersion != null && clientVersion != null) { try { long clientVersionLong = Long.parseLong(clientVersion); if (!objVersion.equals(clientVersionLong)) { throw makeApplicationException("Can't save object", "ERR9016", (Serializable[]) null); } } catch (NumberFormatException nfe) { // Version from client isn't number - ignore } } } catch (NoSuchMethodException nme) { // No version control } Method[] methods = expectedClass.getMethods(); for (Method m : methods) { Class<?>[] paramTypes = m.getParameterTypes(); Class persistentClass = null; if (paramTypes.length == 1) { if (paramTypes[0].getAnnotation(Entity.class) != null) { persistentClass = paramTypes[0]; } else if (paramTypes[0].getAnnotation(Embeddable.class) != null) { persistentClass = paramTypes[0]; } } ServiceDescription srvParam = paramTypes.length == 1 ? findServiceByClassName(paramTypes[0].getName()) : null; if ((m.getName().startsWith(SET_PREFIX) && paramTypes.length == 1 && (paramTypes[0].isAssignableFrom(String.class) || paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE) || paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE) || paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE) || paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE) || paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE) || paramTypes[0].equals(Date.class) || Enum.class.isAssignableFrom(paramTypes[0]) || (srvParam != null && srvParam.getFindById() != null) || persistentClass != null)) || (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType())))) { String fldName; if (m.getName().startsWith(GET_TRANSLATE)) { fldName = m.getName().substring(GET_TRANSLATE_LENGTH, GET_TRANSLATE_LENGTH + 1).toLowerCase() + m.getName().substring(GET_TRANSLATE_LENGTH + 1); } else { fldName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); } Object value = data.get(fldName); if (value == null) { fldName = m.getName().substring(3); value = data.get(fldName); } if (value != null) { Object typedVal; String val = null; if (value instanceof String) { val = (String) value; } log.log(Level.FINER, " value = " + value); if (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType()))) { log.log(Level.FINER, "GET"); String attrName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); Type[] actualTypeArguments = null; Class iterClass = expectedClass; while (iterClass != null) { try { Field field = iterClass.getDeclaredField(attrName); ParameterizedType genericType = (ParameterizedType) field.getGenericType(); actualTypeArguments = genericType.getActualTypeArguments(); break; } catch (NoSuchFieldException nsfe) { // do nothing iterate again } iterClass = iterClass.getSuperclass(); iterClass = iterClass.equals(Object.class) ? null : iterClass; } if (actualTypeArguments != null && actualTypeArguments.length == 1 && actualTypeArguments[0] instanceof Class) { Class assocClass = (Class) actualTypeArguments[0]; ServiceDescription assocService = findServiceByClassName(assocClass.getName()); Collection dbValueSet = (Collection) m.invoke(obj, (Object[]) null); if (value == null || !(value instanceof HashMap)) { log.log(Level.FINE, "No data for db property {0}", attrName); } else if (assocService != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { boolean wasMatchingGuiVal = false; ArrayList<String> removeKeys = new ArrayList<String>(); for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object guiValue = ((HashMap<String, Object>) object).get("id"); if (guiValue.equals(dbValId)) { removeKeys.add(key); wasMatchingGuiVal = true; mapRequestToObj((HashMap<String, Object>) guiValue, assocClass, dbVal); break; } } else if (object instanceof String) { // Association if (dbValId.equals(object)) { removeKeys.add(key); wasMatchingGuiVal = true; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } // Remove processed elements // Direct remove is firing concurrent modification exception for (String removeKey : removeKeys) { guiValueMap.remove(removeKey); } if (!wasMatchingGuiVal) { // Is not in list comming from GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else if (object instanceof String) { // Association try { Long id = new Long((String) object); Object assocObj = assocService.getFindById().invoke( assocService.getInstance(), ServiceContextStore.get(), id); if (assocObj != null) { dbValueSet.add(assocObj); } else { log.log(Level.WARNING, "Object with ID {0} not availabla via service {1}", new Object[] { id, assocService.getName() }); } } catch (Exception ex) { log.log(Level.WARNING, "No ID parsable from value {0} under key {1}", new Object[] { object, key }); } } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } else if (assocClass != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { Object matchingGuiVal = null; for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { HashMap<String, Object> guiVal = (HashMap<String, Object>) object; if (dbValId.equals(guiVal.get("id"))) { guiValueMap.remove(key); matchingGuiVal = guiVal; break; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } if (matchingGuiVal != null) { // Coming from GUI - update mapRequestToObj((HashMap<String, Object>) matchingGuiVal, assocClass, dbVal); } else { // Not in GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } } else { log.log(Level.WARNING, "No DB mapping or not of collection type: {0}", attrName); } typedVal = null; } else if (paramTypes[0].isAssignableFrom(String.class)) { typedVal = val; } else if (paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE)) { typedVal = Integer.parseInt(val); } else if (paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE)) { typedVal = Long.parseLong(val); } else if (paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE)) { typedVal = Double.parseDouble(val); } else if (paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE)) { typedVal = Float.parseFloat(val); } else if (paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE)) { typedVal = "true".equalsIgnoreCase(val) || "t".equalsIgnoreCase(val) || "y".equalsIgnoreCase(val); } else if (paramTypes[0].isAssignableFrom(Date.class)) { typedVal = dateFormat.parse(val); } else if (Enum.class.isAssignableFrom(paramTypes[0])) { try { Method fromValueMethod = paramTypes[0].getMethod("fromValue", String.class); typedVal = fromValueMethod.invoke(null, val); } catch (Exception ex) { typedVal = null; } try { if (typedVal == null) { Method valueOfMethod = paramTypes[0].getMethod("valueOf", String.class); typedVal = valueOfMethod.invoke(null, val); } } catch (Exception ex) { typedVal = null; } } else if (persistentClass != null && persistentClass.equals(FileUpload.class)) { FileItem fileItem = uploadServlet.getFileItem(sessionId.get(), fldName, val); if (fileItem != null) { typedVal = fileUploadService.uploadFile(ServiceContextStore.get(), fileItem.getName(), fileItem.getContentType(), fileItem.getInputStream()); } else { typedVal = null; } } else if (srvParam != null && srvParam.getFindById() != null) { if (value instanceof HashMap) { HashMap<String, Object> embeddedObj = (HashMap<String, Object>) value; typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), new Long((String) embeddedObj.get("id"))); mapRequestToObj(embeddedObj, srvParam.getExpectedClass(), typedVal); } else { try { Long parsedId = new Long(val); typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), parsedId); } catch (NumberFormatException nfe) { // wrong value typedVal = null; } } } else if (persistentClass != null) { String getMethodName = "g" + m.getName().substring(1); try { Method getMethod = obj.getClass().getMethod(getMethodName, (Class[]) null); typedVal = getMethod.invoke(obj, (Object[]) null); } catch (NoSuchMethodException nsme) { typedVal = null; } if (typedVal == null) { typedVal = makeNewInstance(persistentClass, (HashMap<String, Object>) value); } mapRequestToObj((HashMap<String, Object>) value, typedVal.getClass(), typedVal); } else { log.log(Level.WARNING, "Can't convert value for: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); typedVal = null; } if (typedVal != null) { m.invoke(obj, typedVal); } } } else if (m.getName().startsWith(SET_PREFIX)) { log.log(Level.WARNING, "Unusable setter method: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); } } }
From source file:br.gov.jfrj.siga.vraptor.ExClassificacaoController.java
@Post("app/expediente/classificacao/gravarVia") public void gravarVia(String acao, String codificacao, ExVia via, Long idDestino, Long idTemporalidadeArqCorr, Long idTemporalidadeArqInterm, Long idDestinacaoFinal) throws Exception { assertAcesso("DOC:Mdulo de Documentos;FE:Ferramentas;PC:Plano de Classificao"); if (idDestino == null || idDestino <= 0) { throw new AplicacaoException("A destinao da via deve ser definida!"); }//ww w . j a v a2s. c o m dao().iniciarTransacao(); try { Date dt = dao().consultarDataEHoraDoServidor(); ExClassificacao exClassAntiga = buscarExClassificacao(codificacao); if (exClassAntiga == null) { throw new AplicacaoException("Erro ao obter a classificao"); } ExClassificacao exClassNovo = Ex.getInstance().getBL().getCopia(exClassAntiga); dao().gravarComHistorico(exClassNovo, exClassAntiga, dt, getIdentidadeCadastrante()); ExVia exVia = null; ExVia exViaGravar = null; Date dtHist = null; Boolean removerViaAntiga = false; if (via.getId() == null) { // nova via exVia = new ExVia(); exVia.setCodVia(String.valueOf(exClassAntiga.getExViaSet().size() + 1)); exViaGravar = exVia; exVia = null; dtHist = null; } else { // alterar via existente exVia = dao().consultar(via.getId(), ExVia.class, false); ExVia exViaNova = new ExVia(); try { PropertyUtils.copyProperties(exViaNova, exVia); // novo id exViaNova.setId(null); exViaNova.setCodVia(exVia.getCodVia()); exViaGravar = exViaNova; dtHist = dt; removerViaAntiga = true; } catch (Exception e) { throw new AplicacaoException("Erro ao copiar as propriedades da via anterior."); } } ExTipoDestinacao destino = !idDestino.equals(-1L) ? dao().consultar(idDestino, ExTipoDestinacao.class, false) : null; ExTipoDestinacao destFinal = !idDestinacaoFinal.equals(-1L) ? dao().consultar(idDestinacaoFinal, ExTipoDestinacao.class, false) : null; ExTemporalidade tempCorrente = !idTemporalidadeArqCorr.equals(-1L) ? dao().consultar(idTemporalidadeArqCorr, ExTemporalidade.class, false) : null; ExTemporalidade tempInterm = !idTemporalidadeArqInterm.equals(-1L) ? dao().consultar(idTemporalidadeArqInterm, ExTemporalidade.class, false) : null; exViaGravar.setExClassificacao(exClassNovo); exViaGravar.setExTipoDestinacao(destino); exViaGravar.setExDestinacaoFinal(destFinal); exViaGravar.setTemporalidadeCorrente(tempCorrente); exViaGravar.setTemporalidadeIntermediario(tempInterm); exViaGravar.setObs(via.getObs()); dao().gravarComHistorico(exViaGravar, exVia, dtHist, getIdentidadeCadastrante()); exClassNovo.getExViaSet().add(exViaGravar); if (removerViaAntiga) { exClassAntiga.getExViaSet().remove(exVia); } Ex.getInstance().getBL().copiarReferencias(exClassNovo, exClassAntiga, dt, getIdentidadeCadastrante()); dao().commitTransacao(); //result.redirectTo("editar?codificacao="+codificacao+"&acao="+acao); result.forwardTo(this).edita(exClassNovo, codificacao, acao); } catch (Exception e) { dao().rollbackTransacao(); throw new AplicacaoException("No foi possvel gravar via no banco de dados." + e.getMessage()); } }
From source file:com.square.core.service.implementations.PersonnePhysiqueServiceImplementation.java
/** * Rcupre le tlphone d'une personne./*w w w .ja v a2 s. c om*/ * @param personne la personne * @param idNatureTelephone la nature du tlphone recherch * @return le tlphone trouv */ private Telephone getTelephonePersonne(Personne personne, Long idNatureTelephone) { Telephone telephoneRecherche = null; for (Telephone telephone : personne.getTelephones()) { if (!telephone.isSupprime() && idNatureTelephone.equals(telephone.getNatureTelephone().getId())) { telephoneRecherche = telephone; break; } } return telephoneRecherche; }
From source file:org.apache.cocoon.acting.AbstractValidatorAction.java
/** * Validates nullability and default value for given parameter. If given * constraints are not null they are validated as well. *///from w w w .j a va 2 s .c o m private ValidatorActionHelper validateLong(String name, Configuration constraints, Configuration conf, Map params, boolean is_string, Object param) { boolean nullable = getNullable(conf, constraints); Long value = null; Long dflt = getLongValue(getDefault(conf, constraints), true); if (getLogger().isDebugEnabled()) getLogger().debug("Validating long parameter " + name + " (encoded in a string: " + is_string + ")"); try { value = getLongValue(param, is_string); } catch (Exception e) { // Unable to parse long return new ValidatorActionHelper(value, ValidatorActionResult.ERROR); } if (value == null) { if (getLogger().isDebugEnabled()) getLogger().debug("Long parameter " + name + " is null"); if (!nullable) { return new ValidatorActionHelper(value, ValidatorActionResult.ISNULL); } else { return new ValidatorActionHelper(dflt); } } if (constraints != null) { Long eq = getAttributeAsLong(constraints, "equals-to", null); String eqp = constraints.getAttribute("equals-to-param", ""); Long min = getAttributeAsLong(conf, "min", null); min = getAttributeAsLong(constraints, "min", min); Long max = getAttributeAsLong(conf, "max", null); max = getAttributeAsLong(constraints, "max", max); // Validate whether param is equal to constant if (eq != null) { if (getLogger().isDebugEnabled()) getLogger().debug("Long parameter " + name + " should be equal to " + eq); if (!value.equals(eq)) { if (getLogger().isDebugEnabled()) getLogger().debug("and it is not"); return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH); } } // Validate whether param is equal to another param // FIXME: take default value of param being compared with into // account? if (!"".equals(eqp)) { if (getLogger().isDebugEnabled()) getLogger().debug("Long parameter " + name + " should be equal to " + params.get(eqp)); // Request parameter is stored as string. // Need to convert it beforehand. try { Long _eqp = new Long(Long.parseLong((String) params.get(eqp))); if (!value.equals(_eqp)) { if (getLogger().isDebugEnabled()) getLogger().debug("and it is not"); return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH); } } catch (NumberFormatException nfe) { if (getLogger().isDebugEnabled()) getLogger().debug("Long parameter " + name + ": " + eqp + " is no long", nfe); return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH); } } // Validate wheter param is at least min if (min != null) { if (getLogger().isDebugEnabled()) getLogger().debug("Long parameter " + name + " should be at least " + min); if (min.compareTo(value) > 0) { if (getLogger().isDebugEnabled()) getLogger().debug("and it is not"); return new ValidatorActionHelper(value, ValidatorActionResult.TOOSMALL); } } // Validate wheter param is at most max if (max != null) { if (getLogger().isDebugEnabled()) getLogger().debug("Long parameter " + name + " should be at most " + max); if (max.compareTo(value) < 0) { if (getLogger().isDebugEnabled()) getLogger().debug("and it is not"); return new ValidatorActionHelper(value, ValidatorActionResult.TOOLARGE); } } } return new ValidatorActionHelper(value); }
From source file:jp.primecloud.auto.process.puppet.PuppetComponentProcess.java
protected Map<String, Object> createInstanceMap(Long componentNo, ComponentProcessContext context, boolean start, Long instanceNo, Map<String, Object> rootMap) { Map<String, Object> map = new HashMap<String, Object>(rootMap); // Instance/*from w w w . ja va2 s .c o m*/ Instance instance = instanceDao.read(instanceNo); map.put("instance", instance); // PuppetInstance PuppetInstance puppetInstance = puppetInstanceDao.read(instanceNo); map.put("puppetInstance", puppetInstance); // InstanceConfig List<InstanceConfig> instanceConfigs = instanceConfigDao.readByInstanceNo(instanceNo); Map<String, Object> configs = new HashMap<String, Object>(); for (InstanceConfig instanceConfig : instanceConfigs) { if (componentNo.equals(instanceConfig.getComponentNo())) { configs.put(instanceConfig.getConfigName(), instanceConfig.getConfigValue()); } } map.put("instanceConfigs", configs); // Platform Platform platform = platformDao.read(instance.getPlatformNo()); map.put("platform", platform); // TODO CLOUD BRANCHING if (PCCConstant.PLATFORM_TYPE_AWS.equals(platform.getPlatformType())) { // AwsInstance AwsInstance awsInstance = awsInstanceDao.read(instanceNo); map.put("awsInstance", awsInstance); // AwsVolume AwsVolume awsVolume = awsVolumeDao.readByComponentNoAndInstanceNo(componentNo, instanceNo); if (awsVolume != null) { map.put("awsVolume", awsVolume); } } else if (PCCConstant.PLATFORM_TYPE_CLOUDSTACK.equals(platform.getPlatformType())) { // CloudStackInstance CloudstackInstance cloudstackInstance = cloudstackInstanceDao.read(instanceNo); map.put("cloudstackInstance", cloudstackInstance); // CloudStackVolume CloudstackVolume cloudstackVolume = cloudstackVolumeDao.readByComponentNoAndInstanceNo(componentNo, instanceNo); if (cloudstackVolume != null) { map.put("cloudstackVolume", cloudstackVolume); } } else if (PCCConstant.PLATFORM_TYPE_VMWARE.equals(platform.getPlatformType())) { // VmwareInstance VmwareInstance vmwareInstance = vmwareInstanceDao.read(instanceNo); map.put("vmwareInstance", vmwareInstance); // VmwareDisk VmwareDisk vmwareDisk = vmwareDiskDao.readByComponentNoAndInstanceNo(componentNo, instanceNo); if (vmwareDisk != null) { map.put("vmwareDisk", vmwareDisk); } } else if (PCCConstant.PLATFORM_TYPE_NIFTY.equals(platform.getPlatformType())) { // NiftyInstance NiftyInstance niftyInstance = niftyInstanceDao.read(instanceNo); map.put("niftyInstance", niftyInstance); // NiftyVolume NiftyVolume niftyVolume = niftyVolumeDao.readByComponentNoAndInstanceNo(componentNo, instanceNo); if (niftyVolume != null) { map.put("niftyVolume", niftyVolume); } } else if (PCCConstant.PLATFORM_TYPE_VCLOUD.equals(platform.getPlatformType())) { // VcloudInstance VcloudInstance vcloudInstance = vcloudInstanceDao.read(instanceNo); map.put("vcloudInstance", vcloudInstance); // VcloudDisk VcloudDisk vcloudDisk = null; List<VcloudDisk> vcloudDisks = vcloudDiskDao.readByComponentNo(componentNo); for (VcloudDisk tmpVcloudDisk : vcloudDisks) { if (tmpVcloudDisk.getInstanceNo().equals(instanceNo)) { vcloudDisk = tmpVcloudDisk; break; } } if (vcloudDisk != null) { map.put("vcloudDisk", vcloudDisk); } } else if (PCCConstant.PLATFORM_TYPE_AZURE.equals(platform.getPlatformType())) { // AzureInstance AzureInstance azureInstance = azureInstanceDao.read(instanceNo); map.put("azureInstance", azureInstance); // AzureDisk AzureDisk azureDisk = azureDiskDao.readByComponentNoAndInstanceNo(componentNo, instanceNo); if (azureDisk != null) { map.put("azureDisk", azureDisk); } } else if (PCCConstant.PLATFORM_TYPE_OPENSTACK.equals(platform.getPlatformType())) { // OpenstackInstance OpenstackInstance openstackInstance = openstackInstanceDao.read(instanceNo); map.put("openstackInstance", openstackInstance); // OpenstackVolume OpenstackVolume openstackVolume = openstackVolumeDao.readByComponentNoAndInstanceNo(componentNo, instanceNo); if (openstackVolume != null) { map.put("openstackVolume", openstackVolume); } } // IP List<Instance> runningInstances = instanceDao.readInInstanceNos(context.getRunningInstanceNos()); Map<String, String> accessIps = new HashMap<String, String>(); for (Instance runningInstance : runningInstances) { // ?publicIp?? String accessIp = runningInstance.getPublicIp(); if (instance.getPlatformNo().equals(runningInstance.getPlatformNo())) { // ???? // TODO CLOUD BRANCHING if (PCCConstant.PLATFORM_TYPE_AWS.equals(platform.getPlatformType())) { PlatformAws platformAws = platformAwsDao.read(runningInstance.getPlatformNo()); if (BooleanUtils.isFalse(platformAws.getVpc())) { // VPC?????privateIp?? accessIp = runningInstance.getPrivateIp(); } } else if (PCCConstant.PLATFORM_TYPE_CLOUDSTACK.equals(platform.getPlatformType())) { // Cloudstack?publicIp?? accessIp = runningInstance.getPublicIp(); } else if (PCCConstant.PLATFORM_TYPE_VMWARE.equals(platform.getPlatformType())) { // VMware???privateIp?? accessIp = runningInstance.getPrivateIp(); } else if (PCCConstant.PLATFORM_TYPE_NIFTY.equals(platform.getPlatformType())) { // ???privateIp?? accessIp = runningInstance.getPrivateIp(); } else if (PCCConstant.PLATFORM_TYPE_VCLOUD.equals(platform.getPlatformType())) { // VCloud???privateIp?? accessIp = runningInstance.getPrivateIp(); } else if (PCCConstant.PLATFORM_TYPE_AZURE.equals(platform.getPlatformType())) { // Azure???privateIp?? accessIp = runningInstance.getPrivateIp(); } else if (PCCConstant.PLATFORM_TYPE_OPENSTACK.equals(platform.getPlatformType())) { // Openstack?publicIp?? accessIp = runningInstance.getPublicIp(); } } accessIps.put(runningInstance.getInstanceNo().toString(), accessIp); } map.put("accessIps", accessIps); // ???????? boolean unDetachVolume = BooleanUtils.toBoolean(Config.getProperty("unDetachVolume")); map.put("unDetachVolume", unDetachVolume); return map; }
From source file:hu.netmind.beankeeper.modification.impl.ModificationTrackerImpl.java
/** * This method registers "potential" change serials for a given id. The * change becomes final only when the transaction's commit ends. * @param meta The list of metainformation for objects that changed. * @param endSerial The serial on which these changes went into database. * @param txSerial The tx identifier for later tracking, whether the tx committed. *///from w w w . ja va 2 s . co m private void changeCandidates(List<PersistenceMetaData> metas, Long endSerial, Long txSerial) { synchronized (operationTracker.getMutex()) { // Clear obsolate data while (((!entriesByDate.isEmpty()) && (System.currentTimeMillis() - ((ModificationEntry) entriesByDate.first()).entryDate.getTime() > MAX_ENTRY_AGE)) || (entriesByDate.size() > MAX_ENTRY_ITEMS)) { // The first entry is obsolate, so clear it from the cache ModificationEntry entry = (ModificationEntry) entriesByDate.first(); entriesById.remove(entry.id); entriesByDate.remove(entry); if (entry.potentialTxSerial != null) entriesByTxSerial.remove(entry.potentialTxSerial); if (entry.lastChangeSerial != null) lastCacheRemovedSerial = entry.lastChangeSerial; modifyClassEntries(entry, false); // Remove } // Add all data to internal structures if (logger.isDebugEnabled()) logger.debug("changed following objects: " + metas + ", with endserial: " + endSerial + ", tx: " + txSerial); ArrayList entries = new ArrayList(); entriesByTxSerial.put(txSerial, entries); for (int i = 0; i < metas.size(); i++) { PersistenceMetaData meta = (PersistenceMetaData) metas.get(i); // Search or create entry ModificationEntry entry = (ModificationEntry) entriesById.get(meta.getPersistenceId()); if (entry == null) { entry = new ModificationEntry(); entry.id = meta.getPersistenceId(); entry.objectClass = meta.getObjectClass(); entry.entryDate = new Date(); // Update data structure entriesById.put(entry.id, entry); entriesByDate.add(entry); modifyClassEntries(entry, true); } entry.potentialChangeSerial = endSerial; if ((entry.potentialTxSerial != null) && (!txSerial.equals(entry.potentialTxSerial))) { // This entry was part of an old transaction, which was // unfinished (endCommit was not received). So delete from // it's list. List obsolateTxList = (List) entriesByTxSerial.get(entry.potentialTxSerial); if (obsolateTxList != null) { obsolateTxList.remove(entry); if (obsolateTxList.isEmpty()) entriesByTxSerial.remove(entry.potentialTxSerial); } } entry.potentialTxSerial = txSerial; entries.add(entry); } } }