List of usage examples for java.util Calendar before
public boolean before(Object when)
Calendar
represents a time before the time represented by the specified Object
. From source file:pl.psnc.dl.wf4ever.sms.SemanticMetadataServiceImplTest.java
/** * Test method for/* w w w .j a v a 2 s .c o m*/ * {@link pl.psnc.dl.wf4ever.sms.SemanticMetadataServiceImpl#getManifest(java.net.URI, org.openrdf.rio.RDFFormat)} . * * @throws IOException * @throws SQLException * @throws NamingException * @throws ClassNotFoundException * @throws URISyntaxException */ @Test public final void testGetManifest() throws IOException, ClassNotFoundException, NamingException, SQLException, URISyntaxException { SemanticMetadataService sms = new SemanticMetadataServiceImpl(userProfile, false); try { Assert.assertNull("Returns null when manifest does not exist", sms.getManifest(researchObject, RDFFormat.RDFXML)); Calendar before = Calendar.getInstance(); sms.createResearchObject(researchObject); Calendar after = Calendar.getInstance(); OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); model.read(sms.getManifest(researchObject, RDFFormat.RDFXML), null); Individual manifest = model.getIndividual(researchObject.getManifestUri().toString()); Individual ro = model.getIndividual(researchObject.getUri().toString()); Assert.assertNotNull("Manifest must contain ro:Manifest", manifest); Assert.assertNotNull("Manifest must contain ro:ResearchObject", ro); Assert.assertTrue("Manifest must be a ro:Manifest", manifest.hasRDFType(RO.NAMESPACE + "Manifest")); Assert.assertTrue("RO must be a ro:ResearchObject", ro.hasRDFType(RO.NAMESPACE + "ResearchObject")); Literal createdLiteral = manifest.getPropertyValue(DCTerms.created).asLiteral(); Assert.assertNotNull("Manifest must contain dcterms:created", createdLiteral); Assert.assertEquals("Date type is xsd:dateTime", XSDDatatype.XSDdateTime, createdLiteral.getDatatype()); Calendar created = ((XSDDateTime) createdLiteral.getValue()).asCalendar(); Assert.assertTrue("Created is a valid date", !before.after(created) && !after.before(created)); // Resource creatorResource = manifest.getPropertyResourceValue(DCTerms.creator); // Assert.assertNotNull("Manifest must contain dcterms:creator", creatorResource); // Individual creator = creatorResource.as(Individual.class); // Assert.assertTrue("Creator must be a foaf:Agent", creator.hasRDFType("http://xmlns.com/foaf/0.1/Agent")); // Assert.assertEquals("Creator name must be correct", "RODL", creator.getPropertyValue(foafName).asLiteral() // .getString()); Resource creatorResource = ro.getPropertyResourceValue(DCTerms.creator); Assert.assertNotNull("RO must contain dcterms:creator", creatorResource); OntModel userModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM); userModel.read(sms.getNamedGraph(new URI(creatorResource.getURI()), RDFFormat.RDFXML), ""); Individual creator = userModel.getIndividual(creatorResource.getURI()); Assert.assertTrue("Creator must be a foaf:Agent", creator.hasRDFType("http://xmlns.com/foaf/0.1/Agent")); Assert.assertEquals("Creator name must be correct", userProfile.getName(), creator.getPropertyValue(FOAF.name).asLiteral().getString()); } finally { sms.close(); } }
From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java
private Validator getTransferValidator(final TransferDTO transfer) { final Validator validator = new Validator("transfer"); // as currency is sometimes not set on the DTO, we get it from the TT in stead of directly from the DTO final TransferType tt = fetchService.fetch(transfer.getTransferType(), RelationshipHelper.nested(TransferType.Relationships.FROM, AccountType.Relationships.CURRENCY, Currency.Relationships.A_RATE_PARAMETERS, Currency.Relationships.D_RATE_PARAMETERS)); final Currency currency = tt.getCurrency(); // if rates enabled, it is not allowed to have a date in the past. if (currency.isEnableARate() || currency.isEnableDRate()) { final Calendar now = Calendar.getInstance(); // make a few minutes earlier, because if the transfer's date has just before been set to Calendar.getInstance(), it may already be a // few milliseconds or even seconds later. now.add(Calendar.MINUTE, -4); final Calendar date = transfer.getDate(); if (date != null && date.before(now)) { validator.general(new NoPastDateWithRatesValidator()); }/*w w w .java 2 s. c om*/ } else { validator.property("date").key("payment.manualDate").pastOrToday(); } validator.property("fromOwner").required(); validator.property("toOwner").required(); addAmountValidator(validator, tt); validator.property("transferType").key("transfer.type").required(); validator.property("description").maxLength(1000); validator.property("traceNumber").add(new TraceNumberValidation()); if (transfer.getTransferType() != null) { // Custom fields validator.chained(new DelegatingValidator(new DelegatingValidator.DelegateSource() { @Override public Validator getValidator() { return paymentCustomFieldService.getValueValidator(transfer.getTransferType()); } })); } return validator; }
From source file:nl.strohalm.cyclos.services.transactions.LoanServiceImpl.java
@Override public LoanRepaymentAmountsDTO getLoanPaymentAmount(final LoanPaymentDTO dto) { final LoanRepaymentAmountsDTO ret = new LoanRepaymentAmountsDTO(); Calendar date = dto.getDate(); if (date == null) { date = Calendar.getInstance(); }/*from w ww .j a v a 2 s . co m*/ final Loan loan = fetchService.fetch(dto.getLoan(), Loan.Relationships.TRANSFER, Loan.Relationships.PAYMENTS); LoanPayment payment = fetchService.fetch(dto.getLoanPayment()); if (payment == null) { payment = loan.getFirstOpenPayment(); } ret.setLoanPayment(payment); // Update the dto with fetched values dto.setLoan(loan); dto.setLoanPayment(payment); if (payment != null) { payment = fetchService.fetch(payment, LoanPayment.Relationships.TRANSFERS); final BigDecimal paymentAmount = payment.getAmount(); BigDecimal remainingAmount = paymentAmount; Calendar expirationDate = payment.getExpirationDate(); Calendar lastPaymentDate = (Calendar) expirationDate.clone(); expirationDate = DateUtils.truncate(expirationDate, Calendar.DATE); final LoanParameters parameters = loan.getParameters(); Collection<Transfer> transfers = payment.getTransfers(); if (transfers == null) { transfers = Collections.emptyList(); } final BigDecimal expirationDailyInterest = CoercionHelper.coerce(BigDecimal.class, parameters.getExpirationDailyInterest()); final LocalSettings localSettings = settingsService.getLocalSettings(); final MathContext mathContext = localSettings.getMathContext(); for (final Transfer transfer : transfers) { Calendar trfDate = transfer.getDate(); trfDate = DateUtils.truncate(trfDate, Calendar.DATE); final BigDecimal trfAmount = transfer.getAmount(); BigDecimal actualAmount = trfAmount; final int diffDays = (int) ((trfDate.getTimeInMillis() - expirationDate.getTimeInMillis()) / DateUtils.MILLIS_PER_DAY); if (diffDays > 0 && expirationDailyInterest != null) { // Apply interest actualAmount = actualAmount.subtract(remainingAmount.multiply(new BigDecimal(diffDays)) .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext))); } remainingAmount = remainingAmount.subtract(actualAmount); lastPaymentDate = (Calendar) trfDate.clone(); } date = DateHelper.truncate(date); BigDecimal remainingAmountAtDate = remainingAmount; final int diffDays = (int) ((date.getTimeInMillis() - (expirationDate.before(lastPaymentDate) ? lastPaymentDate.getTimeInMillis() : expirationDate.getTimeInMillis())) / DateUtils.MILLIS_PER_DAY); if (diffDays > 0 && expirationDailyInterest != null) { // Apply interest remainingAmountAtDate = remainingAmountAtDate.add(remainingAmount.multiply(new BigDecimal(diffDays)) .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext))); } final Amount expirationFee = parameters.getExpirationFee(); if (expirationFee != null && (remainingAmountAtDate.compareTo(BigDecimal.ZERO) == 1) && expirationDate.before(date) && (expirationFee.getValue().compareTo(BigDecimal.ZERO) == 1)) { // Apply expiration fee remainingAmountAtDate = remainingAmountAtDate.add(expirationFee.apply(remainingAmount)); } // Round the result ret.setRemainingAmountAtExpirationDate(localSettings.round(remainingAmount)); ret.setRemainingAmountAtDate(localSettings.round(remainingAmountAtDate)); } return ret; }
From source file:mvc.OrderController.java
private String getJsonStringByDateList(Date dateFrom, Date dateTo, List<Map> listByDates) { String json = ""; Calendar cl = Calendar.getInstance(); cl.setTime(dateFrom);/*ww w. jav a 2 s .c o m*/ setStartOfDay(cl); Calendar end = Calendar.getInstance(); end.setTime(dateTo); setStartOfDay(end); // ? ? for (; cl.before(end) || cl.equals(end); cl.add(Calendar.DAY_OF_MONTH, 1)) { int year = cl.get(Calendar.YEAR); int month = cl.get(Calendar.MONTH) + 1; int day = cl.get(Calendar.DAY_OF_MONTH); json += getJsonByDate(listByDates, day, month, year); } return json; }
From source file:org.atricore.idbus.capabilities.sso.main.sp.producers.AssertionConsumerProducer.java
private void validateAssertionConditions(ResponseType response, ConditionsType conditions) throws SSOException, SSOResponseException { if (conditions == null) return;//w ww. ja v a 2 s . c o m long tolerance = ((AbstractSSOMediator) channel.getIdentityMediator()).getTimestampValidationTolerance(); Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); if (conditions.getConditionOrAudienceRestrictionOrOneTimeUse() == null && conditions.getNotBefore() == null && conditions.getNotOnOrAfter() == null) { return; } logger.debug("Current time (UTC): " + utcCalendar.toString()); XMLGregorianCalendar notBeforeUTC = null; XMLGregorianCalendar notOnOrAfterUTC = null; if (conditions.getNotBefore() != null) { //normalize to UTC logger.debug("Conditions.NotBefore: " + conditions.getNotBefore()); notBeforeUTC = conditions.getNotBefore().normalize(); logger.debug("Conditions.NotBefore normalized: " + notBeforeUTC.toString()); if (!notBeforeUTC.isValid()) { throw new SSOResponseException(response, StatusCode.TOP_REQUESTER, StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_UTC_VALUE, notBeforeUTC.toString()); } else { Calendar notBefore = notBeforeUTC.toGregorianCalendar(); notBefore.add(Calendar.MILLISECOND, (int) tolerance * -1); if (utcCalendar.before(notBefore)) throw new SSOResponseException(response, StatusCode.TOP_REQUESTER, StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_BEFORE_VIOLATED, notBeforeUTC.toString()); } } // Make sure that the NOT ON OR AFTER is not violated, give a five minutes tolerance (should be configurable) if (conditions.getNotOnOrAfter() != null) { //normalize to UTC logger.debug("Conditions.NotOnOrAfter: " + conditions.getNotOnOrAfter().toString()); notOnOrAfterUTC = conditions.getNotOnOrAfter().normalize(); logger.debug("Conditions.NotOnOrAfter normalized: " + notOnOrAfterUTC.toString()); if (!notOnOrAfterUTC.isValid()) { throw new SSOResponseException(response, StatusCode.TOP_REQUESTER, StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_UTC_VALUE, notOnOrAfterUTC.toString()); } else { // diff in millis Calendar notOnOrAfter = notOnOrAfterUTC.toGregorianCalendar(); notOnOrAfter.add(Calendar.MILLISECOND, (int) tolerance); if (utcCalendar.after(notOnOrAfter)) throw new SSOResponseException(response, StatusCode.TOP_REQUESTER, StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_ONORAFTER_VIOLATED, notOnOrAfterUTC.toString()); } } if (notBeforeUTC != null && notOnOrAfterUTC != null && notOnOrAfterUTC.compare(notBeforeUTC) <= 0) { throw new SSOResponseException(response, StatusCode.TOP_REQUESTER, StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_CONDITION, "'Not On or After' earlier that 'Not Before'"); } // Our SAMLR2 Enityt ID should be part of the audience CircleOfTrustMemberDescriptor sp = this.getCotMemberDescriptor(); MetadataEntry spMd = sp.getMetadata(); if (spMd == null || spMd.getEntry() == null) throw new SSOException("No metadata descriptor found for SP " + sp); EntityDescriptorType md = null; if (spMd.getEntry() instanceof EntityDescriptorType) { md = (EntityDescriptorType) spMd.getEntry(); } else throw new SSOException("Unsupported Metadata type " + md + ", SAML 2 Metadata expected"); if (conditions.getConditionOrAudienceRestrictionOrOneTimeUse() != null) { boolean audienceRestrictionValid = false; boolean spInAllAudiences = false; boolean initState = true; for (ConditionAbstractType conditionAbs : conditions.getConditionOrAudienceRestrictionOrOneTimeUse()) { if (conditionAbs instanceof AudienceRestrictionType) { AudienceRestrictionType audienceRestriction = (AudienceRestrictionType) conditionAbs; if (audienceRestriction.getAudience() != null) { boolean spInAudience = false; for (String audience : audienceRestriction.getAudience()) { if (audience.equals(md.getEntityID())) { spInAudience = true; break; } } spInAllAudiences = (initState ? spInAudience : spInAllAudiences && spInAudience); initState = false; } } audienceRestrictionValid = audienceRestrictionValid || spInAllAudiences; } if (!audienceRestrictionValid) { logger.error("SP is not in Audience list."); throw new SSOResponseException(response, StatusCode.TOP_REQUESTER, StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_IN_AUDIENCE); } } }
From source file:grupob.TipoProceso.java
public TipoProceso() { initComponents();/*from w w w . j av a 2 s . c o m*/ initInstitucional(); // listaRegiones.add(new Region(1,"Lima",15000)); // listaRegiones.add(new Region(1,"Arequipa",10000)); // listaRegiones.add(new Region(1,"Junin",12000)); TipoProcesoVotacion tipoNacional = Manager.queryProcesoById(1); TipoProcesoVotacion tipoRegional = Manager.queryProcesoById(2); TipoProcesoVotacion tipoDistrital = Manager.queryProcesoById(3); Calendar cal = Calendar.getInstance(); Date dateActual = cal.getTime(); textConfGeneral.setText(Recorte.rutaGeneral); textConfHuellas.setText(Recorte.rutaHuella); textConfFirmas.setText(Recorte.rutaFirma); /* Recorte.rutaGeneral = FramePrincipal.rutaGeneral; Recorte.rutaHuella = FramePrincipal.rutaHuella; Recorte.rutaFirma = FramePrincipal.rutaFirma;*/ if (tipoNacional != null && tipoNacional.getId() != 0) { if (!tipoNacional.getFechaInicio2().after(dateActual)) { fechai1Nacional.setDate(tipoNacional.getFechaInicio1().getTime()); fechai2Nacional.setDate(tipoNacional.getFechaInicio2().getTime()); fechaf1Nacional.setDate(tipoNacional.getFechaFin1().getTime()); fechaf2Nacional.setDate(tipoNacional.getFechaFin2().getTime()); } if ((tipoNacional.getFechaInicio1().before(dateActual)) && (cal.before(tipoNacional.getFechaFin2()))) { botonGuardarNacional.setEnabled(false); } if (tipoNacional.getFechaFin2().before(dateActual)) { botonGuardarNacional.setEnabled(true); } } if (tipoRegional != null && tipoRegional.getId() != 0) { if (!tipoRegional.getFechaInicio2().after(dateActual)) { fechai1Regiones.setDate(tipoRegional.getFechaInicio1().getTime()); fechai2Regiones.setDate(tipoRegional.getFechaInicio2().getTime()); fechaf1Regiones.setDate(tipoRegional.getFechaFin1().getTime()); fechaf2Regiones.setDate(tipoRegional.getFechaFin2().getTime()); porcentajeRegional.setText("" + tipoRegional.getPorcentajeMinimo() * 100); } if ((tipoRegional.getFechaInicio1().before(dateActual)) && (cal.before(tipoRegional.getFechaFin2()))) { botonGuardarRegional.setEnabled(false); } if (tipoRegional.getFechaFin2().before(dateActual)) { botonGuardarRegional.setEnabled(true); } } if (tipoDistrital != null && tipoDistrital.getId() != 0) { if (!tipoRegional.getFechaInicio2().after(dateActual)) { fechai1Distritos.setDate(tipoDistrital.getFechaInicio1().getTime()); fechai2Distritos.setDate(tipoDistrital.getFechaInicio2().getTime()); fechaf1Distritos.setDate(tipoDistrital.getFechaFin1().getTime()); fechaf2Distritos.setDate(tipoDistrital.getFechaFin2().getTime()); porcentajeDistrital.setText("" + tipoDistrital.getPorcentajeMinimo() * 100); } if ((tipoDistrital.getFechaInicio1().before(dateActual)) && (cal.before(tipoDistrital.getFechaFin2()))) { botonGuardarDistrital.setEnabled(false); // addRowRegional.setEnabled(false); // jTable6.setEnabled(false); } if (tipoDistrital.getFechaFin2().before(dateActual)) { botonGuardarDistrital.setEnabled(true); // addRowRegional.setEnabled(true); } } agregarDatos(); agregarDatosDistritos(); if (listaRegiones != null) { jTableRegiones.getColumn("Eliminar").setCellRenderer(new ButtonRenderer()); jTableRegiones.getColumn("Eliminar").setCellEditor(new botonEliminarRegiones()); } if (listaDistritos != null) { jTableDistritos.getColumn("Eliminar").setCellRenderer(new ButtonRenderer()); jTableDistritos.getColumn("Eliminar").setCellEditor(new botonEliminarDistritos()); } TableColumn sColumn = jTableDistritos.getColumnModel().getColumn(2); ArrayList<Region> lReg = Manager.queryAllRegion(); JComboBox comboBox = new JComboBox(); for (int i = 0; i < lReg.size(); i++) { comboBox.addItem(lReg.get(i).getNombre()); } sColumn.setCellEditor(new DefaultCellEditor(comboBox)); TableColumn instColumn = tblInstitucional.getColumnModel().getColumn(2); ArrayList<Local> lLoc = Manager.queryAllLocales(); JComboBox comboBoxLocal = new JComboBox(); for (int i = 0; i < lLoc.size(); i++) { comboBoxLocal.addItem(lLoc.get(i).getNombre()); } instColumn.setCellEditor(new DefaultCellEditor(comboBoxLocal)); ChangeListener changeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { JTabbedPane sourceTabbedPane = (JTabbedPane) e.getSource(); int index = sourceTabbedPane.getSelectedIndex(); switch (index) { case 3: cargarDatosLocal(); return; default: return; } } }; jconfiguracion.addChangeListener(changeListener); }
From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java
private Validator getProjectionValidator() { final Validator projectionValidator = new Validator("transfer"); projectionValidator.property("paymentCount").required().positiveNonZero().add(new PropertyValidation() { private static final long serialVersionUID = 5022911381764849941L; @Override//w ww .j a v a2 s .c o m public ValidationError validate(final Object object, final Object property, final Object value) { final Integer paymentCount = (Integer) value; if (paymentCount == null) { return null; } final ProjectionDTO dto = (ProjectionDTO) object; final AccountOwner from = dto.getFrom(); if (from instanceof Member) { final Member member = fetchService.fetch((Member) from, Element.Relationships.GROUP); final int maxSchedulingPayments = member.getMemberGroup().getMemberSettings() .getMaxSchedulingPayments(); return CompareToValidation.lessEquals(maxSchedulingPayments).validate(object, property, value); } return null; } }); projectionValidator.property("amount").required().positiveNonZero(); projectionValidator.property("firstExpirationDate").key("transfer.firstPaymentDate").required() .add(new PropertyValidation() { private static final long serialVersionUID = -3612786027250751763L; @Override public ValidationError validate(final Object object, final Object property, final Object value) { final Calendar firstDate = CoercionHelper.coerce(Calendar.class, value); if (firstDate == null) { return null; } if (firstDate.before(DateHelper.truncate(Calendar.getInstance()))) { return new InvalidError(); } return null; } }); projectionValidator.property("recurrence.number").key("transfer.paymentEvery").required().between(1, 100); projectionValidator.property("recurrence.field").key("transfer.paymentEvery").required() .anyOf(TimePeriod.Field.DAYS, TimePeriod.Field.WEEKS, TimePeriod.Field.MONTHS); return projectionValidator; }
From source file:com.aurel.track.report.dashboard.BurnDownChart.java
public SortedMap<Integer, SortedMap<Integer, Double>> calculateEarnedValuesDependingOnEffortType( SortedMap<Integer, SortedMap<Integer, Double>> yearToIntervalToPlannedValue, Integer timeInterval, Set<Integer> finalStates, Integer selectedEffortType) { SortedMap<Integer, SortedMap<Integer, Double>> yearToIntervalToEarnedValue = new TreeMap<Integer, SortedMap<Integer, Double>>(); if (reportBeanWithHistoryList != null) { Calendar calendarStartDate = Calendar.getInstance(); Calendar calendarEndDate = Calendar.getInstance(); Calendar calendar = Calendar.getInstance(); //to avoid that the last days of the year to be taken as the first //week of the now year but the year remains the old one int calendarInterval = EarnedValueDatasource.getCalendarInterval(timeInterval); for (ReportBeanWithHistory reportBeanWithHistory : reportBeanWithHistoryList) { TWorkItemBean workItemBean = reportBeanWithHistory.getWorkItemBean(); Date startDate = workItemBean.getStartDate(); Date endDate = workItemBean.getEndDate(); if (startDate == null || endDate == null) { continue; }/*w w w. j a v a 2s . c o m*/ calendarStartDate.setTime(dateFrom); calendarEndDate.setTime(dateTo); Map<Integer, Map<Integer, HistoryValues>> historyMap = reportBeanWithHistory.getHistoryValuesMap(); List<HistoryValues> historyValuesList = HistoryLoaderBL.getHistoryValuesList(historyMap, false); if (historyValuesList == null || historyValuesList.isEmpty()) { continue; } //the first HistoryValue should be the most recent because of sorting in HistoryLoaderBL.getHistoryValuesList() HistoryValues historyValues = historyValuesList.get(0); if (!SystemFields.INTEGER_STATE.equals(historyValues.getFieldID())) { //should never happen continue; } Integer stateID = (Integer) historyValues.getNewValue(); if (stateID == null) { continue; } Date lastStateChangeDate = historyValues.getLastEdit(); calendar.setTime(dateFrom); int yearValue = calendarStartDate.get(Calendar.YEAR); int intervalValue = calendarStartDate.get(calendarInterval); boolean isFirst = true; while (calendar.before(calendarEndDate) || isFirst) { if (isFirst) { isFirst = false; } else { calendar.add(calendarInterval, 1); } yearValue = calendar.get(Calendar.YEAR); intervalValue = calendar.get(calendarInterval); SortedMap<Integer, Double> intervalToPlannedValues = yearToIntervalToEarnedValue .get(Integer.valueOf(yearValue)); if (intervalToPlannedValues == null) { yearToIntervalToEarnedValue.put(new Integer(yearValue), new TreeMap<Integer, Double>()); intervalToPlannedValues = yearToIntervalToEarnedValue.get(Integer.valueOf(yearValue)); } Double totalPlannedValueForInterval = intervalToPlannedValues .get(Integer.valueOf(intervalValue)); if (totalPlannedValueForInterval == null) { SortedMap<Integer, Double> firstIntervalToPlannedvalues = yearToIntervalToPlannedValue .get(yearToIntervalToPlannedValue.firstKey()); totalPlannedValueForInterval = firstIntervalToPlannedvalues .get(firstIntervalToPlannedvalues.firstKey()); } if (DateTimeUtils.less(lastStateChangeDate, calendar.getTime())) { if (finalStates.contains(stateID)) { if (selectedEffortType == EFFORT_TYPE.NR_OF_ITEMS_IN_INTERVAL) { totalPlannedValueForInterval -= 1.0; } else { Integer storyPointValueID = getStoryPointValueID(workItemBean, customFieldIDForStoryPoint); if (storyPointValueID != null) { Integer storyPointValue = storyPointValueIDToValueMap.get(storyPointValueID); if (storyPointValue != null) { totalPlannedValueForInterval -= (double) storyPointValue; } } } } } intervalToPlannedValues.put(Integer.valueOf(intervalValue), totalPlannedValueForInterval); } } } return yearToIntervalToEarnedValue; }
From source file:org.celllife.idart.gui.patient.AddPatient.java
public void cmdUpdateAge() { SimpleDateFormat sdf = new SimpleDateFormat("d-MMMM-yyyy", Locale.ENGLISH); //$NON-NLS-1$ try {/*from w w w. j a v a 2s . co m*/ // Set the date of birth if ((!cmbDOBDay.getText().isEmpty()) && (!cmbDOBMonth.getText().isEmpty()) && (!cmbDOBYear.getText().isEmpty())) { Date theDate = sdf.parse(cmbDOBDay.getText() + "-" //$NON-NLS-1$ + cmbDOBMonth.getText() + "-" + cmbDOBYear.getText()); //$NON-NLS-1$ Calendar today = Calendar.getInstance(); Calendar dob = Calendar.getInstance(); dob.setTime(theDate); // Get age based on year int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR); // Add the tentative age to the date of birth to get this year's // birthday dob.add(Calendar.YEAR, age); // If birthday hasn't happened yet, subtract one from // age if (today.before(dob)) { age--; } txtAge.setText(String.valueOf(age)); } } catch (ParseException nbe) { } }
From source file:org.moqui.impl.service.ServiceDefinition.java
private boolean validateParameterSingle(MNode valNode, String parameterName, Object pv, ExecutionContextImpl eci) {/*from w w w .j a v a 2 s .co m*/ // should never be null (caller checks) but check just in case if (pv == null) return true; String validateName = valNode.getName(); if ("val-or".equals(validateName)) { boolean anyPass = false; for (MNode child : valNode.getChildren()) if (validateParameterSingle(child, parameterName, pv, eci)) anyPass = true; return anyPass; } else if ("val-and".equals(validateName)) { boolean allPass = true; for (MNode child : valNode.getChildren()) if (!validateParameterSingle(child, parameterName, pv, eci)) allPass = false; return allPass; } else if ("val-not".equals(validateName)) { boolean allPass = true; for (MNode child : valNode.getChildren()) if (!validateParameterSingle(child, parameterName, pv, eci)) allPass = false; return !allPass; } else if ("matches".equals(validateName)) { if (!(pv instanceof CharSequence)) { Map<String, Object> map = new HashMap<>(1); map.put("pv", pv); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is not a string, cannot do matches validation.", "", map), null); return false; } String pvString = pv.toString(); String regexp = valNode.attribute("regexp"); if (regexp != null && !regexp.isEmpty() && !pvString.matches(regexp)) { // a message attribute should always be there, but just in case we'll have a default final String message = valNode.attribute("message"); Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("regexp", regexp); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource() .expand(message != null && !message.isEmpty() ? message : "Value entered (${pv}) did not match expression: ${regexp}", "", map), null); return false; } return true; } else if ("number-range".equals(validateName)) { BigDecimal bdVal = new BigDecimal(pv.toString()); String minStr = valNode.attribute("min"); if (minStr != null && !minStr.isEmpty()) { BigDecimal min = new BigDecimal(minStr); if ("false".equals(valNode.attribute("min-include-equals"))) { if (bdVal.compareTo(min) <= 0) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("min", min); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is less than or equal to ${min} must be greater than.", "", map), null); return false; } } else { if (bdVal.compareTo(min) < 0) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("min", min); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is less than ${min} and must be greater than or equal to.", "", map), null); return false; } } } String maxStr = valNode.attribute("max"); if (maxStr != null && !maxStr.isEmpty()) { BigDecimal max = new BigDecimal(maxStr); if ("true".equals(valNode.attribute("max-include-equals"))) { if (bdVal.compareTo(max) > 0) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("max", max); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is greater than ${max} and must be less than or equal to.", "", map), null); return false; } } else { if (bdVal.compareTo(max) >= 0) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("max", max); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is greater than or equal to ${max} and must be less than.", "", map), null); return false; } } } return true; } else if ("number-integer".equals(validateName)) { try { new BigInteger(pv.toString()); } catch (NumberFormatException e) { if (logger.isTraceEnabled()) logger.trace( "Adding error message for NumberFormatException for BigInteger parse: " + e.toString()); Map<String, Object> map = new HashMap<>(1); map.put("pv", pv); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value [${pv}] is not a whole (integer) number.", "", map), null); return false; } return true; } else if ("number-decimal".equals(validateName)) { try { new BigDecimal(pv.toString()); } catch (NumberFormatException e) { if (logger.isTraceEnabled()) logger.trace( "Adding error message for NumberFormatException for BigDecimal parse: " + e.toString()); Map<String, Object> map = new HashMap<>(1); map.put("pv", pv); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value [${pv}] is not a decimal number.", "", map), null); return false; } return true; } else if ("text-length".equals(validateName)) { String str = pv.toString(); String minStr = valNode.attribute("min"); if (minStr != null && !minStr.isEmpty()) { int min = Integer.parseInt(minStr); if (str.length() < min) { Map<String, Object> map = new HashMap<>(3); map.put("pv", pv); map.put("str", str); map.put("minStr", minStr); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}), length ${str.length()}, is shorter than ${minStr} characters.", "", map), null); return false; } } String maxStr = valNode.attribute("max"); if (maxStr != null && !maxStr.isEmpty()) { int max = Integer.parseInt(maxStr); if (str.length() > max) { Map<String, Object> map = new HashMap<>(3); map.put("pv", pv); map.put("str", str); map.put("maxStr", maxStr); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}), length ${str.length()}, is longer than ${maxStr} characters.", "", map), null); return false; } } return true; } else if ("text-email".equals(validateName)) { String str = pv.toString(); if (!emailValidator.isValid(str)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${str}) is not a valid email address.", "", map), null); return false; } return true; } else if ("text-url".equals(validateName)) { String str = pv.toString(); if (!urlValidator.isValid(str)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${str}) is not a valid URL.", "", map), null); return false; } return true; } else if ("text-letters".equals(validateName)) { String str = pv.toString(); for (char c : str.toCharArray()) { if (!Character.isLetter(c)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${str}) must have only letters.", "", map), null); return false; } } return true; } else if ("text-digits".equals(validateName)) { String str = pv.toString(); for (char c : str.toCharArray()) { if (!Character.isDigit(c)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value [${str}] must have only digits.", "", map), null); return false; } } return true; } else if ("time-range".equals(validateName)) { Calendar cal; String format = valNode.attribute("format"); if (pv instanceof CharSequence) { cal = eci.getL10n().parseDateTime(pv.toString(), format); } else { // try letting groovy convert it cal = Calendar.getInstance(); // TODO: not sure if this will work: ((pv as java.util.Date).getTime()) cal.setTimeInMillis((DefaultGroovyMethods.asType(pv, Date.class)).getTime()); } String after = valNode.attribute("after"); if (after != null && !after.isEmpty()) { // handle after date/time/date-time depending on type of parameter, support "now" too Calendar compareCal; if ("now".equals(after)) { compareCal = Calendar.getInstance(); compareCal.setTimeInMillis(eci.getUser().getNowTimestamp().getTime()); } else { compareCal = eci.getL10n().parseDateTime(after, format); } if (cal != null && !cal.after(compareCal)) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("after", after); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${pv}) is before ${after}.", "", map), null); return false; } } String before = valNode.attribute("before"); if (before != null && !before.isEmpty()) { // handle after date/time/date-time depending on type of parameter, support "now" too Calendar compareCal; if ("now".equals(before)) { compareCal = Calendar.getInstance(); compareCal.setTimeInMillis(eci.getUser().getNowTimestamp().getTime()); } else { compareCal = eci.getL10n().parseDateTime(before, format); } if (cal != null && !cal.before(compareCal)) { Map<String, Object> map = new HashMap<>(1); map.put("pv", pv); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${pv}) is after ${before}.", "", map), null); return false; } } return true; } else if ("credit-card".equals(validateName)) { long creditCardTypes = 0; String types = valNode.attribute("types"); if (types != null && !types.isEmpty()) { for (String cts : types.split(",")) creditCardTypes += creditCardTypeMap.get(cts.trim()); } else { creditCardTypes = allCreditCards; } CreditCardValidator ccv = new CreditCardValidator(creditCardTypes); String str = pv.toString(); if (!ccv.isValid(str)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource() .expand("Value entered (${str}) is not a valid credit card number.", "", map), null); return false; } return true; } // shouldn't get here, but just in case return true; }