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:com.cloud.hypervisor.xenserver.resource.CitrixResourceBase.java

protected double getDataAverage(final Node dataNode, final int col, final int numRows) {
    double value = 0;
    final double dummy = 0;
    int numRowsUsed = 0;
    for (int row = 0; row < numRows; row++) {
        final Node data = dataNode.getChildNodes().item(numRows - 1 - row).getChildNodes().item(col + 1);
        final Double currentDataAsDouble = Double.valueOf(getXMLNodeValue(data));
        if (!currentDataAsDouble.equals(Double.NaN)) {
            numRowsUsed += 1;/*from   w w w  . ja v  a  2  s  .  com*/
            value += currentDataAsDouble;
        }
    }

    if (numRowsUsed == 0) {
        if (!Double.isInfinite(value) && !Double.isNaN(value)) {
            return value;
        } else {
            s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows=0");
            return dummy;
        }
    } else {
        if (!Double.isInfinite(value / numRowsUsed) && !Double.isNaN(value / numRowsUsed)) {
            return value / numRowsUsed;
        } else {
            s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows>0");
            return dummy;
        }
    }

}

From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java

public boolean identicalValue(String localValue, String serverValue, ElementDataType dt) {

    if (localValue == null && serverValue == null) {
        return true;
    } else if (localValue == null || serverValue == null) {
        return false;
    } else if (localValue.equals(serverValue)) {
        return true;
    }/* www.  j a v  a  2s  .  c o m*/

    // NOT textually identical.
    //
    // Everything must be textually identical except possibly number fields
    // which may have rounding due to different database implementations,
    // data representations, and marshaling libraries.
    //
    if (dt == ElementDataType.number) {
        // !!Important!! Double.valueOf(str) handles NaN and +/-Infinity
        Double localNumber = Double.valueOf(localValue);
        Double serverNumber = Double.valueOf(serverValue);

        if (localNumber.equals(serverNumber)) {
            // simple case -- trailing zeros or string representation mix-up
            //
            return true;
        } else if (localNumber.isInfinite() && serverNumber.isInfinite()) {
            // if they are both plus or both minus infinity, we have a match
            if (Math.signum(localNumber) == Math.signum(serverNumber)) {
                return true;
            } else {
                return false;
            }
        } else if (localNumber.isNaN() || localNumber.isInfinite() || serverNumber.isNaN()
                || serverNumber.isInfinite()) {
            // one or the other is special1
            return false;
        } else {
            double localDbl = localNumber;
            double serverDbl = serverNumber;
            if (localDbl == serverDbl) {
                return true;
            }
            // OK. We have two values like 9.80 and 9.8
            // consider them equal if they are adjacent to each other.
            double localNear = localDbl;
            int idist = 0;
            int idistMax = 128;
            for (idist = 0; idist < idistMax; ++idist) {
                localNear = Math.nextAfter(localNear, serverDbl);
                if (localNear == serverDbl) {
                    break;
                }
            }
            if (idist < idistMax) {
                return true;
            }
            return false;
        }
    } else {
        // textual identity is required!
        return false;
    }
}

From source file:classes.MyVisitor.java

