List of usage examples for java.lang Long equals
public boolean equals(Object obj)
From source file:jp.primecloud.auto.service.impl.IaasDescribeServiceImpl.java
/** * {@inheritDoc}//from ww w. j a v a 2 s .c om */ @Override public String hasIpAddresse(Long platformNo, Long instanceNo, String ipAddress) { // ? if (platformNo == null) { throw new AutoApplicationException("ECOMMON-000003", "platformNo"); } if (instanceNo == null) { throw new AutoApplicationException("ECOMMON-000003", "instanceNo"); } if (StringUtils.isEmpty(ipAddress)) { throw new AutoApplicationException("ECOMMON-000003", "ipAddress"); } List<VcloudInstanceNetwork> vcloudInstanceNetworks = vcloudInstanceNetworkDao.readByPlatformNo(platformNo); for (VcloudInstanceNetwork instanceNetwork : vcloudInstanceNetworks) { if (!instanceNo.equals(instanceNetwork.getInstanceNo()) && instanceNetwork.getIpAddress().equals(ipAddress)) { Instance instance = instanceDao.read(instanceNetwork.getInstanceNo()); return instance.getInstanceName(); } } return null; }
From source file:com.viettel.util.excel.DynamicExport.java
public void setRowHeight(int r1, int c1, int r2, int c2, Long value) throws Exception { if (value.equals(0L)) { value = 500L;/*from www . ja v a 2 s. c o m*/ } for (int i = r1; i <= r2; i++) { view.setRowHeight(i, value.intValue()); } }
From source file:com.square.core.service.implementations.OpportuniteServiceImplementation.java
@Override public void mettreAJourStatutOpportunite(OpportuniteMaJStatutDto opportuniteMaJStatut) { // Vrification que les champs ne sont pas null if (opportuniteMaJStatut == null) { throw new BusinessException( messageSourceUtil.get(OpportuniteKeyUtil.MESSAGE_ERREUR_OPP_MODIFICATION_DTO_NULL)); }// w w w .jav a2 s .co m if (opportuniteMaJStatut.getIdOpportunite() == null) { throw new BusinessException(messageSourceUtil.get(OpportuniteKeyUtil.MESSAGE_ERREUR_OPP_ID_OPP_NULL)); } if (opportuniteMaJStatut.getStatut() == null || opportuniteMaJStatut.getStatut().getIdentifiant() == null) { throw new BusinessException(messageSourceUtil.get(OpportuniteKeyUtil.MESSAGE_ERREUR_OPP_STATUT_NULL)); } // Vrification de l'existance du statut final OpportuniteStatut opportuniteStatut = opportuniteStatutDao .rechercherOpportuniteStatutParId(opportuniteMaJStatut.getStatut().getIdentifiant()); if (opportuniteStatut == null) { logger.error("Le statut de l'opportunit n'existe pas : " + opportuniteMaJStatut.getStatut().getIdentifiant()); throw new BusinessException( messageSourceUtil.get(OpportuniteKeyUtil.MESSAGE_ERREUR_OPPORTUNITE_STATUT_INEXISTANT)); } final Long idStatutApres = opportuniteMaJStatut.getStatut().getIdentifiant(); // Rcupration de l'opportunit final Opportunite opportunite = opportuniteDao .rechercherOpportuniteParId(opportuniteMaJStatut.getIdOpportunite()); final Long idStatutAvant = opportunite.getStatut().getId(); // Modification de l'opportunit opportunite.setStatut(opportuniteStatut); // Fermeture des actions de types relance lies l'opportunit si l'opportunit passe "Transforme" final Long idStatutTransforme = squareMappingService.getIdStatutOpportuniteTransforme(); if (!idStatutTransforme.equals(idStatutAvant) && idStatutTransforme.equals(idStatutApres)) { final List<Action> listeActionsOpportunite = actionDao .rechercherActionsParOpportunite(opportuniteMaJStatut.getIdOpportunite()); final Long idTypeActionRelance = squareMappingService.getIdTypeActionRelance(); final Long idStatutActionAFaire = squareMappingService.getIdStatutAFaire(); final ActionStatut statutTermine = actionStatutDao .rechercherStatutActionParId(squareMappingService.getIdStatutTerminer()); final Calendar maintenant = Calendar.getInstance(); for (Action action : listeActionsOpportunite) { if (action.getType() != null && idTypeActionRelance.equals(action.getType().getId()) && (action.getStatut() == null || action.getStatut().getId() == null || idStatutActionAFaire.equals(action.getStatut().getId()))) { action.setStatut(statutTermine); action.setDateModification(maintenant); action.setDateTerminee(maintenant); } } } }
From source file:com.clustercontrol.agent.filecheck.FileCheck.java
/** * ?<BR>/* w ww .j a va 2 s. c o m*/ * */ public void run() { m_log.debug("check start. directory=" + m_directory); ArrayList<JobFileCheck> kickList = new ArrayList<JobFileCheck>(); // 1. File directory = new File(m_directory); if (!directory.isDirectory()) { m_log.warn(m_directory + " is not directory"); return; } File[] files = directory.listFiles(); if (files == null) { m_log.warn(m_directory + " does not have a reference permission"); return; } ArrayList<File> fileList = new ArrayList<File>(); for (File file : files) { if (!file.isFile()) { m_log.debug(file.getName() + " is not file"); continue; } fileList.add(file); } // 2. ?? ArrayList<String> filenameList = new ArrayList<String>(); for (File file : fileList) { filenameList.add(file.getName()); } for (String filename : fileTimestampCache.keySet()) { if (!filenameList.contains(filename)) { fileTimestampCache.remove(filename); fileTimestampFlagCache.remove(filename); fileSizeCache.remove(filename); fileSizeFlagCache.remove(filename); for (JobFileCheck check : m_jobFileCheckList) { if (check.getEventType() == FileCheckConstant.TYPE_DELETE && matchFile(check, filename)) { m_log.info("kickList.add [" + filename + "] (delete)"); JobFileCheck kick = getCopy(check); kick.setFileName(filename); kickList.add(kick); } } } } // 3. ?? for (File file : fileList) { String filename = file.getName(); Long newTimestamp = file.lastModified(); Long oldTimestamp = fileTimestampCache.get(filename); if (oldTimestamp == null) { fileTimestampCache.put(filename, newTimestamp); fileTimestampFlagCache.put(filename, false); for (JobFileCheck check : m_jobFileCheckList) { if (check.getEventType() == FileCheckConstant.TYPE_CREATE && matchFile(check, filename)) { m_log.info("kickList.add [" + filename + "] (create)"); JobFileCheck kick = getCopy(check); kick.setFileName(filename); kickList.add(kick); } } } else if (!oldTimestamp.equals(newTimestamp)) { m_log.info("timestamp : " + oldTimestamp + "->" + newTimestamp + " (" + filename + ")"); fileTimestampCache.put(filename, newTimestamp); fileTimestampFlagCache.put(filename, true); } else { if (fileTimestampFlagCache.get(filename) != null && fileTimestampFlagCache.get(filename)) { // ????????? for (JobFileCheck check : m_jobFileCheckList) { if (check.getEventType() == FileCheckConstant.TYPE_MODIFY && check.getModifyType() == FileCheckConstant.TYPE_MODIFY_TIMESTAMP && matchFile(check, filename)) { m_log.info("kickList.add [" + filename + "] (timestamp)"); JobFileCheck kick = getCopy(check); kick.setFileName(filename); kickList.add(kick); } } } fileTimestampFlagCache.put(filename, false); } } // 4. ?? for (File file : fileList) { String filename = file.getName(); RandomAccessFileWrapper fr = null; try { fr = new RandomAccessFileWrapper(file, "r"); Long newSize = fr.length(); Long oldSize = fileSizeCache.get(filename); if (oldSize == null) { fileSizeCache.put(filename, newSize); fileSizeFlagCache.put(filename, false); } else if (!oldSize.equals(newSize)) { m_log.info("size : " + oldSize + "->" + newSize + " (" + filename + ")"); fileSizeCache.put(filename, newSize); fileSizeFlagCache.put(filename, true); } else { if (fileSizeFlagCache.get(filename) != null && fileSizeFlagCache.get(filename)) { // ????????? for (JobFileCheck check : m_jobFileCheckList) { if (check.getEventType() == FileCheckConstant.TYPE_MODIFY && check.getModifyType() == FileCheckConstant.TYPE_MODIFY_FILESIZE && matchFile(check, filename)) { m_log.info("kickList.add [" + filename + "] (filesize)"); JobFileCheck kick = getCopy(check); kick.setFileName(filename); kickList.add(kick); } } } fileSizeFlagCache.put(filename, false); } } catch (IOException e) { m_log.info("run() : IOException: " + e.getMessage()); } catch (Exception e) { m_log.warn("run() : IOException: " + e.getMessage()); } finally { if (fr != null) { try { fr.close(); } catch (final Exception e) { m_log.debug("run() : " + e.getMessage()); } } } } // 1?????? if (initFlag) { initFlag = false; return; } // 5. Job? for (JobFileCheck jobFileCheck : kickList) { m_log.info("kick " + jobFileCheck.getId()); String calendarId = jobFileCheck.getCalendarId(); CalendarInfo calendarInfo = jobFileCheck.getCalendarInfo(); boolean run = true; if (calendarId != null && calendarInfo == null) { m_log.info("unknown error : id=" + jobFileCheck.getId() + "calendarId=" + calendarId); } if (calendarInfo != null) { run = CalendarWSUtil.isRun(calendarInfo); } if (!run) { m_log.info("not exec(calendar) : id=" + jobFileCheck.getId() + "calendarId=" + calendarId); continue; } try { String sessionId = jobFileCheckResultRetry(jobFileCheck); String jobunitId = jobFileCheck.getJobunitId(); String jobId = jobFileCheck.getJobId(); m_log.info("jobFileCheckResult sessionId=" + sessionId + ", jobunitId=" + jobunitId + ", jobId=" + jobId); } catch (Exception e) { m_log.warn("run(jobFileCheckResult) : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); } } }
From source file:com.viettel.util.excel.DynamicExport.java
public String getEmployeeNumber(List<Object[]> list, Long entityId) { for (Object[] a : list) { if (entityId.equals((Long) a[0])) { return ((Long) a[1]).toString(); }/*from w w w . j a v a 2 s . co m*/ } return ""; }
From source file:org.openmeetings.app.data.user.Organisationmanagement.java
/** * /*from w w w. j a v a 2s .c om*/ * @param user_id * @param usersToStore * @return * @throws Exception */ private boolean checkUserShouldBeStored(Long user_id, @SuppressWarnings("rawtypes") LinkedHashMap usersToStore) throws Exception { for (Iterator<?> it2 = usersToStore.keySet().iterator(); it2.hasNext();) { Integer key = (Integer) it2.next(); Long usersIdToCheck = Long.valueOf(usersToStore.get(key).toString()).longValue(); log.debug("usersIdToCheck: " + usersIdToCheck); if (user_id.equals(usersIdToCheck)) { return true; } } return false; }
From source file:org.openmeetings.axis.services.CalendarWebService.java
/** * Get the appointments (calendar events) for the given requestUserId <br/> * The TimeZone can be either given by the Id of the timezone in the table * "om_timezone" with the param timeZoneIdA <br/> * Or with the java name of the TimeZone in the param javaTimeZoneName * /*w w w .j a v a2s.c o m*/ * @param SID * a valid user id * @param firstDayInWeek * the first dayin week, 0=Sunday, 1=Monday, ... * @param startDate * the date it should start with * @param requestUserId * the user id the calendar events are requested, if it is not * the user id of the SID then the SID's user needs to have the * right to watch those events * @param omTimeZoneId * the id of the timezone (alternativly use javaTimeZoneName) * @param javaTimeZoneName * the name of the java time zone, see <a * href="http://en.wikipedia.org/wiki/Time_zone#Java" * target="_blank" * >http://en.wikipedia.org/wiki/Time_zone#Java</a> * @return * @throws AxisFault */ public List<Week> getAppointmentsByWeekCalendar(String SID, int firstDayInWeek, Date startDate, Long requestUserId, Long omTimeZoneId, String javaTimeZoneName) throws AxisFault { try { Long users_id = sessionManagement.checkSession(SID); Long user_level = userManagement.getUserLevelByID(users_id); if (authLevelManagement.checkUserLevel(user_level)) { if (!requestUserId.equals(users_id)) { UserContacts userContacts = userContactsDaoImpl.getUserContactByShareCalendar(requestUserId, true, users_id); if (userContacts == null) { throw new Exception("Your are not allowed to see this calendar"); } } TimeZone timezone = null; if (javaTimeZoneName != null && !javaTimeZoneName.isEmpty()) { timezone = TimeZone.getTimeZone(javaTimeZoneName); if (timezone == null) { throw new Exception("Invalid javaTimeZoneName given"); } } if (omTimeZoneId > 0) { timezone = timezoneUtil.getTimezoneByOmTimeZoneId(omTimeZoneId); } if (timezone == null) { throw new Exception("No timeZone given"); } // Calculate the first day of a calendar based on the first // showing day of the week List<Week> weeks = new ArrayList<Week>(6); Calendar currentDate = Calendar.getInstance(); currentDate.setTime(startDate); currentDate.set(Calendar.HOUR_OF_DAY, 12); // set to 12 to prevent timezone issues currentDate.set(Calendar.DATE, 1); int currentWeekDay = currentDate.get(Calendar.DAY_OF_WEEK); Calendar startWeekDay = Calendar.getInstance(); log.debug("currentWeekDay -- " + currentWeekDay); log.debug("firstDayInWeek -- " + firstDayInWeek); if (currentWeekDay == firstDayInWeek) { log.debug("ARE equal currentWeekDay -- "); startWeekDay.setTime(currentDate.getTime()); } else { startWeekDay .setTimeInMillis((currentDate.getTimeInMillis() - ((currentWeekDay - 1) * 86400000))); if (currentWeekDay > firstDayInWeek) { startWeekDay.setTimeInMillis(startWeekDay.getTimeInMillis() + (firstDayInWeek * 86400000)); } else { startWeekDay.setTimeInMillis(startWeekDay.getTimeInMillis() - (firstDayInWeek * 86400000)); } } Calendar calStart = Calendar.getInstance(timezone); calStart.setTime(startWeekDay.getTime()); Calendar calEnd = Calendar.getInstance(timezone); // every month page in our calendar shows 42 days calEnd.setTime(new Date(startWeekDay.getTime().getTime() + (42L * 86400000L))); List<Appointment> appointments = appointmentDao.getAppointmentsByRange(requestUserId, calStart.getTime(), calEnd.getTime()); log.debug("startWeekDay 2" + startWeekDay.getTime()); log.debug("startWeekDay Number of appointments " + appointments.size()); long z = 0; for (int k = 0; k < 6; k++) { // 6 weeks per monthly summary Week week = new Week(); for (int i = 0; i < 7; i++) { // 7 days a week Calendar tCal = Calendar.getInstance(timezone); tCal.setTimeInMillis(startWeekDay.getTimeInMillis() + (z * 86400000L)); Day day = new Day(tCal.getTime()); for (Appointment appointment : appointments) { if (appointment.appointmentStartAsCalendar(timezone).get(Calendar.MONTH) == tCal .get(Calendar.MONTH) && appointment.appointmentStartAsCalendar(timezone).get(Calendar.DATE) == tCal .get(Calendar.DATE)) { day.getAppointments().add(new AppointmentDTO(appointment, timezone)); } } week.getDays().add(day); z++; } weeks.add(week); } return weeks; } } catch (Exception err) { log.error("[getAppointmentReminderTypList]", err); throw new AxisFault(err.getMessage()); } return null; }
From source file:com.mobileman.projecth.business.UserServiceTest.java
/** * /*from w w w .jav a 2 s.c om*/ * @throws Exception */ @Test public void addAndRemoveDiseasesToUser() throws Exception { DiseaseService diseaseService = (DiseaseService) applicationContext.getBean(ComponentNames.DISEASE_SERVICE); assertNotNull(diseaseService); DiseaseGroup diseaseGroup = new DiseaseGroup(); diseaseGroup.setCode("code"); diseaseGroup.setName("name"); Long diseaseGroupId = diseaseService.saveGroup(diseaseGroup); assertNotNull(diseaseGroupId); assertTrue(!diseaseGroupId.equals(0L)); DiseaseSubgroup diseaseSubgroup = new DiseaseSubgroup(); diseaseSubgroup.setCode("code"); diseaseSubgroup.setName("name"); diseaseSubgroup.setDiseaseGroup(diseaseGroup); Long diseaseSubgroupId = diseaseService.saveSubgroup(diseaseSubgroup); assertNotNull(diseaseSubgroupId); assertTrue(!diseaseSubgroupId.equals(0L)); Disease disease1 = new Disease(); disease1.setCode("code1"); disease1.setName("name1"); disease1.setImageName("imageName1"); disease1.setDiseaseSubgroup(diseaseSubgroup); Disease disease2 = new Disease(); disease2.setCode("code2"); disease2.setName("name2"); disease2.setImageName("imageName2"); disease2.setDiseaseSubgroup(diseaseSubgroup); Long diseaseId1 = diseaseService.save(disease1); assertNotNull(diseaseId1); assertTrue(!diseaseId1.equals(0L)); Long diseaseId2 = diseaseService.save(disease2); assertNotNull(diseaseId2); assertTrue(!diseaseId2.equals(0L)); List<Disease> diseases = diseaseService.findAll(); String name1 = "name1"; String name2 = "name2"; String login1 = "login1"; String login2 = "login2"; String password = "12345"; String email1 = "email1@email.com"; String email2 = "email2@email.com"; Patient patient1 = new Patient(); patient1.setName(new Name(name1, null)); Long userId1 = userService.register(patient1, login1, password, email1, null, "projecth.com"); User user1 = userService.findById(userId1); userService.activateUserAccount(user1.getActivationUid()); user1 = userService.login(login1, password); assertNotNull(user1); Patient patient2 = new Patient(); patient2.setName(new Name(name2, null)); Long userId2 = userService.register(patient2, login2, password, email2, null, "projecth.com"); User user2 = userService.findById(userId2); userService.activateUserAccount(user2.getActivationUid()); user2 = userService.login(login2, password); assertNotNull(user2); userService.addDiseasesToUser(user1.getId(), diseases); user1 = userService.findById(user1.getId()); assertTrue(user1.getDiseases().size() == diseases.size()); List<Disease> diseases2 = new ArrayList<Disease>(); Disease disease20 = diseases.get(0); diseases2.add(disease20); userService.addDiseasesToUser(user2.getId(), diseases2); user2 = userService.findById(user2.getId()); assertTrue(user2.getDiseases().size() == diseases2.size()); int oldSize = user2.getDiseases().size(); userService.removeDiseasesFromUser(user2.getId(), diseases2); user2 = userService.findById(user2.getId()); assertTrue(user2.getDiseases().size() == oldSize - diseases2.size()); }
From source file:org.apache.fineract.portfolio.shareproducts.serialization.ShareProductDataSerializer.java
public ShareProduct validateAndCreate(JsonCommand jsonCommand) { if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); }// w ww. java2 s . com final Type typeOfMap = new TypeToken<Map<String, Object>>() { }.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), ShareProductApiConstants.supportedParametersForCreate); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("sharesproduct"); JsonElement element = jsonCommand.parsedJson(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject()); final String productName = this.fromApiJsonHelper .extractStringNamed(ShareProductApiConstants.name_paramname, element); baseDataValidator.reset().parameter(ShareProductApiConstants.name_paramname).value(productName).notBlank() .notExceedingLengthOf(200); final String shortName = this.fromApiJsonHelper .extractStringNamed(ShareProductApiConstants.shortname_paramname, element); baseDataValidator.reset().parameter(ShareProductApiConstants.shortname_paramname).value(shortName) .notBlank().notExceedingLengthOf(4); String description = null; if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.description_paramname, element)) { description = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.description_paramname, element); } String externalId = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.externalid_paramname, element); // baseDataValidator.reset().parameter(ShareProductApiConstants.externalid_paramname).value(externalId).notBlank(); Long totalNumberOfShares = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.totalshares_paramname, element); baseDataValidator.reset().parameter(ShareProductApiConstants.totalshares_paramname) .value(totalNumberOfShares).notNull().longGreaterThanZero(); final Long sharesIssued = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.totalsharesissued_paramname, element); if (sharesIssued != null && totalNumberOfShares != null && sharesIssued > totalNumberOfShares) { baseDataValidator.reset().parameter(ShareProductApiConstants.totalsharesissued_paramname) .value(sharesIssued).failWithCodeNoParameterAddedToErrorCode( "sharesIssued.cannot.be.greater.than.totalNumberOfShares"); } final String currencyCode = this.fromApiJsonHelper .extractStringNamed(ShareProductApiConstants.currency_paramname, element); final Integer digitsAfterDecimal = this.fromApiJsonHelper .extractIntegerWithLocaleNamed(ShareProductApiConstants.digitsafterdecimal_paramname, element); final Integer inMultiplesOf = this.fromApiJsonHelper .extractIntegerWithLocaleNamed(ShareProductApiConstants.inmultiplesof_paramname, element); final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); final BigDecimal unitPrice = this.fromApiJsonHelper .extractBigDecimalNamed(ShareProductApiConstants.unitprice_paramname, element, locale); baseDataValidator.reset().parameter(ShareProductApiConstants.unitprice_paramname).value(unitPrice).notNull() .positiveAmount(); BigDecimal shareCapitalValue = BigDecimal.ONE; if (sharesIssued != null && unitPrice != null) { shareCapitalValue = BigDecimal.valueOf(sharesIssued).multiply(unitPrice); } Integer accountingRule = this.fromApiJsonHelper .extractIntegerNamed(ShareProductApiConstants.accountingRuleParamName, element, locale); baseDataValidator.reset().parameter(ShareProductApiConstants.accountingRuleParamName).value(accountingRule) .notNull().integerGreaterThanZero(); AccountingRuleType accountingRuleType = null; if (accountingRule != null) { accountingRuleType = AccountingRuleType.fromInt(accountingRule); } Long minimumClientShares = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.minimumshares_paramname, element); Long nominalClientShares = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.nominaltshares_paramname, element); baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname) .value(nominalClientShares).notNull().longGreaterThanZero(); if (minimumClientShares != null && nominalClientShares != null && !minimumClientShares.equals(nominalClientShares)) { baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname) .value(nominalClientShares).longGreaterThanNumber(minimumClientShares); } Long maximumClientShares = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.maximumshares_paramname, element); if (maximumClientShares != null && nominalClientShares != null && !maximumClientShares.equals(nominalClientShares)) { baseDataValidator.reset().parameter(ShareProductApiConstants.maximumshares_paramname) .value(maximumClientShares).longGreaterThanNumber(nominalClientShares); } Set<ShareProductMarketPrice> marketPriceSet = asembleShareMarketPrice(element); Set<Charge> charges = assembleListOfProductCharges(element, currencyCode); Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed( ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element); Integer minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed( ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale); PeriodFrequencyType minimumActivePeriodType = extractPeriodType( ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, element); if (minimumActivePeriod != null) { baseDataValidator.reset().parameter(ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname) .value(minimumActivePeriodType.getValue()) .integerSameAsNumber(PeriodFrequencyType.DAYS.getValue()); } Integer lockinPeriod = this.fromApiJsonHelper .extractIntegerNamed(ShareProductApiConstants.lockperiod_paramname, element, locale); PeriodFrequencyType lockPeriodType = extractPeriodType( ShareProductApiConstants.lockinperiodfrequencytype_paramname, element); AppUser createdBy = platformSecurityContext.authenticatedUser(); AppUser modifiedBy = createdBy; DateTime createdDate = DateUtils.getLocalDateTimeOfTenant().toDateTime(); DateTime modifiedOn = createdDate; ShareProduct product = new ShareProduct(productName, shortName, description, externalId, currency, totalNumberOfShares, sharesIssued, unitPrice, shareCapitalValue, minimumClientShares, nominalClientShares, maximumClientShares, marketPriceSet, charges, allowdividendsForInactiveClients, lockinPeriod, lockPeriodType, minimumActivePeriod, minimumActivePeriodType, createdBy, createdDate, modifiedBy, modifiedOn, accountingRuleType); for (ShareProductMarketPrice data : marketPriceSet) { data.setShareProduct(product); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } return product; }
From source file:com.gst.portfolio.shareproducts.serialization.ShareProductDataSerializer.java
public ShareProduct validateAndCreate(JsonCommand jsonCommand) { if (StringUtils.isBlank(jsonCommand.json())) { throw new InvalidJsonException(); }//from w w w. j a v a 2s .c o m final Type typeOfMap = new TypeToken<Map<String, Object>>() { }.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(), ShareProductApiConstants.supportedParametersForCreate); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("sharesproduct"); JsonElement element = jsonCommand.parsedJson(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject()); final String productName = this.fromApiJsonHelper .extractStringNamed(ShareProductApiConstants.name_paramname, element); baseDataValidator.reset().parameter(ShareProductApiConstants.name_paramname).value(productName).notBlank() .notExceedingLengthOf(200); final String shortName = this.fromApiJsonHelper .extractStringNamed(ShareProductApiConstants.shortname_paramname, element); baseDataValidator.reset().parameter(ShareProductApiConstants.shortname_paramname).value(shortName) .notBlank().notExceedingLengthOf(4); String description = null; if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.description_paramname, element)) { description = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.description_paramname, element); } String externalId = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.externalid_paramname, element); // baseDataValidator.reset().parameter(ShareProductApiConstants.externalid_paramname).value(externalId).notBlank(); Long totalNumberOfShares = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.totalshares_paramname, element); baseDataValidator.reset().parameter(ShareProductApiConstants.totalshares_paramname) .value(totalNumberOfShares).notNull().longGreaterThanZero(); final Long sharesIssued = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.totalsharesissued_paramname, element); if (sharesIssued != null && totalNumberOfShares != null && sharesIssued > totalNumberOfShares) { baseDataValidator.reset().parameter(ShareProductApiConstants.totalsharesissued_paramname) .value(sharesIssued).failWithCodeNoParameterAddedToErrorCode( "sharesIssued.cannot.be.greater.than.totalNumberOfShares"); } final String currencyCode = this.fromApiJsonHelper .extractStringNamed(ShareProductApiConstants.currency_paramname, element); final Integer digitsAfterDecimal = this.fromApiJsonHelper .extractIntegerWithLocaleNamed(ShareProductApiConstants.digitsafterdecimal_paramname, element); final Integer inMultiplesOf = this.fromApiJsonHelper .extractIntegerWithLocaleNamed(ShareProductApiConstants.inmultiplesof_paramname, element); final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); final BigDecimal unitPrice = this.fromApiJsonHelper .extractBigDecimalNamed(ShareProductApiConstants.unitprice_paramname, element, locale); baseDataValidator.reset().parameter(ShareProductApiConstants.unitprice_paramname).value(unitPrice).notNull() .positiveAmount(); BigDecimal shareCapitalValue = BigDecimal.ONE; if (sharesIssued != null && unitPrice != null) { shareCapitalValue = BigDecimal.valueOf(sharesIssued).multiply(unitPrice); } Integer accountingRule = this.fromApiJsonHelper .extractIntegerNamed(ShareProductApiConstants.accountingRuleParamName, element, locale); baseDataValidator.reset().parameter(ShareProductApiConstants.accountingRuleParamName).value(accountingRule) .notNull().integerGreaterThanZero(); AccountingRuleType accountingRuleType = null; if (accountingRule != null) { accountingRuleType = AccountingRuleType.fromInt(accountingRule); } Long minimumClientShares = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.minimumshares_paramname, element); Long nominalClientShares = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.nominaltshares_paramname, element); baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname) .value(nominalClientShares).notNull().longGreaterThanZero(); if (minimumClientShares != null && nominalClientShares != null && !minimumClientShares.equals(nominalClientShares)) { baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname) .value(nominalClientShares).longGreaterThanNumber(minimumClientShares); } Long maximumClientShares = this.fromApiJsonHelper .extractLongNamed(ShareProductApiConstants.maximumshares_paramname, element); if (maximumClientShares != null && nominalClientShares != null && !maximumClientShares.equals(nominalClientShares)) { baseDataValidator.reset().parameter(ShareProductApiConstants.maximumshares_paramname) .value(maximumClientShares).longGreaterThanNumber(nominalClientShares); } Set<ShareProductMarketPrice> marketPriceSet = asembleShareMarketPrice(element); Set<Charge> charges = assembleListOfProductCharges(element, currencyCode); Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed( ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element); Integer minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed( ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale); PeriodFrequencyType minimumActivePeriodType = extractPeriodType( ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, element); if (minimumActivePeriod != null) { baseDataValidator.reset().parameter(ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname) .value(minimumActivePeriodType.getValue()) .integerSameAsNumber(PeriodFrequencyType.DAYS.getValue()); } Integer lockinPeriod = this.fromApiJsonHelper .extractIntegerNamed(ShareProductApiConstants.lockperiod_paramname, element, locale); PeriodFrequencyType lockPeriodType = extractPeriodType( ShareProductApiConstants.lockinperiodfrequencytype_paramname, element); AppUser createdBy = platformSecurityContext.authenticatedUser(); AppUser modifiedBy = createdBy; DateTime createdDate = DateUtils.getLocalDateTimeOfTenant().toDateTime(); DateTime modifiedOn = createdDate; ShareProduct product = new ShareProduct(productName, shortName, description, externalId, currency, totalNumberOfShares, sharesIssued, unitPrice, shareCapitalValue, minimumClientShares, nominalClientShares, maximumClientShares, marketPriceSet, charges, allowdividendsForInactiveClients, lockinPeriod, lockPeriodType, minimumActivePeriod, minimumActivePeriodType, createdBy, createdDate, modifiedBy, modifiedOn, accountingRuleType); for (ShareProductMarketPrice data : marketPriceSet) { data.setShareProduct(product); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } return product; }