Example usage for java.lang Double longBitsToDouble

List of usage examples for java.lang Double longBitsToDouble

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static native double longBitsToDouble(long bits);

Source Link

Document

Returns the double value corresponding to a given bit representation.

Usage

From source file:org.apache.solr.schema.TestUseDocValuesAsStored.java

private String[] nextValues(int arity, String valueType) throws Exception {
    String[] values = new String[arity];
    for (int i = 0; i < arity; ++i) {
        switch (valueType) {
        case "int":
            values[i] = String.valueOf(random().nextInt());
            break;
        case "double":
            values[i] = String.valueOf(Double.longBitsToDouble(random().nextLong()));
            break;
        case "long":
            values[i] = String.valueOf(random().nextLong());
            break;
        case "float":
            values[i] = String.valueOf(Float.intBitsToFloat(random().nextInt()));
            break;
        case "enum":
            values[i] = SEVERITY[TestUtil.nextInt(random(), 0, SEVERITY.length - 1)];
            break;
        case "str": {
            String str = TestUtil.randomRealisticUnicodeString(random());
            values[i] = BAD_CHAR_PATTERN.matcher(str).replaceAll("\uFFFD");
            break;
        }//from   ww  w.  ja va 2s.  co  m
        case "date": {
            long epochMillis = TestUtil.nextLong(random(), START_RANDOM_EPOCH_MILLIS, END_RANDOM_EPOCH_MILLIS);
            values[i] = Instant.ofEpochMilli(epochMillis).toString();
            break;
        }
        default:
            throw new Exception("unknown type '" + valueType + "'");
        }
    }
    return values;
}

From source file:savant.file.SavantROFile.java

@Override
public synchronized double readDouble() throws IOException {
    byte[] bytes = new byte[8];
    int result = read(bytes);
    if (result != 8) {
        LOG.warn("Could not read 8 bytes for a double");
        throw new IOException("At EOF");
    }//  w w  w.  j av a 2s  .co  m
    long longBits = ((long) bytes[0] & 0xFF) << 56 | ((long) bytes[1] & 0xFF) << 48
            | ((long) bytes[2] & 0xFF) << 40 | ((long) bytes[3] & 0xFF) << 32 | ((long) bytes[4] & 0xFF) << 24
            | ((long) bytes[5] & 0xFF) << 16 | ((long) bytes[6] & 0xFF) << 8 | ((long) bytes[7] & 0xFF);
    return Double.longBitsToDouble(longBits);
}

From source file:com.siemens.industrialbenchmark.dynamics.IndustrialBenchmarkDynamics.java

/**
 * This function applies an action to the industrial benchmark
 * @param aAction The industrial benchmark action
 * @return The successor state/*from w  ww.j  a  va  2 s .  c o m*/
 * @throws PropertiesException
 */
@Override
public double step(DataVector aAction) {

    // apply randomSeed to PRNGs and external drivers + filter (e.g. setpoint)
    this.rda.reSeed(randomSeed);
    for (ExternalDriver d : externalDrivers) {
        d.setSeed(rda.nextLong(0, Long.MAX_VALUE));
        d.filter(this.markovState);
    }

    // add actions to state:
    addAction((ActionDelta) aAction);

    try {
        // update spiking dynamics
        updateFatigue();

        // updated current operationalcost
        updateCurrentOperationalCost();

    } catch (PropertiesException e) {
        e.printStackTrace();
    }

    // update convoluted operationalcosts
    updateOperationalCostCovolution();

    // update gs
    updateGS();

    updateOperationalCosts();

    // update reward
    mRewardCore.calcReward(markovState);

    // set random seed for next iteration
    this.randomSeed = rda.nextLong(0, Long.MAX_VALUE);
    this.markovState.setValue(MarkovianStateDescription.RandomSeed, Double.longBitsToDouble(this.randomSeed));

    //return observableState;        
    return this.markovState.getValue(ObservableStateDescription.RewardTotal);
}

