Example usage for java.lang Double equals

List of usage examples for java.lang Double equals

Introduction

In this page you can find the example usage for java.lang Double equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object against the specified object.

Usage

From source file:org.apache.pig.test.TestFilterOpNumeric.java

@Test
public void testNumericNeq() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for (int i = 0; i < LOOP_COUNT; i++) {
        if (i % 5 == 0) {
            ps.println("1:1");
        } else {//from w  w w.  ja v  a  2s  .c  o m
            ps.println("2:3");
        }
    }
    ps.close();
    pig.registerQuery("A=load '" + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext()))
            + "' using " + PigStorage.class.getName() + "(':');");
    String query = "A = filter A by $0 != $1;";
    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    while (it.hasNext()) {
        Tuple t = it.next();
        Double first = Double.valueOf(t.get(0).toString());
        Double second = Double.valueOf(t.get(1).toString());
        assertFalse(first.equals(second));
    }
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes an entity to the specified <code>JsonGenerator</code> as an JSON resource
 * //w w  w .  j a  v a2  s.co  m
 * @param generator
 *            The <code>JsonGenerator</code> to write the entity to.
 * @param format
 *            The {@link TablePayloadFormat} to use for parsing.
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @throws StorageException
 *             if a Storage service error occurs.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 */
private static void writeJsonEntity(final JsonGenerator generator, TablePayloadFormat format,
        final TableEntity entity, final boolean isTableEntry, final OperationContext opContext)
        throws StorageException, IOException {

    HashMap<String, EntityProperty> properties = entity.writeEntity(opContext);
    if (properties == null) {
        properties = new HashMap<String, EntityProperty>();
    }

    // start object
    generator.writeStartObject();

    if (!isTableEntry) {
        Utility.assertNotNull(TableConstants.PARTITION_KEY, entity.getPartitionKey());
        Utility.assertNotNull(TableConstants.ROW_KEY, entity.getRowKey());
        Utility.assertNotNull(TableConstants.TIMESTAMP, entity.getTimestamp());

        // PartitionKey
        generator.writeStringField(TableConstants.PARTITION_KEY, entity.getPartitionKey());

        // RowKey
        generator.writeStringField(TableConstants.ROW_KEY, entity.getRowKey());

        // Timestamp
        generator.writeStringField(TableConstants.TIMESTAMP, Utility
                .getTimeByZoneAndFormat(entity.getTimestamp(), Utility.UTC_ZONE, Utility.ISO8061_LONG_PATTERN));
    }

    for (final Entry<String, EntityProperty> ent : properties.entrySet()) {
        if (ent.getKey().equals(TableConstants.PARTITION_KEY) || ent.getKey().equals(TableConstants.ROW_KEY)
                || ent.getKey().equals(TableConstants.TIMESTAMP) || ent.getKey().equals("Etag")) {
            continue;
        }

        EntityProperty currProp = ent.getValue();
        if (currProp.getEdmType().mustAnnotateType()) {
            final String edmTypeString = currProp.getEdmType().toString();

            // property type
            generator.writeStringField(ent.getKey() + ODataConstants.ODATA_TYPE_SUFFIX, edmTypeString);

            // property key and value
            generator.writeStringField(ent.getKey(), ent.getValue().getValueAsString());
        } else if (currProp.getEdmType() == EdmType.DOUBLE && currProp.getIsNull() == false) {
            final String edmTypeString = currProp.getEdmType().toString();
            final Double value = currProp.getValueAsDouble();

            // property type, if needed
            if (value.equals(Double.POSITIVE_INFINITY) || value.equals(Double.NEGATIVE_INFINITY)
                    || value.equals(Double.NaN)) {
                generator.writeStringField(ent.getKey() + ODataConstants.ODATA_TYPE_SUFFIX, edmTypeString);

                // property key and value
                generator.writeStringField(ent.getKey(), ent.getValue().getValueAsString());
            } else {
                writeJsonProperty(generator, ent);
            }

        } else {
            writeJsonProperty(generator, ent);
        }
    }

    // end object
    generator.writeEndObject();
}