@Override
public T visitExpr(MyLanguageParser.ExprContext ctx) {
    // Multipliacin/divisin
    if (ctx.expr(0) != null && ctx.MULOP() != null && ctx.expr(1) != null) {
        T visit1 = posicionArray(visitExpr(ctx.expr(0)));
        T visit2 = posicionArray(visitExpr(ctx.expr(1)));
        Double a = Double.valueOf(visit1.toString());
        Double b = Double.valueOf(visit2.toString());
        if (ctx.MULOP().toString().equals("*")) {
            Double c;// ww w .  j  av a  2s .  c  om
            c = a * b;
            if (isInt(c)) {
                Integer d = c.intValue();
                return (T) d;
            }
            return (T) c;
        } else if (ctx.MULOP().toString().equals("/")) {
            Double c;
            c = a * b;
            if (isInt(c)) {
                Integer d = c.intValue();
                return (T) d;
            }
            return (T) c;
        }
    }
    // NO.token
    else if (ctx.NO_ID() != null && ctx.ID() != null) {
        Objeto obj = buscar(ctx.ID().toString());
        String bool;
        if (getTipo(obj) != 4) {
            // SEMANTICO
            error = "Negacion se usa para cambiar el estado de variables logicas";
            error();
        } else if (obj.getObjeto().equals("verdadero")) {
            bool = "falso";
            return (T) bool;
        } else if (obj.getObjeto().equals("falso")) {
            bool = "verdadero";
            return (T) bool;
        }
    }
    // +/- expr
    else if (ctx.SUMOP() != null && ctx.expr(0) != null && ctx.expr(1) == null) {
        T tipo1 = visitExpr(ctx.expr(0));
        T tipo = posicionArray(visitExpr(ctx.expr(0)));

        boolean isNumber = NumberUtils.isNumber(tipo.toString());
        if (isNumber) {
            if (ctx.SUMOP().toString().equals("+")) {
                Double tipe = Double.valueOf(tipo.toString());
                return (T) tipe;
            } else {
                Double tipe = -Double.valueOf(tipo.toString());
                return (T) tipe;
            }
        }

    }
    // b[a][][] etc REVCISASUDJWQ
    else if (ctx.ID() != null && ctx.COR_IZQ() != null && ctx.expr(0) != null && ctx.COR_DER() != null) {
        T tipo = visitExpr(ctx.expr(0));
        String lista = tipo.toString();
        lista = lista.replace("[", "");
        lista = lista.replace("]", "");
        lista = lista.replace(" ", "");
        ArrayList<String> list = new ArrayList<String>(Arrays.asList(lista.split(",")));
        for (String string : list) {
            if (!isNum(string)) {
                error = "<linea:col> Error en tiempo de ejecucion: se accedio a una posicion no valida del arreglo: "
                        + string;
                error();

            }
        }
        ArrayList<String> idList = new ArrayList<>();
        idList.add(ctx.ID().toString());
        for (String string : list) {
            idList.add(string);
        }

        return (T) idList;

    }
    // [expr]
    else if (ctx.COR_IZQ() != null && ctx.expr(0) != null && ctx.COR_DER() != null) {
        T tipo = visitExpr(ctx.expr(0));
        String s = tipo + "";
        return (T) s;
    }
    // SUMA
    else if (ctx.expr(0) != null && ctx.SUMOP() != null && ctx.expr(1) != null) {
        T visit1 = posicionArray(visitExpr(ctx.expr(0)));
        T visit2 = posicionArray(visitExpr(ctx.expr(1)));
        Double a = Double.valueOf(visit1.toString());
        Double b = Double.valueOf(visit2.toString());
        if (ctx.SUMOP().toString().equals("+")) {
            Double c;
            c = a + b;
            if (isInt(c)) {
                Integer d = c.intValue();
                return (T) d;
            }
            return (T) c;
        } else if (ctx.SUMOP().toString().equals("-")) {
            Double c;
            c = a - b;
            if (isInt(c)) {
                Integer d = c.intValue();
                return (T) d;
            }
            return (T) c;
        }
    }
    // pow
    else if (ctx.expr(0) != null && ctx.POTENCIA() != null && ctx.expr(1) != null) {
        T visit1 = posicionArray(visitExpr(ctx.expr(0)));
        T visit2 = posicionArray(visitExpr(ctx.expr(1)));
        Double a = Double.valueOf(visit1.toString());
        Double b = Double.valueOf(visit2.toString());
        Double c = Math.pow(a, b);
        return (T) c;
    }
    // modulo %
    else if (ctx.expr(0) != null && ctx.MODOP() != null && ctx.expr(1) != null) {
        T visit1 = posicionArray(visitExpr(ctx.expr(0)));
        T visit2 = posicionArray(visitExpr(ctx.expr(1)));
        Double a = Double.valueOf(visit1.toString());
        Double b = Double.valueOf(visit2.toString());
        Double c = a % b;
        return (T) c;

    }
    // modulo mod
    else if (ctx.expr(0) != null && ctx.MODULO() != null && ctx.expr(1) != null) {
        T visit1 = posicionArray(visitExpr(ctx.expr(0)));
        T visit2 = posicionArray(visitExpr(ctx.expr(1)));
        Double a = Double.valueOf(visit1.toString());
        Double b = Double.valueOf(visit2.toString());
        Double c = a % b;
        return (T) c;
    }
    // Case Y/O
    else if (ctx.expr(0) != null && (ctx.AND_OP() != null || ctx.OR_OP() != null) && ctx.expr(1) != null) {
        T visit1 = posicionArray(visitExpr(ctx.expr(0)));
        T visit2 = posicionArray(visitExpr(ctx.expr(1)));
        String a = visit1.toString();
        String b = visit2.toString();
        if (!(a.equals("verdadero") || a.equals("falso"))) {
            error = "Se esperaba un valor logico, en cambio llego" + a;
            error();
        }
        if (!(b.equals("verdadero") || b.equals("falso"))) {
            error = "Se esperaba un valor logico, en cambio llego" + b;
            error();
        }
        String valor;
        if (ctx.AND_OP() != null) {
            if (a.equals("verdadero") && b.equals("verdadero")) {
                valor = "verdadero";
            } else {
                valor = "falso";
            }
            return (T) valor;
        } else if (ctx.OR_OP() != null) {
            if (a.equals("verdadero") || b.equals("verdadero")) {
                valor = "verdadero";
            } else {
                valor = "falso";
            }
            return (T) valor;
        }
    }
    // real
    else if (ctx.REAL() != null) {
        Double a = Double.valueOf(ctx.REAL().toString());
        if (isInt(a)) {
            Integer d = a.intValue();
            return (T) d;
        }
        return (T) a;
    }
    // entero
    else if (ctx.ENTERO() != null) {
        Integer a = Integer.valueOf(ctx.ENTERO().toString());
        return (T) a;
    }
    // logico verdadero
    else if (ctx.VERDADERO() != null) {
        String bool = "verdadero";
        return (T) bool;
    }
    // logico falso
    else if (ctx.FALSO() != null) {
        String bool = "falso";
        return (T) bool;
    }
    // ROP
    else if (ctx.ROP() != null) {
        String rop = ctx.ROP().toString();
        return (T) rop;

    }
    // ID, expr
    else if (ctx.ID() != null && ctx.COMMA() != null && ctx.expr(0) != null) {
        Objeto obj = isDefined(ctx.ID().toString());
        // T visit1 = posicionArray(visitExpr(ctx.expr(0)));
        String s = obj.getObjeto() + ", " + visitExpr(ctx.expr(0)).toString();
        return (T) s;
    }
    // ID
    else if (ctx.ID() != null) {
        Objeto obj = isDefined(ctx.ID().toString());
        String valor = isInicialized(obj);
        return (T) valor;
    }
    // (expr)
    else if (ctx.PAR_DER() != null && ctx.expr(0) != null && ctx.PAR_DER() != null) {
        return posicionArray(visitExpr(ctx.expr(0)));
    }
    // function f(expr)??
    else if (ctx.ID() != null && ctx.PAR_DER() != null && ctx.expr(0) != null && ctx.PAR_DER() != null) {
        System.out.println("definir Caso funcion(expr)");
    }
    // expr, expr
    else if (ctx.expr(0) != null && ctx.COMMA() != null && ctx.expr(1) != null) {
        ArrayList<T> a = new ArrayList<T>();
        T visit1 = visitExpr(ctx.expr(0));
        T visit2 = visitExpr(ctx.expr(1));
        String izq = visit1.toString();
        String der = visit2.toString();
        a.add((T) izq);
        a.add((T) der);
        return (T) a;
    }
    // f()??
    else if (ctx.ID() != null && ctx.PAR_IZQ() != null && ctx.PAR_DER() != null) {
        System.out.println("definir Caso f()");
    }
    // negacion
    else if (ctx.NEGACION() != null && ctx.expr(0) != null) {
        T visit1 = posicionArray(visitExpr(ctx.expr(0)));
        String bool;
        if (visit1.toString() != "verdadero" || visit1.toString() != "falso") {
            // SEMANTICO
            error = "Negacion se usa para cambiar el estado de variables logicas";
            error();
        } else if (visit1.toString().equals("verdadero")) {
            bool = "falso";
            return (T) bool;
        } else if (visit1.toString().equals("falso")) {
            bool = "verdadero";
            return (T) bool;
        }
    }
    System.out.println("Estado no definido");
    return null;
}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