From source file:com.ebay.nest.io.sede.binarysortable.BinarySortableSerDe.java

static Object deserialize(InputByteBuffer buffer, TypeInfo type, boolean invert, Object reuse)
        throws IOException {

    // Is this field a null?
    byte isNull = buffer.read(invert);
    if (isNull == 0) {
        return null;
    }//from w w  w.  j  av  a  2s .c o m
    assert (isNull == 1);

    switch (type.getCategory()) {
    case PRIMITIVE: {
        PrimitiveTypeInfo ptype = (PrimitiveTypeInfo) type;
        switch (ptype.getPrimitiveCategory()) {
        case VOID: {
            return null;
        }
        case BOOLEAN: {
            BooleanWritable r = reuse == null ? new BooleanWritable() : (BooleanWritable) reuse;
            byte b = buffer.read(invert);
            assert (b == 1 || b == 2);
            r.set(b == 2);
            return r;
        }
        case BYTE: {
            ByteWritable r = reuse == null ? new ByteWritable() : (ByteWritable) reuse;
            r.set((byte) (buffer.read(invert) ^ 0x80));
            return r;
        }
        case SHORT: {
            ShortWritable r = reuse == null ? new ShortWritable() : (ShortWritable) reuse;
            int v = buffer.read(invert) ^ 0x80;
            v = (v << 8) + (buffer.read(invert) & 0xff);
            r.set((short) v);
            return r;
        }
        case INT: {
            IntWritable r = reuse == null ? new IntWritable() : (IntWritable) reuse;
            r.set(deserializeInt(buffer, invert));
            return r;
        }
        case LONG: {
            LongWritable r = reuse == null ? new LongWritable() : (LongWritable) reuse;
            long v = buffer.read(invert) ^ 0x80;
            for (int i = 0; i < 7; i++) {
                v = (v << 8) + (buffer.read(invert) & 0xff);
            }
            r.set(v);
            return r;
        }
        case FLOAT: {
            FloatWritable r = reuse == null ? new FloatWritable() : (FloatWritable) reuse;
            int v = 0;
            for (int i = 0; i < 4; i++) {
                v = (v << 8) + (buffer.read(invert) & 0xff);
            }
            if ((v & (1 << 31)) == 0) {
                // negative number, flip all bits
                v = ~v;
            } else {
                // positive number, flip the first bit
                v = v ^ (1 << 31);
            }
            r.set(Float.intBitsToFloat(v));
            return r;
        }
        case DOUBLE: {
            DoubleWritable r = reuse == null ? new DoubleWritable() : (DoubleWritable) reuse;
            long v = 0;
            for (int i = 0; i < 8; i++) {
                v = (v << 8) + (buffer.read(invert) & 0xff);
            }
            if ((v & (1L << 63)) == 0) {
                // negative number, flip all bits
                v = ~v;
            } else {
                // positive number, flip the first bit
                v = v ^ (1L << 63);
            }
            r.set(Double.longBitsToDouble(v));
            return r;
        }
        case STRING: {
            Text r = reuse == null ? new Text() : (Text) reuse;
            return deserializeText(buffer, invert, r);
        }

        case VARCHAR: {
            HiveVarcharWritable r = reuse == null ? new HiveVarcharWritable() : (HiveVarcharWritable) reuse;
            // Use HiveVarchar's internal Text member to read the value.
            deserializeText(buffer, invert, r.getTextValue());
            // If we cache helper data for deserialization we could avoid having
            // to call getVarcharMaxLength() on every deserialize call.
            r.enforceMaxLength(getVarcharMaxLength(type));
            return r;
        }

        case BINARY: {
            BytesWritable bw = new BytesWritable();
            // Get the actual length first
            int start = buffer.tell();
            int length = 0;
            do {
                byte b = buffer.read(invert);
                if (b == 0) {
                    // end of string
                    break;
                }
                if (b == 1) {
                    // the last char is an escape char. read the actual char
                    buffer.read(invert);
                }
                length++;
            } while (true);

            if (length == buffer.tell() - start) {
                // No escaping happened, so we are already done.
                bw.set(buffer.getData(), start, length);
            } else {
                // Escaping happened, we need to copy byte-by-byte.
                // 1. Set the length first.
                bw.set(buffer.getData(), start, length);
                // 2. Reset the pointer.
                buffer.seek(start);
                // 3. Copy the data.
                byte[] rdata = bw.getBytes();
                for (int i = 0; i < length; i++) {
                    byte b = buffer.read(invert);
                    if (b == 1) {
                        // The last char is an escape char, read the actual char.
                        // The serialization format escape \0 to \1, and \1 to \2,
                        // to make sure the string is null-terminated.
                        b = (byte) (buffer.read(invert) - 1);
                    }
                    rdata[i] = b;
                }
                // 4. Read the null terminator.
                byte b = buffer.read(invert);
                assert (b == 0);
            }
            return bw;
        }

        case DATE: {
            DateWritable d = reuse == null ? new DateWritable() : (DateWritable) reuse;
            d.set(deserializeInt(buffer, invert));
            return d;
        }

        case TIMESTAMP:
            TimestampWritable t = (reuse == null ? new TimestampWritable() : (TimestampWritable) reuse);
            byte[] bytes = new byte[TimestampWritable.BINARY_SORTABLE_LENGTH];

            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = buffer.read(invert);
            }
            t.setBinarySortable(bytes, 0);
            return t;

        case DECIMAL: {
            // See serialization of decimal for explanation (below)

            HiveDecimalWritable bdw = (reuse == null ? new HiveDecimalWritable() : (HiveDecimalWritable) reuse);

            int b = buffer.read(invert) - 1;
            assert (b == 1 || b == -1 || b == 0);
            boolean positive = b != -1;

            int factor = buffer.read(invert) ^ 0x80;
            for (int i = 0; i < 3; i++) {
                factor = (factor << 8) + (buffer.read(invert) & 0xff);
            }

            if (!positive) {
                factor = -factor;
            }

            int start = buffer.tell();
            int length = 0;

            do {
                b = buffer.read(positive ? invert : !invert);
                assert (b != 1);

                if (b == 0) {
                    // end of digits
                    break;
                }

                length++;
            } while (true);

            if (decimalBuffer == null || decimalBuffer.length < length) {
                decimalBuffer = new byte[length];
            }

            buffer.seek(start);
            for (int i = 0; i < length; ++i) {
                decimalBuffer[i] = buffer.read(positive ? invert : !invert);
            }

            // read the null byte again
            buffer.read(positive ? invert : !invert);

            String digits = new String(decimalBuffer, 0, length, decimalCharSet);
            BigInteger bi = new BigInteger(digits);
            HiveDecimal bd = new HiveDecimal(bi).scaleByPowerOfTen(factor - length);

            if (!positive) {
                bd = bd.negate();
            }

            bdw.set(bd);
            return bdw;
        }

        default: {
            throw new RuntimeException("Unrecognized type: " + ptype.getPrimitiveCategory());
        }
        }
    }

    case LIST: {
        ListTypeInfo ltype = (ListTypeInfo) type;
        TypeInfo etype = ltype.getListElementTypeInfo();

        // Create the list if needed
        ArrayList<Object> r = reuse == null ? new ArrayList<Object>() : (ArrayList<Object>) reuse;

        // Read the list
        int size = 0;
        while (true) {
            int more = buffer.read(invert);
            if (more == 0) {
                // \0 to terminate
                break;
            }
            // \1 followed by each element
            assert (more == 1);
            if (size == r.size()) {
                r.add(null);
            }
            r.set(size, deserialize(buffer, etype, invert, r.get(size)));
            size++;
        }
        // Remove additional elements if the list is reused
        while (r.size() > size) {
            r.remove(r.size() - 1);
        }
        return r;
    }
    case MAP: {
        MapTypeInfo mtype = (MapTypeInfo) type;
        TypeInfo ktype = mtype.getMapKeyTypeInfo();
        TypeInfo vtype = mtype.getMapValueTypeInfo();

        // Create the map if needed
        Map<Object, Object> r;
        if (reuse == null) {
            r = new HashMap<Object, Object>();
        } else {
            r = (HashMap<Object, Object>) reuse;
            r.clear();
        }

        while (true) {
            int more = buffer.read(invert);
            if (more == 0) {
                // \0 to terminate
                break;
            }
            // \1 followed by each key and then each value
            assert (more == 1);
            Object k = deserialize(buffer, ktype, invert, null);
            Object v = deserialize(buffer, vtype, invert, null);
            r.put(k, v);
        }
        return r;
    }
    case STRUCT: {
        StructTypeInfo stype = (StructTypeInfo) type;
        List<TypeInfo> fieldTypes = stype.getAllStructFieldTypeInfos();
        int size = fieldTypes.size();
        // Create the struct if needed
        ArrayList<Object> r = reuse == null ? new ArrayList<Object>(size) : (ArrayList<Object>) reuse;
        assert (r.size() <= size);
        // Set the size of the struct
        while (r.size() < size) {
            r.add(null);
        }
        // Read one field by one field
        for (int eid = 0; eid < size; eid++) {
            r.set(eid, deserialize(buffer, fieldTypes.get(eid), invert, r.get(eid)));
        }
        return r;
    }
    case UNION: {
        UnionTypeInfo utype = (UnionTypeInfo) type;
        StandardUnion r = reuse == null ? new StandardUnion() : (StandardUnion) reuse;
        // Read the tag
        byte tag = buffer.read(invert);
        r.setTag(tag);
        r.setObject(deserialize(buffer, utype.getAllUnionObjectTypeInfos().get(tag), invert, null));
        return r;
    }
    default: {
        throw new RuntimeException("Unrecognized type: " + type.getCategory());
    }
    }
}