From source file:org.kalypso.model.hydrology.internal.preprocessing.writer.TsFileWriter.java

private void writeSynthNFile(final File targetFileN, final Catchment catchment)
        throws SensorException, IOException {
    final List<Feature> statNList = new ArrayList<>();

    final StringBuffer buffer = new StringBuffer();
    final Double annualityKey = m_metaControl.getAnnuality();
    // Kostra-Kachel/ synth. N gebietsabngig
    final String synthNKey = catchment.getSynthZR();

    statNList.addAll(Arrays//w  w w  .ja va2  s. c om
            .asList(FeatureHelper.getFeaturesWithName(m_synthNWorkspace, NaModelConstants.SYNTHN_STATN_FT)));

    // Performance & readability: linear search loop; first hash the synth-definitions; then write....

    for (final Feature statNFE : statNList) {
        if (statNFE.getName() != null) {
            if (statNFE.getName().equals(synthNKey)) {
                final List<?> statNParameterList = (List<?>) statNFE
                        .getProperty(NaModelConstants.STATNPARA_MEMBER);
                for (final Object object : statNParameterList) {
                    final Feature fe = (Feature) object;
                    final String annuality = Double
                            .toString(1d / (Double) fe.getProperty(NaModelConstants.STATN_PROP_XJAH));
                    if (annuality.equals(annualityKey.toString())) {
                        final IObservation tnProp = (IObservation) fe
                                .getProperty(NaModelConstants.STATN_PROP_STATN_DIAG);
                        if (tnProp != null) {
                            final IObservation observation = tnProp;
                            final IAxis[] axisList = observation.getAxes();
                            final IAxis minutesAxis = ObservationUtilities.findAxisByType(axisList,
                                    ITimeseriesConstants.TYPE_MIN);
                            final IAxis precipitationAxis = ObservationUtilities.findAxisByType(axisList,
                                    ITimeseriesConstants.TYPE_RAINFALL);
                            buffer.append(FortranFormatHelper.printf(annualityKey, "f6.3") + " " + "1" + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                            final ITupleModel values = observation.getValues(null);
                            final int count = values.size();
                            // if( count > 20 )
                            // throw new Exception( "Fehler!!! NA-Modell: Anzahl Wertepaare synth Niederschlag > maximale Anzahl
                            // (20) \n Niederschlag:" + synthNKey + "\n Wiederkehrwahrscheinlichkeit: "
                            // + annualityKey );
                            for (int row = 0; row < count; row++) {
                                final Double minutesValue = (Double) values.get(row, minutesAxis);
                                final Double hoursValue = minutesValue / 60d;
                                if (hoursValue.equals(m_metaControl.getDurationHours())) {
                                    final Double precipitationValue = (Double) values.get(row,
                                            precipitationAxis);
                                    buffer.append(FortranFormatHelper.printf(hoursValue, "f9.3") + " " //$NON-NLS-1$//$NON-NLS-2$
                                            + FortranFormatHelper.printf(precipitationValue, "*") + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
                                }
                            }

                            // FIXME: highly dubious: the same buffer is written again and again, but never cleared during the
                            // loop... is this correct?

                            final FileWriter writer = new FileWriter(targetFileN);
                            writer.write(buffer.toString());
                            IOUtils.closeQuietly(writer);
                        } else {
                            final String msg = Messages.getString(
                                    "org.kalypso.convert.namodel.manager.CatchmentManager.143", synthNKey, //$NON-NLS-1$
                                    annualityKey);
                            m_logger.log(Level.WARNING, msg);
                        }
                    }
                }
            }
        }
    }
}

From source file:no.imr.stox.functions.acoustic.PgNapesIO.java

public static void convertPgNapesToLuf20(String path, String fileName, String outFileName) {
    try {/*from ww  w .  ja v a2s .c o m*/
        List<String> acList = Files.readAllLines(Paths.get(path + "/" + fileName + ".txt"));
        List<String> acVList = Files.readAllLines(Paths.get(path + "/" + fileName + "Values.txt"));
        if (acList.isEmpty() || acVList.isEmpty()) {
            return;
        }
        acList.remove(0);
        acVList.remove(0);
        List<DistanceBO> dList = acList.stream().map(s -> {
            DistanceBO d = new DistanceBO();
            String[] str = s.split("\t", 14);
            d.setNation(str[0]);
            d.setPlatform(str[1]);
            d.setCruise(str[2]);
            d.setLog_start(Conversion.safeStringtoDoubleNULL(str[3]));
            d.setStart_time(Date.from(LocalDateTime.of(Conversion.safeStringtoIntegerNULL(str[4]),
                    Conversion.safeStringtoIntegerNULL(str[5]), Conversion.safeStringtoIntegerNULL(str[6]),
                    Conversion.safeStringtoIntegerNULL(str[7]), Conversion.safeStringtoIntegerNULL(str[8]), 0)
                    .toInstant(ZoneOffset.UTC)));
            d.setLat_start(Conversion.safeStringtoDoubleNULL(str[9]));
            d.setLon_start(Conversion.safeStringtoDoubleNULL(str[10]));
            d.setIntegrator_dist(Conversion.safeStringtoDoubleNULL(str[11]));
            FrequencyBO freq = new FrequencyBO();
            d.getFrequencies().add(freq);
            freq.setTranceiver(1); // implicit in pgnapes
            freq.setUpper_interpret_depth(0d);
            freq.setUpper_integrator_depth(0d);
            freq.setDistance(d);
            freq.setFreq(Conversion.safeStringtoIntegerNULL(str[12]));
            freq.setThreshold(Conversion.safeStringtoDoubleNULL(str[13]));
            return d;
        }).collect(Collectors.toList());
        // Fill in sa values
        acVList.forEach(s -> {
            String[] str = s.split("\t", 11);
            String cruise = str[2];
            Double log = Conversion.safeStringtoDoubleNULL(str[3]);
            Integer year = Conversion.safeStringtoIntegerNULL(str[4]);
            Integer month = Conversion.safeStringtoIntegerNULL(str[5]);
            Integer day = Conversion.safeStringtoIntegerNULL(str[6]);
            if (log == null || year == null || month == null || day == null) {
                return;
            }
            DistanceBO d = dList.parallelStream().filter(di -> {
                if (di.getCruise() == null || di.getLog_start() == null || di.getStart_time() == null) {
                    return false;
                }
                LocalDate ld = di.getStart_time().toInstant().atZone(ZoneOffset.UTC).toLocalDate();
                return cruise.equals(di.getCruise()) && log.equals(di.getLog_start())
                        && year.equals(ld.getYear()) && month.equals(ld.getMonthValue())
                        && day.equals(ld.getDayOfMonth());
            }).findFirst().orElse(null);
            if (d == null) {
                return;
            }
            FrequencyBO freq = d.getFrequencies().get(0);

            String species = str[7];
            Integer acocat = PgNapesEchoConvert.getAcoCatFromPgNapesSpecies(species);
            Double chUppDepth = Conversion.safeStringtoDoubleNULL(str[8]);
            Double chLowDepth = Conversion.safeStringtoDoubleNULL(str[9]);
            Double sa = Conversion.safeStringtoDoubleNULL(str[10]);
            if (acocat == null || sa == null || sa == 0d || chLowDepth == null || chUppDepth == null) {
                return;
            }
            if (d.getPel_ch_thickness() == null) {
                d.setPel_ch_thickness(chLowDepth - chUppDepth);
            }
            Integer ch = (int) (chLowDepth / d.getPel_ch_thickness() + 0.5);
            SABO sabo = new SABO();
            sabo.setFrequency(freq);
            freq.getSa().add(sabo);
            sabo.setAcoustic_category(acocat + "");
            sabo.setCh_type("P");
            sabo.setCh(ch);
            sabo.setSa(sa);
        });
        // Calculate number of pelagic channels

        /*dList.stream().forEach(d -> {
        FrequencyBO f = d.getFrequencies().get(0);
        Integer minCh = f.getSa().stream().map(SABO::getCh).min(Integer::compare).orElse(null);
        Integer maxCh = f.getSa().stream().map(SABO::getCh).max(Integer::compare).orElse(null);
        if (maxCh != null && minCh != null) {
            f.setNum_pel_ch(maxCh - minCh + 1);
        }
        });*/

        if (dList.isEmpty()) {
            return;
        }
        DistanceBO d = dList.get(0);
        String cruise = d.getCruise();
        String nation = d.getNation();
        String pl = d.getPlatform();
        ListUser20Writer.export(cruise, nation, pl, path + "/" + cruise + outFileName + ".xml", dList);

    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.pivot4j.ui.poi.ExcelExporter.java

/**
 * @see org.pivot4j.ui.RenderCallback#renderContent(org.pivot4j.ui.RenderContext,
 *      java.lang.String, java.lang.Double)
 *//*  w w  w.  j a  v  a  2  s. c  o  m*/
@Override
public void renderContent(TableRenderContext context, String label, Double value) {
    cell.setCellStyle(getCellStyle(context));

    if (VALUE.equals(context.getCellType()) && context.getAxis() != Axis.FILTER) {
        if (value == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(value);
        }
    } else {
        boolean showParentMembers = context.getRenderer().getShowParentMembers();

        if (!showParentMembers && label != null && context.getAxis() == Axis.ROWS && context.getMember() != null
                && context.getCell() == null) {
            label = StringUtils.leftPad(label, context.getMember().getDepth() + label.length());
        }

        cell.setCellValue(label);
        cell.setCellType(Cell.CELL_TYPE_STRING);
    }
}

From source file:org.jahia.services.content.nodetypes.JahiaCndWriter.java

/**
 * write prop def//from w  w  w.  j a va  2 s  .  c o  m
 * @param pd
 */
private void writePropertyDefExtension(ExtendedNodeType ntd, ExtendedPropertyDefinition pd) throws IOException {
    out.write("\n" + INDENT + "- ");
    out.write(pd.getName());
    out.write(" (");
    out.write(PropertyType.nameFromValue(pd.getRequiredType()).toLowerCase());

    if (SelectorType.nameFromValue(pd.getSelector()) != null
            && (SelectorType.defaultSelectors.get(pd.getRequiredType()) == null
                    || pd.getSelector() != SelectorType.defaultSelectors.get(pd.getRequiredType())
                    || !pd.getSelectorOptions().isEmpty())) {
        out.write(", ");
        out.write(SelectorType.nameFromValue(pd.getSelector()).toLowerCase());
        Map<String, String> selectorOptions = pd.getSelectorOptions();
        if (!selectorOptions.isEmpty()) {
            out.write("[");
            Iterator<Map.Entry<String, String>> keys = selectorOptions.entrySet().iterator();
            while (keys.hasNext()) {
                Map.Entry<String, String> entry = keys.next();
                String key = entry.getKey();
                String value = entry.getValue();
                out.write(key);
                if (StringUtils.isNotBlank(value)) {
                    out.write("='" + value + "'");
                }
                if (keys.hasNext()) {
                    out.write(",");
                }
            }
            out.write("]");
        }
    }
    out.write(")");
    writeDefaultValues(pd.getDefaultValuesAsUnexpandedValue());
    out.write(ntd.getPrimaryItemName() != null && ntd.getPrimaryItemName().equals(pd.getName()) ? " primary"
            : "");
    if (pd.isMandatory()) {
        out.write(" mandatory");
    }
    if (pd.isAutoCreated()) {
        out.write(" autocreated");
    }
    if (pd.isProtected()) {
        out.write(" protected");
    }
    if (pd.isMultiple()) {
        out.write(" multiple");
    }
    if (pd.isHidden()) {
        out.write(" hidden");
    }
    if (pd.isInternationalized()) {
        out.write(" internationalized");
    }
    if (pd.getOnConflict() != OnConflictAction.USE_LATEST) {
        out.write(" onconflict=" + OnConflictAction.nameFromValue(pd.getOnConflict()));
    }

    if (pd.getIndex() != IndexType.TOKENIZED) {
        out.write(" indexed=" + IndexType.nameFromValue(pd.getIndex()));
    }

    final Double scoreboost = pd.getScoreboost();
    if (!scoreboost.isInfinite() && !scoreboost.isNaN() && !scoreboost.equals(1.0)) {
        out.write(" scoreboost=" + scoreboost);
    }
    if (pd.getAnalyzer() != null) {
        out.write(" analyzer=" + pd.getAnalyzer());
    }
    if (pd.isFacetable()) {
        out.write(" facetable");
    }
    if (pd.isHierarchical()) {
        out.write(" hierarchical");
    }
    if (!pd.isQueryOrderable()) {
        out.write(" noqueryorder");
    }
    if (!pd.isFullTextSearchable()) {
        out.write(" nofulltext");
    }
    if (pd.getLocalItemType() != null) {
        out.write(" itemtype = " + pd.getLocalItemType());
    }
    if (pd.getOnParentVersion() != OnParentVersionAction.VERSION) {
        out.write(" ");
        out.write(OnParentVersionAction.nameFromValue(pd.getOnParentVersion()).toLowerCase());
    }
    String[] availableQueryOperators = pd.getAvailableQueryOperators();
    if (availableQueryOperators != null && availableQueryOperators.length > 0) {
        writeQueryOperators(availableQueryOperators);
    }

    writeValueConstraints(pd.getValueConstraintsAsValue());
}

From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java

public void setExchangeRatio(String from, String to, double ratio) {
    Double old = (Double) map.get(from + to);
    Double quote = new Double(ratio);
    map.put(from + to, quote);/*  w w w .jav  a 2s  .  c om*/
    if (old == null && quote != null || old != null && !old.equals(quote)) {
        setChanged();
        notifyObservers();
    }
}

From source file:com.btobits.automator.ant.sql.task.SQLCompareTask.java

private void verify() throws Exception {
    final LinkedList<SQLCompareTask.VerifyCell> rows = impl.getVerifySqls();
    for (final SQLCompareTask.VerifyCell sqlRow : rows) {
        sqlRow.validate();//w  w  w. j  a  v a2  s.c  o  m

        switch (getColumnType(sqlRow)) {
        case Types.DOUBLE: {
            final Double val = (Double) getRowValue(sqlRow);

            if (val == null) {
                errors.add("Error compare row, row not exist [" + sqlRow.toString() + "].");
            }

            final DoubleValidator doubleValidator = new DoubleValidator();
            if (doubleValidator.isValid(sqlRow.getValue())) {
                final Double dbValue = doubleValidator.validate(sqlRow.getValue());
                if (!dbValue.equals(val)) {
                    errors.add("Error compare row [" + sqlRow.getRow() + "], field [" + sqlRow.getField()
                            + "], value [" + sqlRow.getValue() + " != " + val + "]");
                }
            } else {
                errors.add("Error cast field [" + sqlRow.toString() + "] to Double value.");
            }
        }
            break;

        case Types.FLOAT: {
            final Float val = (Float) getRowValue(sqlRow);

            if (val == null) {
                errors.add("Error compare row, row not exist [" + sqlRow.toString() + "].");
            }

            final FloatValidator validator = new FloatValidator();
            if (validator.isValid(sqlRow.getValue())) {
                final Float dbValue = validator.validate(sqlRow.getValue());
                if (!dbValue.equals(val)) {
                    errors.add("Error compare row [" + sqlRow.getRow() + "], field [" + sqlRow.getField()
                            + "], value [" + sqlRow.getValue() + " != " + val + "]");
                }
            } else {
                errors.add("Error cast field [" + sqlRow.toString() + "] to Float value.");
            }
        }
            break;

        case Types.DECIMAL: {
            final BigDecimal val = (BigDecimal) getRowValue(sqlRow);

            if (val == null) {
                errors.add("Error compare row, row not exist [" + sqlRow.toString() + "].");
            }

            final BigDecimalValidator validator = new BigDecimalValidator();
            if (validator.isValid(sqlRow.getValue())) {
                BigDecimal dbValue = validator.validate(sqlRow.getValue());
                dbValue = dbValue.setScale(val.scale());
                if (!dbValue.equals(val)) {
                    errors.add("Error compare row [" + sqlRow.getRow() + "], field [" + sqlRow.getField()
                            + "], value [" + sqlRow.getValue() + " != " + val + "]");
                }
            } else {
                errors.add("Error cast field [" + sqlRow.toString() + "] to Decimal value.");
            }
        }
            break;

        case Types.DATE: {
            final Date val = (Date) getDateRowValue(sqlRow);

            if (val == null) {
                errors.add("Error compare row, row not exist [" + sqlRow.toString() + "].");
            }

            final DateValidator validator = DateValidator.getInstance();
            if (validator.isValid(sqlRow.getValue(), "yyyy-MM-dd")) {
                final Date dbValue = validator.validate(sqlRow.getValue(), "yyyy-MM-dd");
                if (!dbValue.equals(val)) {
                    errors.add("Error compare row [" + sqlRow.getRow() + "], field [" + sqlRow.getField()
                            + "], value [" + sqlRow.getValue() + " != " + val + "]");
                }
            } else {
                errors.add("Error cast field [" + sqlRow.toString() + "] to Date value.");
            }
        }
            break;

        case Types.TIME: {
            final Date val = (Date) getTimeRowValue(sqlRow);
            if (val == null) {
                errors.add("Error compare row, row not exist [" + sqlRow.toString() + "].");
            }

            final TimeValidator validator = TimeValidator.getInstance();
            if (validator.isValid(sqlRow.getValue(), "HH:mm:ss")) {
                final Calendar dbValue = validator.validate(sqlRow.getValue(), "HH:mm:ss");
                final Calendar dbVal = Calendar.getInstance();
                dbVal.setTime(val);

                if (validator.compareHours(dbValue, dbVal) != 0 || validator.compareMinutes(dbValue, dbVal) != 0
                        || validator.compareSeconds(dbValue, dbVal) != 0) {
                    errors.add("Error compare row [" + sqlRow.getRow() + "], field [" + sqlRow.getField()
                            + "], value [" + sqlRow.getValue() + " != " + val + "]");
                }
            } else {
                errors.add("Error cast field [" + sqlRow.toString() + "] to Time value.");
            }
        }
            break;

        case Types.TIMESTAMP: {
            final Date val = getDateTimeRowValue(sqlRow);
            if (val == null) {
                errors.add("Error compare row, row not exist [" + sqlRow.toString() + "].");
            }

            final CalendarValidator validatorDate = CalendarValidator.getInstance();
            final TimeValidator validatorTime = TimeValidator.getInstance();
            if (validatorDate.isValid(sqlRow.getValue(), "yyyy-MM-dd HH:mm:ss")) {
                final Calendar dbValue = validatorDate.validate(sqlRow.getValue(), "yyyy-MM-dd HH:mm:ss");
                final Calendar dbVal = Calendar.getInstance();
                dbVal.setTimeInMillis(val.getTime());
                if (validatorDate.compareDates(dbVal, dbValue) != 0
                        || validatorTime.compareHours(dbValue, dbVal) != 0
                        || validatorTime.compareMinutes(dbValue, dbVal) != 0
                        || validatorTime.compareSeconds(dbValue, dbVal) != 0) {
                    errors.add("Error compare row [" + sqlRow.getRow() + "], field [" + sqlRow.getField()
                            + "], value [" + sqlRow.getValue() + " != " + val + "]");
                }
            } else {
                errors.add("Error cast field [" + sqlRow.toString() + "] to Timestamp value.");
            }
        }
            break;

        default: {
            final String dbValue = getStringRowValue(sqlRow);
            if (dbValue == null) {
                errors.add("Error compare row, row not exist [" + sqlRow.toString() + "].");
            } else if (!StringUtils.equals(sqlRow.getValue(), dbValue)) {
                errors.add("Error compare row [" + sqlRow.getRow() + "], field [" + sqlRow.getField()
                        + "], value [" + sqlRow.getValue() + " != " + dbValue + "]");
            }
        }
        }
    }
}

From source file:org.openmicroscopy.shoola.util.ui.NumericalTextField.java

/**
 * Checks if the value is correct.//from  w ww  . java 2s  . c  om
 *
 * @return See above.
 */
private String checkValue() {
    String str = getText();
    try {
        if (Integer.class.equals(numberType)) {
            int m = (int) getMinimum();
            if (StringUtils.isBlank(str)) {
                return "" + m;
            }
            int val = Integer.parseInt(str);
            if (val < m)
                return "" + m;
        } else if (Double.class.equals(numberType)) {
            Double min = getMinimum();
            if (StringUtils.isBlank(str)) {
                return "" + min;
            }
            double val = Double.parseDouble(str);
            if (val < min && !min.equals(Double.MIN_VALUE)) {
                return "" + min;
            }
        } else if (Long.class.equals(numberType)) {
            Long min = new Long((long) getMinimum());
            if (StringUtils.isBlank(str)) {
                return "" + min;
            }
            long val = Long.parseLong(str);
            if (val < min && !min.equals(Long.MIN_VALUE)) {
                return "" + min;
            }
        } else if (Float.class.equals(numberType)) {
            Float min = new Float(getMinimum());
            if (StringUtils.isBlank(str)) {
                return "" + min;
            }
            float val = Float.parseFloat(str);
            if (val < min && !min.equals(Float.MIN_VALUE)) {
                return "" + min;
            }
        }
    } catch (NumberFormatException nfe) {
    }
    return str;
}

From source file:org.openmrs.module.htmlformentry.element.PatientDetailSubmissionElement.java

/**
 * If there's a birthdate specified// w w  w  . j a  va2 s  .  c om
 */
private void calculateBirthDate(Person person, Date date, Double age) {
    Date birthdate = null;
    boolean birthdateEstimated = false;
    if (date != null) {
        birthdate = date;
        //if you have a previous date that's marked as estimated and date does not change -->  keep it that way
        //if you have a previous date that's marked as estimated but date changes --> not estimated
        //if new --> not estimated
        //if existing and not estimated --> not estimated
        birthdateEstimated = person.getBirthdate() != null && person.getBirthdateEstimated() != null
                && person.getBirthdate().equals(date) ? person.getBirthdateEstimated() : false;
    } else if (age != null) {
        try {
            Double ageRemainder = BigDecimal.valueOf(age).subtract(BigDecimal.valueOf(Math.floor(age)))
                    .doubleValue();
            if (ageRemainder.equals(Double.valueOf(0)))
                person.setBirthdateFromAge(age.intValue(), new Date()); //default to usual behavior from core
            else { //a decimal was entered
                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, -Double.valueOf((ageRemainder * 365)).intValue()); //if patient is 2.2 years old, patient was 2.0 years 2.2 - (.2*365) days ago
                c.add(Calendar.YEAR, -1 * Double.valueOf(Math.floor(age)).intValue());
                birthdate = c.getTime();
            }
            birthdateEstimated = true;
        } catch (NumberFormatException e) {
            throw new RuntimeException("Error getting date from age", e);
        }
    } else {
        throw new IllegalArgumentException("You must provide either an age or a birthdate for this patient.");
    }
    if (birthdate != null)
        person.setBirthdate(birthdate);
    person.setBirthdateEstimated(birthdateEstimated);
}