private void processDatasetMetadata(FileMetadataIngest fileMetadataIngest, DatasetVersion editVersion)
        throws IOException {

    for (MetadataBlock mdb : editVersion.getDataset().getOwner().getMetadataBlocks()) {
        if (mdb.getName().equals(fileMetadataIngest.getMetadataBlockName())) {
            logger.fine("Ingest Service: dataset version has " + mdb.getName() + " metadata block enabled.");

            editVersion.setDatasetFields(editVersion.initDatasetFields());

            Map<String, Set<String>> fileMetadataMap = fileMetadataIngest.getMetadataMap();
            for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()) {
                if (dsft.isPrimitive()) {
                    if (!dsft.isHasParent()) {
                        String dsfName = dsft.getName();
                        // See if the plugin has found anything for this field: 
                        if (fileMetadataMap.get(dsfName) != null && !fileMetadataMap.get(dsfName).isEmpty()) {

                            logger.fine("Ingest Service: found extracted metadata for field " + dsfName);
                            // go through the existing fields:
                            for (DatasetField dsf : editVersion.getFlatDatasetFields()) {
                                if (dsf.getDatasetFieldType().equals(dsft)) {
                                    // yep, this is our field!
                                    // let's go through the values that the ingest 
                                    // plugin found in the file for this field: 

                                    Set<String> mValues = fileMetadataMap.get(dsfName);

                                    // Special rules apply to aggregation of values for 
                                    // some specific fields - namely, the resolution.* 
                                    // fields from the Astronomy Metadata block. 
                                    // TODO: rather than hard-coded, this needs to be
                                    // programmatically defined. -- L.A. 4.0
                                    if (dsfName.equals("resolution.Temporal")
                                            || dsfName.equals("resolution.Spatial")
                                            || dsfName.equals("resolution.Spectral")) {
                                        // For these values, we aggregate the minimum-maximum 
                                        // pair, for the entire set. 
                                        // So first, we need to go through the values found by 
                                        // the plugin and select the min. and max. values of 
                                        // these: 
                                        // (note that we are assuming that they all must
                                        // validate as doubles!)

                                        Double minValue = null;
                                        Double maxValue = null;

                                        for (String fValue : mValues) {

                                            try {
                                                double thisValue = Double.parseDouble(fValue);

                                                if (minValue == null
                                                        || Double.compare(thisValue, minValue) < 0) {
                                                    minValue = thisValue;
                                                }
                                                if (maxValue == null
                                                        || Double.compare(thisValue, maxValue) > 0) {
                                                    maxValue = thisValue;
                                                }
                                            } catch (NumberFormatException e) {
                                            }
                                        }

                                        // Now let's see what aggregated values we 
                                        // have stored already: 

                                        // (all of these resolution.* fields have allowedMultiple set to FALSE, 
                                        // so there can be only one!)
                                        //logger.fine("Min value: "+minValue+", Max value: "+maxValue);
                                        if (minValue != null && maxValue != null) {
                                            Double storedMinValue = null;
                                            Double storedMaxValue = null;

                                            String storedValue = "";

                                            if (dsf.getDatasetFieldValues() != null
                                                    && dsf.getDatasetFieldValues().get(0) != null) {
                                                storedValue = dsf.getDatasetFieldValues().get(0).getValue();

                                                if (storedValue != null && !storedValue.equals("")) {
                                                    try {

                                                        if (storedValue.indexOf(" - ") > -1) {
                                                            storedMinValue = Double.parseDouble(storedValue
                                                                    .substring(0, storedValue.indexOf(" - ")));
                                                            storedMaxValue = Double.parseDouble(storedValue
                                                                    .substring(storedValue.indexOf(" - ") + 3));
                                                        } else {
                                                            storedMinValue = Double.parseDouble(storedValue);
                                                            storedMaxValue = storedMinValue;
                                                        }
                                                        if (storedMinValue != null
                                                                && storedMinValue.compareTo(minValue) < 0) {
                                                            minValue = storedMinValue;
                                                        }
                                                        if (storedMaxValue != null
                                                                && storedMaxValue.compareTo(maxValue) > 0) {
                                                            maxValue = storedMaxValue;
                                                        }
                                                    } catch (NumberFormatException e) {
                                                    }
                                                } else {
                                                    storedValue = "";
                                                }
                                            }

                                            //logger.fine("Stored min value: "+storedMinValue+", Stored max value: "+storedMaxValue);

                                            String newAggregateValue = "";

                                            if (minValue.equals(maxValue)) {
                                                newAggregateValue = minValue.toString();
                                            } else {
                                                newAggregateValue = minValue.toString() + " - "
                                                        + maxValue.toString();
                                            }

                                            // finally, compare it to the value we have now:
                                            if (!storedValue.equals(newAggregateValue)) {
                                                if (dsf.getDatasetFieldValues() == null) {
                                                    dsf.setDatasetFieldValues(
                                                            new ArrayList<DatasetFieldValue>());
                                                }
                                                if (dsf.getDatasetFieldValues().get(0) == null) {
                                                    DatasetFieldValue newDsfv = new DatasetFieldValue(dsf);
                                                    dsf.getDatasetFieldValues().add(newDsfv);
                                                }
                                                dsf.getDatasetFieldValues().get(0).setValue(newAggregateValue);
                                            }
                                        }
                                        // Ouch. 
                                    } else {
                                        // Other fields are aggregated simply by 
                                        // collecting a list of *unique* values encountered 
                                        // for this Field throughout the dataset. 
                                        // This means we need to only add the values *not yet present*.
                                        // (the implementation below may be inefficient - ?)

                                        for (String fValue : mValues) {
                                            if (!dsft.isControlledVocabulary()) {
                                                Iterator<DatasetFieldValue> dsfvIt = dsf.getDatasetFieldValues()
                                                        .iterator();

                                                boolean valueExists = false;

                                                while (dsfvIt.hasNext()) {
                                                    DatasetFieldValue dsfv = dsfvIt.next();
                                                    if (fValue.equals(dsfv.getValue())) {
                                                        logger.fine("Value " + fValue
                                                                + " already exists for field " + dsfName);
                                                        valueExists = true;
                                                        break;
                                                    }
                                                }

                                                if (!valueExists) {
                                                    logger.fine("Creating a new value for field " + dsfName
                                                            + ": " + fValue);
                                                    DatasetFieldValue newDsfv = new DatasetFieldValue(dsf);
                                                    newDsfv.setValue(fValue);
                                                    dsf.getDatasetFieldValues().add(newDsfv);
                                                }

                                            } else {
                                                // A controlled vocabulary entry: 
                                                // first, let's see if it's a legit control vocab. entry: 
                                                ControlledVocabularyValue legitControlledVocabularyValue = null;
                                                Collection<ControlledVocabularyValue> definedVocabularyValues = dsft
                                                        .getControlledVocabularyValues();
                                                if (definedVocabularyValues != null) {
                                                    for (ControlledVocabularyValue definedVocabValue : definedVocabularyValues) {
                                                        if (fValue.equals(definedVocabValue.getStrValue())) {
                                                            logger.fine("Yes, " + fValue
                                                                    + " is a valid controlled vocabulary value for the field "
                                                                    + dsfName);
                                                            legitControlledVocabularyValue = definedVocabValue;
                                                            break;
                                                        }
                                                    }
                                                }
                                                if (legitControlledVocabularyValue != null) {
                                                    // Only need to add the value if it is new, 
                                                    // i.e. if it does not exist yet: 
                                                    boolean valueExists = false;

                                                    List<ControlledVocabularyValue> existingControlledVocabValues = dsf
                                                            .getControlledVocabularyValues();
                                                    if (existingControlledVocabValues != null) {
                                                        Iterator<ControlledVocabularyValue> cvvIt = existingControlledVocabValues
                                                                .iterator();
                                                        while (cvvIt.hasNext()) {
                                                            ControlledVocabularyValue cvv = cvvIt.next();
                                                            if (fValue.equals(cvv.getStrValue())) {
                                                                // or should I use if (legitControlledVocabularyValue.equals(cvv)) ?
                                                                logger.fine("Controlled vocab. value " + fValue
                                                                        + " already exists for field "
                                                                        + dsfName);
                                                                valueExists = true;
                                                                break;
                                                            }
                                                        }
                                                    }

                                                    if (!valueExists) {
                                                        logger.fine("Adding controlled vocabulary value "
                                                                + fValue + " to field " + dsfName);
                                                        dsf.getControlledVocabularyValues()
                                                                .add(legitControlledVocabularyValue);
                                                    }
                                                }
                                            }
                                        }
                                    }//from   w  w  w  .ja v a 2  s. c  o m
                                }
                            }
                        }
                    }
                } else {
                    // A compound field: 
                    // See if the plugin has found anything for the fields that 
                    // make up this compound field; if we find at least one 
                    // of the child values in the map of extracted values, we'll 
                    // create a new compound field value and its child 
                    // 
                    DatasetFieldCompoundValue compoundDsfv = new DatasetFieldCompoundValue();
                    int nonEmptyFields = 0;
                    for (DatasetFieldType cdsft : dsft.getChildDatasetFieldTypes()) {
                        String dsfName = cdsft.getName();
                        if (fileMetadataMap.get(dsfName) != null && !fileMetadataMap.get(dsfName).isEmpty()) {
                            logger.fine("Ingest Service: found extracted metadata for field " + dsfName
                                    + ", part of the compound field " + dsft.getName());

                            if (cdsft.isPrimitive()) {
                                // probably an unnecessary check - child fields
                                // of compound fields are always primitive... 
                                // but maybe it'll change in the future. 
                                if (!cdsft.isControlledVocabulary()) {
                                    // TODO: can we have controlled vocabulary
                                    // sub-fields inside compound fields?

                                    DatasetField childDsf = new DatasetField();
                                    childDsf.setDatasetFieldType(cdsft);

                                    DatasetFieldValue newDsfv = new DatasetFieldValue(childDsf);
                                    newDsfv.setValue((String) fileMetadataMap.get(dsfName).toArray()[0]);
                                    childDsf.getDatasetFieldValues().add(newDsfv);

                                    childDsf.setParentDatasetFieldCompoundValue(compoundDsfv);
                                    compoundDsfv.getChildDatasetFields().add(childDsf);

                                    nonEmptyFields++;
                                }
                            }
                        }
                    }

                    if (nonEmptyFields > 0) {
                        // let's go through this dataset's fields and find the 
                        // actual parent for this sub-field: 
                        for (DatasetField dsf : editVersion.getFlatDatasetFields()) {
                            if (dsf.getDatasetFieldType().equals(dsft)) {

                                // Now let's check that the dataset version doesn't already have
                                // this compound value - we are only interested in aggregating 
                                // unique values. Note that we need to compare compound values 
                                // as sets! -- i.e. all the sub fields in 2 compound fields 
                                // must match in order for these 2 compounds to be recognized 
                                // as "the same":

                                boolean alreadyExists = false;
                                for (DatasetFieldCompoundValue dsfcv : dsf.getDatasetFieldCompoundValues()) {
                                    int matches = 0;

                                    for (DatasetField cdsf : dsfcv.getChildDatasetFields()) {
                                        String cdsfName = cdsf.getDatasetFieldType().getName();
                                        String cdsfValue = cdsf.getDatasetFieldValues().get(0).getValue();
                                        if (cdsfValue != null && !cdsfValue.equals("")) {
                                            String extractedValue = (String) fileMetadataMap.get(cdsfName)
                                                    .toArray()[0];
                                            logger.fine("values: existing: " + cdsfValue + ", extracted: "
                                                    + extractedValue);
                                            if (cdsfValue.equals(extractedValue)) {
                                                matches++;
                                            }
                                        }
                                    }
                                    if (matches == nonEmptyFields) {
                                        alreadyExists = true;
                                        break;
                                    }
                                }

                                if (!alreadyExists) {
                                    // save this compound value, by attaching it to the 
                                    // version for proper cascading:
                                    compoundDsfv.setParentDatasetField(dsf);
                                    dsf.getDatasetFieldCompoundValues().add(compoundDsfv);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:edu.ku.brc.specify.conversion.ConvertVerifier.java

/**
 * /*  w ww .j av a2s. co  m*/
 */
private void verifyCEs() {
    newSQL = "SELECT c.CollectingEventID, c.StartTime, l.LocalityName, l.Latitude1, l.Longitude1, g.Name "
            + "FROM collectingevent c LEFT JOIN locality l ON c.LocalityID = l.LocalityID "
            + "LEFT JOIN geography g ON l.GeographyID = g.GeographyID ORDER BY c.CollectingEventID";

    oldSQL = "SELECT c.CollectingEventID, c.StartTime, l.LocalityName, l.Latitude1, l.Longitude1, g.ContinentOrOcean, g.Country, g.State,  g.County, g.IslandGroup, g.Island, g.WaterBody, g.Drainage "
            + "FROM collectingevent c LEFT JOIN locality l ON c.LocalityID = l.LocalityID "
            + "LEFT JOIN geography g ON l.GeographyID = g.GeographyID ORDER BY c.CollectingEventID";

    String newCntSQL = "SELECT count(*) "
            + "FROM collectingevent c LEFT JOIN locality l ON c.LocalityID = l.LocalityID "
            + "LEFT JOIN geography g ON l.GeographyID = g.GeographyID ORDER BY c.CollectingEventID";

    String oldCntSQL = "SELECT count(*) "
            + "FROM collectingevent c LEFT JOIN locality l ON c.LocalityID = l.LocalityID "
            + "LEFT JOIN geography g ON l.GeographyID = g.GeographyID ORDER BY c.CollectingEventID";

    log.info(newCntSQL);
    log.info(oldCntSQL);
    log.info(newSQL);
    log.info(oldSQL);

    Integer oldCnt = BasicSQLUtils.getCount(oldCntSQL);
    Integer newCnt = BasicSQLUtils.getCount(newCntSQL);
    String msg2 = "Record Counts [" + oldCnt + " / " + newCnt + "]";
    log.info(msg2);

    //tblWriter.logErrors("Record Counts", oldCnt + " / "  + newCnt);
    tblWriter.flush();

    try {
        getResultSets(oldSQL, newSQL);
        while (true) {

            boolean hasOldRec = oldDBRS.next();
            boolean hasNewRec = newDBRS.next();

            if (!hasOldRec || !hasNewRec) {
                break;
            }

            int col = 1;
            int newId = newDBRS.getInt(col++);
            Integer newStartTime = newDBRS.getInt(col++);
            String newLocalityName = newDBRS.getString(col++);

            Object bigDecObj = newDBRS.getObject(col);
            BigDecimal newLatitude = bigDecObj == null ? null : newDBRS.getBigDecimal(col);
            col++;

            bigDecObj = newDBRS.getObject(col);
            BigDecimal newLongitude = bigDecObj == null ? null : newDBRS.getBigDecimal(col);
            col++;

            String newGeoName = newDBRS.getString(col++);

            col = 1;
            int oldId = oldDBRS.getInt(col++);
            Integer oldStartTime = oldDBRS.getInt(col++);
            String oldLocalityName = oldDBRS.getString(col++);

            bigDecObj = newDBRS.getObject(col);
            Double oldLatitude = bigDecObj == null ? null : oldDBRS.getDouble(col);
            col++;

            bigDecObj = newDBRS.getObject(col);
            Double oldLongitude = bigDecObj == null ? null : oldDBRS.getDouble(col);
            col++;

            String oldNewIdStr = oldId + " / " + newId;

            if (newGeoName != null && !newGeoName.equals("Undefined")) {
                boolean fnd = false;
                for (int i = 6; i < 14; i++) {
                    //if (i == 7) System.out.println();
                    String name = oldDBRS.getString(i);
                    if (name != null) {
                        //System.out.println("["+name+"]");
                        if (name.equalsIgnoreCase(newGeoName)) {
                            fnd = true;
                            break;
                        }
                    }
                }

                if (!fnd) {
                    String msg = "No match found for new Geo [" + newGeoName + "] [" + oldId + " / " + newId
                            + "]";
                    log.error(msg);
                    tblWriter.logErrors(oldNewIdStr, msg);
                }
            }

            // StartTime
            if (oldStartTime == null && newStartTime != null) {
                String msg = "LocName[" + oldId + " / " + newId + "]  Old StartTime[" + oldStartTime
                        + "] is NULL   New StartTime[" + newStartTime + "] is not";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);

            } else if (oldStartTime != null && newStartTime == null) {
                String msg = "LocName[" + oldId + " / " + newId + "]  Old StartTime[" + oldStartTime
                        + "] is not null   New StartTime[" + newStartTime + "] is NULL";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);

            } else if (oldStartTime != null && newStartTime != null && !oldStartTime.equals(newStartTime)) {
                String msg = "LocName[" + oldId + " / " + newId + "]  Old StartTime[" + oldStartTime
                        + "] is NOT equals   New StartTime[" + newStartTime + "]";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            }

            // LocalityName
            if (oldLocalityName == null && newLocalityName != null) {
                String msg = "LocName[" + oldId + " / " + newId + "]  Old LocalityName[" + oldLocalityName
                        + "] is NULL   New LocalityName[" + newLocalityName + "] is not";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            } else if (oldLocalityName != null && newLocalityName == null) {
                String msg = "LocName[" + oldId + " / " + newId + "]  Old LocalityName[" + oldLocalityName
                        + "] is not null   New LocalityName[" + newLocalityName + "] is NULL";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            } else if (oldLocalityName != null && newLocalityName != null
                    && !oldLocalityName.equals(newLocalityName)) {
                String msg = "LocName[" + oldId + " / " + newId + "]  Old LocalityName[" + oldLocalityName
                        + "] is NOT equals   New LocalityName[" + newLocalityName + "]";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            }

            // Latitude
            if (oldLatitude == null && newLatitude != null) {
                String msg = "Latitude[" + oldId + " / " + newId + "]  Old Latitude[" + oldLatitude
                        + "] is NULL   New Latitude[" + newLatitude + "] is not";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            } else if (oldLatitude != null && newLatitude == null) {
                String msg = "Latitude[" + oldId + " / " + newId + "]  Old Latitude[" + oldLatitude
                        + "] is not null   New Latitude[" + newLatitude + "] is NULL";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            } else if (oldLatitude != null && newLatitude != null
                    && !oldLatitude.equals(newLatitude.doubleValue())) {
                String msg = "Latitude[" + oldId + " / " + newId + "]  Old Latitude[" + oldLatitude
                        + "] is NOT equals   New Latitude[" + newLatitude + "]";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            }

            // Longitude
            if (oldLongitude == null && newLongitude != null) {
                String msg = "Longitude[" + oldId + " / " + newId + "]  Old Longitude[" + oldLongitude
                        + "] is NULL   New Longitude[" + newLongitude + "] is not";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            } else if (oldLongitude != null && newLongitude == null) {
                String msg = "Longitude[" + oldId + " / " + newId + "]  Old Longitude[" + oldLongitude
                        + "] is not null   New Longitude[" + newLongitude + "] is NULL";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            } else if (oldLongitude != null && newLongitude != null
                    && !oldLongitude.equals(newLongitude.doubleValue())) {
                String msg = "Longitude[" + oldId + " / " + newId + "]  Old Longitude[" + oldLongitude
                        + "] is NOT equals   New Longitude[" + newLongitude + "]";
                log.error(msg);
                tblWriter.logErrors(oldNewIdStr, msg);
            }
        }

        oldDBRS.close();
        newDBRS.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java

protected double getDataAverage(Node dataNode, int col, int numRows) {
    double value = 0;
    double dummy = 0;
    int numRowsUsed = 0;
    for (int row = 0; row < numRows; row++) {
        Node data = dataNode.getChildNodes().item(numRows - 1 - row).getChildNodes().item(col + 1);
        Double currentDataAsDouble = Double.valueOf(getXMLNodeValue(data));
        if (!currentDataAsDouble.equals(Double.NaN)) {
            numRowsUsed += 1;/* w  ww .jav a 2 s.  c om*/
            value += currentDataAsDouble;
        }
    }

    if (numRowsUsed == 0) {
        if ((!Double.isInfinite(value)) && (!Double.isNaN(value))) {
            return value;
        } else {
            s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows=0");
            return dummy;
        }
    } else {
        if ((!Double.isInfinite(value / numRowsUsed)) && (!Double.isNaN(value / numRowsUsed))) {
            return (value / numRowsUsed);
        } else {
            s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows>0");
            return dummy;
        }
    }

}

From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java

public String editTitle() {
    if (pageTitle == null || pageTitle.equals("")) {
        return "notitle";
    }/* w w  w .j  av a2s . co m*/

    // because we're using a security advisor, need to make sure it's OK ourselves
    if (!canEditPage()) {
        return "permission-failed";
    }
    if (!checkCsrf())
        return "permission-failed";

    Placement placement = toolManager.getCurrentPlacement();
    SimplePage page = getCurrentPage();
    SimplePageItem pageItem = getCurrentPageItem(null);
    Site site = getCurrentSite();
    boolean needRecompute = false;

    if (page.getOwner() == null && getEditPrivs() == 0) {
        // update gradebook link if necessary
        Double currentPoints = page.getGradebookPoints();
        Double newPoints = null;

        if (points != null) {
            try {
                newPoints = Double.parseDouble(points);
                if (newPoints == 0.0)
                    newPoints = null;
            } catch (Exception ignore) {
                newPoints = null;
            }
        }
        // adjust gradebook entry
        boolean add = false;
        if (newPoints == null && currentPoints != null) {
            add = gradebookIfc.removeExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId());
        } else if (newPoints != null && currentPoints == null) {
            add = gradebookIfc.addExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId(), null,
                    pageTitle, newPoints, null, "Lesson Builder");

            if (!add) {
                setErrMessage(messageLocator.getMessage("simplepage.no-gradebook"));
            } else
                needRecompute = true;
        } else if (currentPoints != null
                && (!currentPoints.equals(newPoints) || !pageTitle.equals(page.getTitle()))) {
            add = gradebookIfc.updateExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId(),
                    null, pageTitle, newPoints, null);
            if (!add) {
                setErrMessage(messageLocator.getMessage("simplepage.no-gradebook"));
            } else if (!currentPoints.equals(newPoints))
                needRecompute = true;
        }
        if (add)
            page.setGradebookPoints(newPoints);
        boolean oldDownloads = site.getProperties().getProperty("lessonbuilder-nodownloadlinks") != null;
        if (oldDownloads != nodownloads) {
            if (oldDownloads)
                site.getPropertiesEdit().removeProperty("lessonbuilder-nodownloadlinks");
            else if (nodownloads)
                site.getPropertiesEdit().addProperty("lessonbuilder-nodownloadlinks", "true");
            try {
                siteService.save(site);
            } catch (Exception e) {
                log.error("editTitle unable to save site " + e);
            }

        }
    }

    if (pageTitle != null && pageItem.getPageId() == 0) {
        try {
            // we need a security advisor because we're allowing users to edit the page if they
            // have
            // simplepage.upd privileges, but site.save requires site.upd.
            securityService.pushAdvisor(new SecurityAdvisor() {
                public SecurityAdvice isAllowed(String userId, String function, String reference) {
                    if (function.equals(SITE_UPD) && reference.equals("/site/" + getCurrentSiteId())) {
                        return SecurityAdvice.ALLOWED;
                    } else {
                        return SecurityAdvice.PASS;
                    }
                }
            });

            SitePage sitePage = site.getPage(page.getToolId());

            for (ToolConfiguration t : sitePage.getTools()) {
                if (t.getId().equals(placement.getId()))
                    t.setTitle(pageTitle);
            }

            sitePage.setTitle(pageTitle);
            siteService.save(site);
            page.setTitle(pageTitle);
            page.setHidden(hidePage);
            if (hasReleaseDate)
                page.setReleaseDate(releaseDate);
            else
                page.setReleaseDate(null);
            update(page);
            updateCurrentPage();
            placement.setTitle(pageTitle);
            placement.save();
            pageVisibilityHelper(site, page.getToolId(), !hidePage);
            pageItem.setPrerequisite(prerequisite);
            pageItem.setRequired(required);
            pageItem.setName(pageTitle);
            update(pageItem);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            securityService.popAdvisor();
        }
    } else if (pageTitle != null) {
        page.setTitle(pageTitle);
        page.setHidden(hidePage);
        if (hasReleaseDate)
            page.setReleaseDate(releaseDate);
        else
            page.setReleaseDate(null);
        update(page);
    }

    if (pageTitle != null) {
        if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT) {
            SimpleStudentPage student = simplePageToolDao.findStudentPageByPageId(page.getPageId());
            student.setTitle(pageTitle);
            update(student, false);
        } else {
            pageItem.setName(pageTitle);
            update(pageItem);
        }

        adjustPath("", pageItem.getPageId(), pageItem.getId(), pageTitle);
    }

    String collectionId = contentHostingService.getSiteCollection(getCurrentSiteId()) + "LB-CSS/";
    String uploadId = uploadFile(collectionId);
    if (uploadId != null) {
        page.setCssSheet(uploadId);

        // Make sure the relevant caches are wiped clean.
        resourceCache.remove(collectionId);
        resourceCache.remove(uploadId);
    } else {
        page.setCssSheet(dropDown);
    }

    update(page);

    // have to do this after the page itself is updated
    if (needRecompute)
        recomputeGradebookEntries(page.getPageId(), points);
    // points, not newPoints because API wants a string

    if (pageItem.getPageId() == 0) {
        return "reload";
    } else {
        return "success";
    }
}