From source file:org.apache.hadoop.hive.serde2.binarysortable.fast.BinarySortableDeserializeRead.java

@Override
public double readDouble() throws IOException {
    final boolean invert = columnSortOrderIsDesc[fieldIndex];
    long v = 0;//from w w w  .  j av  a 2 s .com
    for (int i = 0; i < 8; i++) {
        v = (v << 8) + (inputByteBuffer.read(invert) & 0xff);
    }
    if ((v & (1L << 63)) == 0) {
        // negative number, flip all bits
        v = ~v;
    } else {
        // positive number, flip the first bit
        v = v ^ (1L << 63);
    }
    return Double.longBitsToDouble(v);
}

From source file:com.meetup.memcached.NativeHandler.java

protected static Double decodeDouble(byte[] b) throws Exception {
    Long l = decodeLong(b);//  w w  w.  j av  a 2 s. c om
    return Double.valueOf(Double.longBitsToDouble(l.longValue()));
}

From source file:org.paxle.se.index.lucene.impl.Converter.java

private static Number field2number(Fieldable lfield, org.paxle.core.doc.Field<?> pfield) {
    final long num;
    if (pfield.isIndex()) {
        num = PaxleNumberTools.stringToLong(lfield.stringValue());
    } else {/*  ww  w . j a  v a2 s .  co m*/
        num = PaxleNumberTools.toLong(lfield.binaryValue());
    }

    if (Double.class.isAssignableFrom(pfield.getType())) {
        return Double.valueOf(Double.longBitsToDouble(num));
    } else if (Float.class.isAssignableFrom(pfield.getType())) {
        return Float.valueOf(Float.intBitsToFloat((int) num));
    } else {
        return Long.valueOf(num);
    }
}

From source file:org.apache.hadoop.hive.serde2.binarysortable.BinarySortableSerDe.java

static Object deserialize(InputByteBuffer buffer, TypeInfo type, boolean invert, Object reuse)
        throws IOException {

    // Is this field a null?
    byte isNull = buffer.read(invert);
    if (isNull == 0) {
        return null;
    }/*from   w  ww.ja  v  a  2 s .c  om*/
    assert (isNull == 1);

    switch (type.getCategory()) {
    case PRIMITIVE: {
        PrimitiveTypeInfo ptype = (PrimitiveTypeInfo) type;
        switch (ptype.getPrimitiveCategory()) {
        case VOID: {
            return null;
        }
        case BOOLEAN: {
            BooleanWritable r = reuse == null ? new BooleanWritable() : (BooleanWritable) reuse;
            byte b = buffer.read(invert);
            assert (b == 1 || b == 2);
            r.set(b == 2);
            return r;
        }
        case BYTE: {
            ByteWritable r = reuse == null ? new ByteWritable() : (ByteWritable) reuse;
            r.set((byte) (buffer.read(invert) ^ 0x80));
            return r;
        }
        case SHORT: {
            ShortWritable r = reuse == null ? new ShortWritable() : (ShortWritable) reuse;
            int v = buffer.read(invert) ^ 0x80;
            v = (v << 8) + (buffer.read(invert) & 0xff);
            r.set((short) v);
            return r;
        }
        case INT: {
            IntWritable r = reuse == null ? new IntWritable() : (IntWritable) reuse;
            r.set(deserializeInt(buffer, invert));
            return r;
        }
        case LONG: {
            LongWritable r = reuse == null ? new LongWritable() : (LongWritable) reuse;
            r.set(deserializeLong(buffer, invert));
            return r;
        }
        case FLOAT: {
            FloatWritable r = reuse == null ? new FloatWritable() : (FloatWritable) reuse;
            int v = 0;
            for (int i = 0; i < 4; i++) {
                v = (v << 8) + (buffer.read(invert) & 0xff);
            }
            if ((v & (1 << 31)) == 0) {
                // negative number, flip all bits
                v = ~v;
            } else {
                // positive number, flip the first bit
                v = v ^ (1 << 31);
            }
            r.set(Float.intBitsToFloat(v));
            return r;
        }
        case DOUBLE: {
            DoubleWritable r = reuse == null ? new DoubleWritable() : (DoubleWritable) reuse;
            long v = 0;
            for (int i = 0; i < 8; i++) {
                v = (v << 8) + (buffer.read(invert) & 0xff);
            }
            if ((v & (1L << 63)) == 0) {
                // negative number, flip all bits
                v = ~v;
            } else {
                // positive number, flip the first bit
                v = v ^ (1L << 63);
            }
            r.set(Double.longBitsToDouble(v));
            return r;
        }
        case STRING: {
            Text r = reuse == null ? new Text() : (Text) reuse;
            return deserializeText(buffer, invert, r);
        }

        case CHAR: {
            HiveCharWritable r = reuse == null ? new HiveCharWritable() : (HiveCharWritable) reuse;
            // Use internal text member to read value
            deserializeText(buffer, invert, r.getTextValue());
            r.enforceMaxLength(getCharacterMaxLength(type));
            return r;
        }

        case VARCHAR: {
            HiveVarcharWritable r = reuse == null ? new HiveVarcharWritable() : (HiveVarcharWritable) reuse;
            // Use HiveVarchar's internal Text member to read the value.
            deserializeText(buffer, invert, r.getTextValue());
            // If we cache helper data for deserialization we could avoid having
            // to call getVarcharMaxLength() on every deserialize call.
            r.enforceMaxLength(getCharacterMaxLength(type));
            return r;
        }

        case BINARY: {
            BytesWritable bw = new BytesWritable();
            // Get the actual length first
            int start = buffer.tell();
            int length = 0;
            do {
                byte b = buffer.read(invert);
                if (b == 0) {
                    // end of string
                    break;
                }
                if (b == 1) {
                    // the last char is an escape char. read the actual char
                    buffer.read(invert);
                }
                length++;
            } while (true);

            if (length == buffer.tell() - start) {
                // No escaping happened, so we are already done.
                bw.set(buffer.getData(), start, length);
            } else {
                // Escaping happened, we need to copy byte-by-byte.
                // 1. Set the length first.
                bw.set(buffer.getData(), start, length);
                // 2. Reset the pointer.
                buffer.seek(start);
                // 3. Copy the data.
                byte[] rdata = bw.getBytes();
                for (int i = 0; i < length; i++) {
                    byte b = buffer.read(invert);
                    if (b == 1) {
                        // The last char is an escape char, read the actual char.
                        // The serialization format escape \0 to \1, and \1 to \2,
                        // to make sure the string is null-terminated.
                        b = (byte) (buffer.read(invert) - 1);
                    }
                    rdata[i] = b;
                }
                // 4. Read the null terminator.
                byte b = buffer.read(invert);
                assert (b == 0);
            }
            return bw;
        }

        case DATE: {
            DateWritable d = reuse == null ? new DateWritable() : (DateWritable) reuse;
            d.set(deserializeInt(buffer, invert));
            return d;
        }

        case TIMESTAMP:
            TimestampWritable t = (reuse == null ? new TimestampWritable() : (TimestampWritable) reuse);
            byte[] bytes = new byte[TimestampWritable.BINARY_SORTABLE_LENGTH];

            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = buffer.read(invert);
            }
            t.setBinarySortable(bytes, 0);
            return t;

        case INTERVAL_YEAR_MONTH: {
            HiveIntervalYearMonthWritable i = reuse == null ? new HiveIntervalYearMonthWritable()
                    : (HiveIntervalYearMonthWritable) reuse;
            i.set(deserializeInt(buffer, invert));
            return i;
        }

        case INTERVAL_DAY_TIME: {
            HiveIntervalDayTimeWritable i = reuse == null ? new HiveIntervalDayTimeWritable()
                    : (HiveIntervalDayTimeWritable) reuse;
            long totalSecs = deserializeLong(buffer, invert);
            int nanos = deserializeInt(buffer, invert);
            i.set(totalSecs, nanos);
            return i;
        }

        case DECIMAL: {
            // See serialization of decimal for explanation (below)

            HiveDecimalWritable bdw = (reuse == null ? new HiveDecimalWritable() : (HiveDecimalWritable) reuse);

            int b = buffer.read(invert) - 1;
            assert (b == 1 || b == -1 || b == 0);
            boolean positive = b != -1;

            int factor = buffer.read(invert) ^ 0x80;
            for (int i = 0; i < 3; i++) {
                factor = (factor << 8) + (buffer.read(invert) & 0xff);
            }

            if (!positive) {
                factor = -factor;
            }

            int start = buffer.tell();
            int length = 0;

            do {
                b = buffer.read(positive ? invert : !invert);
                assert (b != 1);

                if (b == 0) {
                    // end of digits
                    break;
                }

                length++;
            } while (true);

            if (decimalBuffer == null || decimalBuffer.length < length) {
                decimalBuffer = new byte[length];
            }

            buffer.seek(start);
            for (int i = 0; i < length; ++i) {
                decimalBuffer[i] = buffer.read(positive ? invert : !invert);
            }

            // read the null byte again
            buffer.read(positive ? invert : !invert);

            String digits = new String(decimalBuffer, 0, length, decimalCharSet);
            BigInteger bi = new BigInteger(digits);
            HiveDecimal bd = HiveDecimal.create(bi).scaleByPowerOfTen(factor - length);

            if (!positive) {
                bd = bd.negate();
            }

            bdw.set(bd);
            return bdw;
        }

        default: {
            throw new RuntimeException("Unrecognized type: " + ptype.getPrimitiveCategory());
        }
        }
    }

    case LIST: {
        ListTypeInfo ltype = (ListTypeInfo) type;
        TypeInfo etype = ltype.getListElementTypeInfo();

        // Create the list if needed
        ArrayList<Object> r = reuse == null ? new ArrayList<Object>() : (ArrayList<Object>) reuse;

        // Read the list
        int size = 0;
        while (true) {
            int more = buffer.read(invert);
            if (more == 0) {
                // \0 to terminate
                break;
            }
            // \1 followed by each element
            assert (more == 1);
            if (size == r.size()) {
                r.add(null);
            }
            r.set(size, deserialize(buffer, etype, invert, r.get(size)));
            size++;
        }
        // Remove additional elements if the list is reused
        while (r.size() > size) {
            r.remove(r.size() - 1);
        }
        return r;
    }
    case MAP: {
        MapTypeInfo mtype = (MapTypeInfo) type;
        TypeInfo ktype = mtype.getMapKeyTypeInfo();
        TypeInfo vtype = mtype.getMapValueTypeInfo();

        // Create the map if needed
        Map<Object, Object> r;
        if (reuse == null) {
            r = new HashMap<Object, Object>();
        } else {
            r = (HashMap<Object, Object>) reuse;
            r.clear();
        }

        while (true) {
            int more = buffer.read(invert);
            if (more == 0) {
                // \0 to terminate
                break;
            }
            // \1 followed by each key and then each value
            assert (more == 1);
            Object k = deserialize(buffer, ktype, invert, null);
            Object v = deserialize(buffer, vtype, invert, null);
            r.put(k, v);
        }
        return r;
    }
    case STRUCT: {
        StructTypeInfo stype = (StructTypeInfo) type;
        List<TypeInfo> fieldTypes = stype.getAllStructFieldTypeInfos();
        int size = fieldTypes.size();
        // Create the struct if needed
        ArrayList<Object> r = reuse == null ? new ArrayList<Object>(size) : (ArrayList<Object>) reuse;
        assert (r.size() <= size);
        // Set the size of the struct
        while (r.size() < size) {
            r.add(null);
        }
        // Read one field by one field
        for (int eid = 0; eid < size; eid++) {
            r.set(eid, deserialize(buffer, fieldTypes.get(eid), invert, r.get(eid)));
        }
        return r;
    }
    case UNION: {
        UnionTypeInfo utype = (UnionTypeInfo) type;
        StandardUnion r = reuse == null ? new StandardUnion() : (StandardUnion) reuse;
        // Read the tag
        byte tag = buffer.read(invert);
        r.setTag(tag);
        r.setObject(deserialize(buffer, utype.getAllUnionObjectTypeInfos().get(tag), invert, null));
        return r;
    }
    default: {
        throw new RuntimeException("Unrecognized type: " + type.getCategory());
    }
    }
}

From source file:it.geosolutions.geocollect.android.core.mission.utils.MissionUtils.java

/**
 * get "created" {@link MissionFeature} from the database, adding the distance property if possible
 * @param tableName//from w  w w . jav  a  2  s.  c o  m
 * @param db
 * @return a list of created {@link MissionFeature}
 */
public static ArrayList<MissionFeature> getMissionFeatures(final String mTableName, final Database db,
        Context ctx) {

    ArrayList<MissionFeature> mFeaturesList = new ArrayList<MissionFeature>();

    String tableName = mTableName;

    // Reader for the Geometry field
    WKBReader wkbReader = new WKBReader();

    //create query
    ////////////////////////////////////////////////////////////////
    // SQLite Geometry cannot be read with direct wkbreader
    // We must do a double conversion with ST_AsBinary and CastToXY 
    ////////////////////////////////////////////////////////////////

    // Cycle all the columns to find the "Point" type one
    HashMap<String, String> columns = SpatialiteUtils.getPropertiesFields(db, tableName);
    if (columns == null) {
        if (BuildConfig.DEBUG) {
            Log.w(TAG, "Cannot retrieve columns from database");
        }
        return mFeaturesList;
    }

    List<String> selectFields = new ArrayList<String>();
    for (String columnName : columns.keySet()) {
        //Spatialite custom field point
        if ("point".equalsIgnoreCase(columns.get(columnName))) {
            selectFields.add("ST_AsBinary(CastToXY(" + columnName + ")) AS GEOMETRY");
        } else {
            selectFields.add(columnName);
        }
    }

    // Merge all the column names
    String selectString = TextUtils.join(",", selectFields);

    if (ctx != null) {

        SharedPreferences prefs = ctx.getSharedPreferences(SQLiteCascadeFeatureLoader.PREF_NAME,
                Context.MODE_PRIVATE);

        boolean useDistance = prefs.getBoolean(SQLiteCascadeFeatureLoader.ORDER_BY_DISTANCE, false);
        double posX = Double.longBitsToDouble(
                prefs.getLong(SQLiteCascadeFeatureLoader.LOCATION_X, Double.doubleToLongBits(0)));
        double posY = Double.longBitsToDouble(
                prefs.getLong(SQLiteCascadeFeatureLoader.LOCATION_Y, Double.doubleToLongBits(0)));

        if (useDistance) {
            selectString = selectString + ", Distance(ST_Transform(GEOMETRY,4326), MakePoint(" + posX + ","
                    + posY + ", 4326)) * 111195 AS '" + MissionFeature.DISTANCE_VALUE_ALIAS + "'";
        }

        //Add Spatial filtering
        int filterSrid = prefs.getInt(SQLiteCascadeFeatureLoader.FILTER_SRID, -1);
        // If the SRID is not defined, skip the filter
        if (filterSrid != -1) {
            double filterN = Double.longBitsToDouble(
                    prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_N, Double.doubleToLongBits(0)));
            double filterS = Double.longBitsToDouble(
                    prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_S, Double.doubleToLongBits(0)));
            double filterW = Double.longBitsToDouble(
                    prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_W, Double.doubleToLongBits(0)));
            double filterE = Double.longBitsToDouble(
                    prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_E, Double.doubleToLongBits(0)));

            tableName += " WHERE MbrIntersects(GEOMETRY, BuildMbr(" + filterW + ", " + filterN + ", " + filterE
                    + ", " + filterS + ")) ";
        }

    }

    // Build the query
    StringWriter queryWriter = new StringWriter();
    queryWriter.append("SELECT ").append(selectString).append(" FROM ").append(tableName).append(";");

    // The resulting query
    String query = queryWriter.toString();

    Stmt stmt;
    //do the query
    if (jsqlite.Database.complete(query)) {
        try {
            if (BuildConfig.DEBUG) {
                Log.i("getCreatedMissionFeatures", "Loading from query: " + query);
            }
            stmt = db.prepare(query);
            MissionFeature f;
            while (stmt.step()) {
                f = new MissionFeature();

                SpatialiteUtils.populateFeatureFromStmt(wkbReader, stmt, f);

                if (f.geometry == null) {
                    //workaround for a bug which does not read out the "Point" geometry in WKBreader
                    //read single x and y coordinates instead and create the geometry by hand
                    double[] xy = PersistenceUtils.getXYCoord(db, tableName, f.id);
                    if (xy != null) {
                        GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4326);
                        f.geometry = geometryFactory.createPoint(new Coordinate(xy[0], xy[1]));
                    }
                }
                f.typeName = mTableName;
                mFeaturesList.add(f);
            }
            stmt.close();
        } catch (Exception e) {
            Log.d(TAG, "Error getCreatedMissions", e);
        }
    } else {
        if (BuildConfig.DEBUG) {
            Log.w(TAG, "Query is not complete: " + query);
        }
    }

    return mFeaturesList;
}

From source file:com.addthis.hydra.data.tree.prop.DataReservoir.java

private static double longToDouble(long value, boolean doubleToLongBits) {
    if (doubleToLongBits) {
        return Double.longBitsToDouble(value);
    } else {//from   ww  w .j  ava  2s . c  o  m
        return (double) value;
    }
}