Example usage for java.lang Byte MAX_VALUE

List of usage examples for java.lang Byte MAX_VALUE

Introduction

In this page you can find the example usage for java.lang Byte MAX_VALUE.

Prototype

byte MAX_VALUE

To view the source code for java.lang Byte MAX_VALUE.

Click Source Link

Document

A constant holding the maximum value a byte can have, 27-1.

Usage

From source file:edu.umass.cs.utils.Util.java

private static void testToBytesAndBack() throws UnknownHostException, UnsupportedEncodingException {
    InetSocketAddress isa = new InetSocketAddress("128.119.235.43", 23451);
    assert (Util.encodedStringToInetSocketAddress(Util.sockAddrToEncodedString(isa)).equals(isa));
    int n = 10000;
    for (int i = 0; i < n; i++) {
        long t = (long) (Math.random() * Long.MAX_VALUE);
        byte[] buf = (Util.longToBytes(t));
        assert (t == Util.bytesToLong(buf));
    }//from w  ww  .java  2 s  .c  om
    for (int i = 0; i < n; i++) {
        long value = (long) (Math.random() * Long.MAX_VALUE);
        assert (value == Util.encodedStringToLong(Util.longToEncodedString(value)));
    }
    for (int i = 0; i < n; i++) {
        byte[] address = new byte[4];
        for (int j = 0; j < 4; j++)
            address[j] = (byte) (Math.random() * Byte.MAX_VALUE);
        InetSocketAddress sockAddr = new InetSocketAddress(InetAddress.getByAddress(address),
                (int) (Math.random() * Short.MAX_VALUE));
        assert (Util.encodedStringToInetSocketAddress(Util.sockAddrToEncodedString(sockAddr)).equals(sockAddr));
    }
}

From source file:org.apache.pig.data.BinInterSedes.java

@Override
@SuppressWarnings("unchecked")
public void writeDatum(DataOutput out, Object val, byte type) throws IOException {
    switch (type) {
    case DataType.TUPLE:
        writeTuple(out, (Tuple) val);
        break;/*from   w  w  w  . j  a v a2 s. com*/

    case DataType.BAG:
        writeBag(out, (DataBag) val);
        break;

    case DataType.MAP: {
        writeMap(out, (Map<String, Object>) val);
        break;
    }

    case DataType.INTERNALMAP: {
        out.writeByte(INTERNALMAP);
        Map<Object, Object> m = (Map<Object, Object>) val;
        out.writeInt(m.size());
        Iterator<Map.Entry<Object, Object>> i = m.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<Object, Object> entry = i.next();
            writeDatum(out, entry.getKey());
            writeDatum(out, entry.getValue());
        }
        break;
    }

    case DataType.INTEGER:
        int i = (Integer) val;
        if (i == 0) {
            out.writeByte(INTEGER_0);
        } else if (i == 1) {
            out.writeByte(INTEGER_1);
        } else if (Byte.MIN_VALUE <= i && i <= Byte.MAX_VALUE) {
            out.writeByte(INTEGER_INBYTE);
            out.writeByte(i);
        } else if (Short.MIN_VALUE <= i && i <= Short.MAX_VALUE) {
            out.writeByte(INTEGER_INSHORT);
            out.writeShort(i);
        } else {
            out.writeByte(INTEGER);
            out.writeInt(i);
        }
        break;

    case DataType.LONG:
        long lng = (Long) val;
        if (lng == 0) {
            out.writeByte(LONG_0);
        } else if (lng == 1) {
            out.writeByte(LONG_1);
        } else if (Byte.MIN_VALUE <= lng && lng <= Byte.MAX_VALUE) {
            out.writeByte(LONG_INBYTE);
            out.writeByte((int) lng);
        } else if (Short.MIN_VALUE <= lng && lng <= Short.MAX_VALUE) {
            out.writeByte(LONG_INSHORT);
            out.writeShort((int) lng);
        } else if (Integer.MIN_VALUE <= lng && lng <= Integer.MAX_VALUE) {
            out.writeByte(LONG_ININT);
            out.writeInt((int) lng);
        } else {
            out.writeByte(LONG);
            out.writeLong(lng);
        }
        break;

    case DataType.DATETIME:
        out.writeByte(DATETIME);
        out.writeLong(((DateTime) val).getMillis());
        out.writeShort(((DateTime) val).getZone().getOffset((DateTime) val) / ONE_MINUTE);
        break;

    case DataType.FLOAT:
        out.writeByte(FLOAT);
        out.writeFloat((Float) val);
        break;

    case DataType.BIGINTEGER:
        out.writeByte(BIGINTEGER);
        writeBigInteger(out, (BigInteger) val);
        break;

    case DataType.BIGDECIMAL:
        out.writeByte(BIGDECIMAL);
        writeBigDecimal(out, (BigDecimal) val);
        break;

    case DataType.DOUBLE:
        out.writeByte(DOUBLE);
        out.writeDouble((Double) val);
        break;

    case DataType.BOOLEAN:
        if ((Boolean) val)
            out.writeByte(BOOLEAN_TRUE);
        else
            out.writeByte(BOOLEAN_FALSE);
        break;

    case DataType.BYTE:
        out.writeByte(BYTE);
        out.writeByte((Byte) val);
        break;

    case DataType.BYTEARRAY: {
        DataByteArray bytes = (DataByteArray) val;
        SedesHelper.writeBytes(out, bytes.mData);
        break;

    }

    case DataType.CHARARRAY: {
        SedesHelper.writeChararray(out, (String) val);
        break;
    }
    case DataType.GENERIC_WRITABLECOMPARABLE:
        out.writeByte(GENERIC_WRITABLECOMPARABLE);
        // store the class name, so we know the class to create on read
        writeDatum(out, val.getClass().getName());
        Writable writable = (Writable) val;
        writable.write(out);
        break;

    case DataType.NULL:
        out.writeByte(NULL);
        break;

    default:
        throw new RuntimeException("Unexpected data type " + val.getClass().getName() + " found in stream. "
                + "Note only standard Pig type is supported when you output from UDF/LoadFunc");
    }
}

From source file:org.apache.rya.indexing.smarturi.duplication.DuplicateDataDetectorIT.java

@Test
public void testByteProperty() throws SmartUriException {
    System.out.println("Byte Property Test");
    final ImmutableList.Builder<TestInput> builder = ImmutableList.builder();
    // Tolerance 0.0
    Tolerance tolerance = new Tolerance(0.0, ToleranceType.DIFFERENCE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, false));
    builder.add(new TestInput((byte) 0x01, tolerance, false));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, false));
    builder.add(new TestInput((byte) 0x04, tolerance, false));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));
    // Tolerance 1.0
    tolerance = new Tolerance(1.0, ToleranceType.DIFFERENCE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, false));
    builder.add(new TestInput((byte) 0x01, tolerance, true));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, true));
    builder.add(new TestInput((byte) 0x04, tolerance, false));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));
    // Tolerance 2.0
    tolerance = new Tolerance(2.0, ToleranceType.DIFFERENCE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, true));
    builder.add(new TestInput((byte) 0x01, tolerance, true));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, true));
    builder.add(new TestInput((byte) 0x04, tolerance, true));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));

    // Tolerance 0.0%
    tolerance = new Tolerance(0.00, ToleranceType.PERCENTAGE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, false));
    builder.add(new TestInput((byte) 0x01, tolerance, false));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, false));
    builder.add(new TestInput((byte) 0x04, tolerance, false));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));
    // Tolerance 50.0%
    tolerance = new Tolerance(0.50, ToleranceType.PERCENTAGE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, false));
    builder.add(new TestInput((byte) 0x01, tolerance, true));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, true));
    builder.add(new TestInput((byte) 0x04, tolerance, false));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));
    // Tolerance 100.0%
    tolerance = new Tolerance(1.00, ToleranceType.PERCENTAGE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, true));
    builder.add(new TestInput((byte) 0xff, tolerance, true));
    builder.add(new TestInput((byte) 0x00, tolerance, true));
    builder.add(new TestInput((byte) 0x01, tolerance, true));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, true));
    builder.add(new TestInput((byte) 0x04, tolerance, true));
    builder.add(new TestInput((byte) 0x05, tolerance, true));
    builder.add(new TestInput((byte) 0x10, tolerance, true));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, true));

    final ImmutableList<TestInput> testInputs = builder.build();

    testProperty(testInputs, PERSON_TYPE_URI, HAS_NUMBER_OF_CHILDREN);
}

From source file:org.apache.rya.indexing.smarturi.duplication.DuplicateDataDetectorTest.java

@Test
public void testByteProperty() throws SmartUriException {
    System.out.println("Byte Property Test");
    final ImmutableList.Builder<TestInput> builder = ImmutableList.<TestInput>builder();
    // Tolerance 0.0
    Tolerance tolerance = new Tolerance(0.0, ToleranceType.DIFFERENCE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, false));
    builder.add(new TestInput((byte) 0x01, tolerance, false));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, false));
    builder.add(new TestInput((byte) 0x04, tolerance, false));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));
    // Tolerance 1.0
    tolerance = new Tolerance(1.0, ToleranceType.DIFFERENCE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, false));
    builder.add(new TestInput((byte) 0x01, tolerance, true));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, true));
    builder.add(new TestInput((byte) 0x04, tolerance, false));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));
    // Tolerance 2.0
    tolerance = new Tolerance(2.0, ToleranceType.DIFFERENCE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, true));
    builder.add(new TestInput((byte) 0x01, tolerance, true));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, true));
    builder.add(new TestInput((byte) 0x04, tolerance, true));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));

    // Tolerance 0.0%
    tolerance = new Tolerance(0.00, ToleranceType.PERCENTAGE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, false));
    builder.add(new TestInput((byte) 0x01, tolerance, false));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, false));
    builder.add(new TestInput((byte) 0x04, tolerance, false));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));
    // Tolerance 50.0%
    tolerance = new Tolerance(0.50, ToleranceType.PERCENTAGE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, false));
    builder.add(new TestInput((byte) 0xff, tolerance, false));
    builder.add(new TestInput((byte) 0x00, tolerance, false));
    builder.add(new TestInput((byte) 0x01, tolerance, true));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, true));
    builder.add(new TestInput((byte) 0x04, tolerance, false));
    builder.add(new TestInput((byte) 0x05, tolerance, false));
    builder.add(new TestInput((byte) 0x10, tolerance, false));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, false));
    // Tolerance 100.0%
    tolerance = new Tolerance(1.00, ToleranceType.PERCENTAGE);
    builder.add(new TestInput(Byte.MIN_VALUE, tolerance, true));
    builder.add(new TestInput((byte) 0xff, tolerance, true));
    builder.add(new TestInput((byte) 0x00, tolerance, true));
    builder.add(new TestInput((byte) 0x01, tolerance, true));
    builder.add(new TestInput((byte) 0x02, tolerance, true)); // Equals value
    builder.add(new TestInput((byte) 0x03, tolerance, true));
    builder.add(new TestInput((byte) 0x04, tolerance, true));
    builder.add(new TestInput((byte) 0x05, tolerance, true));
    builder.add(new TestInput((byte) 0x10, tolerance, true));
    builder.add(new TestInput(Byte.MAX_VALUE, tolerance, true));

    final ImmutableList<TestInput> testInputs = builder.build();

    testProperty(testInputs, PERSON_TYPE_URI, HAS_NUMBER_OF_CHILDREN);
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

protected boolean isInRange(Number value, String stringValue, Class toType) {
    Number bigValue = null;/*  w  w  w  .  ja  va  2s . co m*/
    Number lowerBound = null;
    Number upperBound = null;

    try {
        if (double.class == toType || Double.class == toType) {
            bigValue = new BigDecimal(stringValue);
            // Double.MIN_VALUE is the smallest positive non-zero number
            lowerBound = BigDecimal.valueOf(Double.MAX_VALUE).negate();
            upperBound = BigDecimal.valueOf(Double.MAX_VALUE);
        } else if (float.class == toType || Float.class == toType) {
            bigValue = new BigDecimal(stringValue);
            // Float.MIN_VALUE is the smallest positive non-zero number
            lowerBound = BigDecimal.valueOf(Float.MAX_VALUE).negate();
            upperBound = BigDecimal.valueOf(Float.MAX_VALUE);
        } else if (byte.class == toType || Byte.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Byte.MIN_VALUE);
            upperBound = BigInteger.valueOf(Byte.MAX_VALUE);
        } else if (char.class == toType || Character.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Character.MIN_VALUE);
            upperBound = BigInteger.valueOf(Character.MAX_VALUE);
        } else if (short.class == toType || Short.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Short.MIN_VALUE);
            upperBound = BigInteger.valueOf(Short.MAX_VALUE);
        } else if (int.class == toType || Integer.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Integer.MIN_VALUE);
            upperBound = BigInteger.valueOf(Integer.MAX_VALUE);
        } else if (long.class == toType || Long.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Long.MIN_VALUE);
            upperBound = BigInteger.valueOf(Long.MAX_VALUE);
        }
    } catch (NumberFormatException e) {
        //shoult it fail here? BigInteger doesnt seem to be so nice parsing numbers as NumberFormat
        return true;
    }

    return ((Comparable) bigValue).compareTo(lowerBound) >= 0
            && ((Comparable) bigValue).compareTo(upperBound) <= 0;
}

From source file:org.apache.hive.hcatalog.pig.HCatBaseStorer.java

/**
 * Convert from Pig value object to Hive value object
 * This method assumes that {@link #validateSchema(org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema, org.apache.hive.hcatalog.data.schema.HCatFieldSchema, org.apache.pig.impl.logicalLayer.schema.Schema, org.apache.hive.hcatalog.data.schema.HCatSchema, int)}
 * which checks the types in Pig schema are compatible with target Hive table, has been called.
 *//*from   w  w  w. j  a v  a  2 s .  c o  m*/
private Object getJavaObj(Object pigObj, HCatFieldSchema hcatFS) throws HCatException, BackendException {
    try {
        if (pigObj == null)
            return null;
        // The real work-horse. Spend time and energy in this method if there is
        // need to keep HCatStorer lean and go fast.
        Type type = hcatFS.getType();
        switch (type) {
        case BINARY:
            return ((DataByteArray) pigObj).get();

        case STRUCT:
            HCatSchema structSubSchema = hcatFS.getStructSubSchema();
            // Unwrap the tuple.
            List<Object> all = ((Tuple) pigObj).getAll();
            ArrayList<Object> converted = new ArrayList<Object>(all.size());
            for (int i = 0; i < all.size(); i++) {
                converted.add(getJavaObj(all.get(i), structSubSchema.get(i)));
            }
            return converted;

        case ARRAY:
            // Unwrap the bag.
            DataBag pigBag = (DataBag) pigObj;
            HCatFieldSchema tupFS = hcatFS.getArrayElementSchema().get(0);
            boolean needTuple = tupFS.getType() == Type.STRUCT;
            List<Object> bagContents = new ArrayList<Object>((int) pigBag.size());
            Iterator<Tuple> bagItr = pigBag.iterator();

            while (bagItr.hasNext()) {
                // If there is only one element in tuple contained in bag, we throw away the tuple.
                bagContents.add(getJavaObj(needTuple ? bagItr.next() : bagItr.next().get(0), tupFS));

            }
            return bagContents;
        case MAP:
            Map<?, ?> pigMap = (Map<?, ?>) pigObj;
            Map<Object, Object> typeMap = new HashMap<Object, Object>();
            for (Entry<?, ?> entry : pigMap.entrySet()) {
                // the value has a schema and not a FieldSchema
                typeMap.put(
                        // Schema validation enforces that the Key is a String
                        (String) entry.getKey(),
                        getJavaObj(entry.getValue(), hcatFS.getMapValueSchema().get(0)));
            }
            return typeMap;
        case STRING:
        case INT:
        case BIGINT:
        case FLOAT:
        case DOUBLE:
            return pigObj;
        case SMALLINT:
            if ((Integer) pigObj < Short.MIN_VALUE || (Integer) pigObj > Short.MAX_VALUE) {
                handleOutOfRangeValue(pigObj, hcatFS);
                return null;
            }
            return ((Integer) pigObj).shortValue();
        case TINYINT:
            if ((Integer) pigObj < Byte.MIN_VALUE || (Integer) pigObj > Byte.MAX_VALUE) {
                handleOutOfRangeValue(pigObj, hcatFS);
                return null;
            }
            return ((Integer) pigObj).byteValue();
        case BOOLEAN:
            if (pigObj instanceof String) {
                if (((String) pigObj).trim().compareTo("0") == 0) {
                    return Boolean.FALSE;
                }
                if (((String) pigObj).trim().compareTo("1") == 0) {
                    return Boolean.TRUE;
                }
                throw new BackendException("Unexpected type " + type + " for value " + pigObj + " of class "
                        + pigObj.getClass().getName(), PigHCatUtil.PIG_EXCEPTION_CODE);
            }
            return Boolean.parseBoolean(pigObj.toString());
        case DECIMAL:
            BigDecimal bd = (BigDecimal) pigObj;
            DecimalTypeInfo dti = (DecimalTypeInfo) hcatFS.getTypeInfo();
            if (bd.precision() > dti.precision() || bd.scale() > dti.scale()) {
                handleOutOfRangeValue(pigObj, hcatFS);
                return null;
            }
            return HiveDecimal.create(bd);
        case CHAR:
            String charVal = (String) pigObj;
            CharTypeInfo cti = (CharTypeInfo) hcatFS.getTypeInfo();
            if (charVal.length() > cti.getLength()) {
                handleOutOfRangeValue(pigObj, hcatFS);
                return null;
            }
            return new HiveChar(charVal, cti.getLength());
        case VARCHAR:
            String varcharVal = (String) pigObj;
            VarcharTypeInfo vti = (VarcharTypeInfo) hcatFS.getTypeInfo();
            if (varcharVal.length() > vti.getLength()) {
                handleOutOfRangeValue(pigObj, hcatFS);
                return null;
            }
            return new HiveVarchar(varcharVal, vti.getLength());
        case TIMESTAMP:
            DateTime dt = (DateTime) pigObj;
            return new Timestamp(dt.getMillis());//getMillis() returns UTC time regardless of TZ
        case DATE:
            /**
             * We ignore any TZ setting on Pig value since java.sql.Date doesn't have it (in any
             * meaningful way).  So the assumption is that if Pig value has 0 time component (midnight)
             * we assume it reasonably 'fits' into a Hive DATE.  If time part is not 0, it's considered
             * out of range for target type.
             */
            DateTime dateTime = ((DateTime) pigObj);
            if (dateTime.getMillisOfDay() != 0) {
                handleOutOfRangeValue(pigObj, hcatFS,
                        "Time component must be 0 (midnight) in local timezone; Local TZ val='" + pigObj + "'");
                return null;
            }
            /*java.sql.Date is a poorly defined API.  Some (all?) SerDes call toString() on it
            [e.g. LazySimpleSerDe, uses LazyUtils.writePrimitiveUTF8()],  which automatically adjusts
              for local timezone.  Date.valueOf() also uses local timezone (as does Date(int,int,int).
              Also see PigHCatUtil#extractPigObject() for corresponding read op.  This way a DATETIME from Pig,
              when stored into Hive and read back comes back with the same value.*/
            return new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth());
        default:
            throw new BackendException("Unexpected HCat type " + type + " for value " + pigObj + " of class "
                    + pigObj.getClass().getName(), PigHCatUtil.PIG_EXCEPTION_CODE);
        }
    } catch (BackendException e) {
        // provide the path to the field in the error message
        throw new BackendException((hcatFS.getName() == null ? " " : hcatFS.getName() + ".") + e.getMessage(),
                e);
    }
}

From source file:org.seedstack.seed.core.internal.application.ConfigurationMembersInjectorTest.java

public org.apache.commons.configuration.Configuration mockConfiguration(Field field, boolean isInconfig) {
    if (field == null) {
        return null;
    }/* w w w  .  j av  a 2s . c om*/
    org.apache.commons.configuration.Configuration configuration = mock(
            org.apache.commons.configuration.Configuration.class);
    when(configuration.containsKey(field.getName())).thenReturn(isInconfig);
    if (isInconfig) {
        Class<?> type = field.getType();
        String configParamName = field.getAnnotation(Configuration.class).value();
        if (type.isArray()) {
            type = type.getComponentType();

            if (type == Integer.TYPE || type == Integer.class) {
                when(configuration.getStringArray(configParamName))
                        .thenReturn(new String[] { String.valueOf(Integer.MAX_VALUE) });
            } else if (type == Boolean.TYPE || type == Boolean.class) {
                when(configuration.getStringArray(configParamName)).thenReturn(new String[] { "true" });
            } else if (type == Short.TYPE || type == Short.class) {
                when(configuration.getStringArray(configParamName))
                        .thenReturn(new String[] { String.valueOf(Short.MAX_VALUE) });
            } else if (type == Byte.TYPE || type == Byte.class) {
                when(configuration.getStringArray(configParamName))
                        .thenReturn(new String[] { String.valueOf(Byte.MAX_VALUE) });
            } else if (type == Long.TYPE || type == Long.class) {
                when(configuration.getStringArray(configParamName))
                        .thenReturn(new String[] { String.valueOf(Long.MAX_VALUE) });
            } else if (type == Float.TYPE || type == Float.class) {
                when(configuration.getStringArray(configParamName))
                        .thenReturn(new String[] { String.valueOf(Float.MAX_VALUE) });
            } else if (type == Double.TYPE || type == Double.class) {
                when(configuration.getStringArray(configParamName))
                        .thenReturn(new String[] { String.valueOf(Double.MAX_VALUE) });
            } else if (type == Character.TYPE || type == Character.class) {
                when(configuration.getStringArray(configParamName)).thenReturn(new String[] { "t" });
            } else if (type == String.class) {
                when(configuration.getStringArray(configParamName)).thenReturn(new String[] { "test" });
            } else
                throw new IllegalArgumentException("Type " + type + " cannot be mocked");
        } else {
            if (type == Integer.TYPE || type == Integer.class) {
                when(configuration.getString(configParamName)).thenReturn(String.valueOf(Integer.MAX_VALUE));
            } else if (type == Boolean.TYPE || type == Boolean.class) {
                when(configuration.getString(configParamName)).thenReturn("true");
            } else if (type == Short.TYPE || type == Short.class) {
                when(configuration.getString(configParamName)).thenReturn(String.valueOf(Short.MAX_VALUE));
            } else if (type == Byte.TYPE || type == Byte.class) {
                when(configuration.getString(configParamName)).thenReturn(String.valueOf(Byte.MAX_VALUE));
            } else if (type == Long.TYPE || type == Long.class) {
                when(configuration.getString(configParamName)).thenReturn(String.valueOf(Long.MAX_VALUE));
            } else if (type == Float.TYPE || type == Float.class) {
                when(configuration.getString(configParamName)).thenReturn(String.valueOf(Float.MAX_VALUE));
            } else if (type == Double.TYPE || type == Double.class) {
                when(configuration.getString(configParamName)).thenReturn(String.valueOf(Double.MAX_VALUE));
            } else if (type == Character.TYPE || type == Character.class) {
                when(configuration.getString(configParamName)).thenReturn("t");
            } else if (type == String.class) {
                when(configuration.getString(configParamName)).thenReturn("test");
            } else
                throw new IllegalArgumentException("Type " + type + " cannot be mocked");
        }
    }
    return configuration;
}

From source file:org.vertx.java.http.eventbusbridge.integration.MessageSendWithReplyTest.java

@Test
public void testSendingByteXmlWithResponseXml() throws IOException {
    final EventBusMessageType messageType = EventBusMessageType.Byte;
    final Byte sentByte = Byte.MAX_VALUE;
    int port = findFreePort();
    String responseUrl = createHttpServerUrl(port);
    Map<String, String> expectations = createExpectations("someaddress",
            Base64.encodeAsString(sentByte.toString()), messageType, responseUrl, MediaType.APPLICATION_XML);
    String responseBody = TemplateHelper.generateOutputUsingTemplate(SEND_RESPONSE_TEMPLATE_XML, expectations);
    createHttpServer(port, MediaType.APPLICATION_XML, responseBody);
    Handler<Message> messageConsumerHandler = new MessageSendWithReplyHandler(sentByte, expectations);
    vertx.eventBus().registerHandler(expectations.get("address"), messageConsumerHandler);
    String requestBody = TemplateHelper.generateOutputUsingTemplate(SEND_REQUEST_TEMPLATE_XML, expectations);
    HttpRequestHelper.sendHttpPostRequest(url, requestBody, (VertxInternal) vertx,
            Status.ACCEPTED.getStatusCode(), MediaType.APPLICATION_XML);
}

From source file:org.sakaiproject.content.impl.DbContentService.java

/**
 * Runs tests of the getResourcesOfType() method. Steps are:<br/>
 * 1) Add 26 site-level resource collections ("/group/site_A/" through "/group/site_Z/")
 * and 676 resources of type "org.sakaiproject.content.mock.resource-type".
 * 2) Invoke the getResourcesOfType() method with page-size 64 and compare
 * the resource-id's with the resource-id's that would be returned if the 
 * method works correctly.// www  . ja  v  a  2  s .c om
 * 3) Remove the mock resources and collections created in step 1.
 * A list of the resource-id's is created in step 1 and used in steps 2 and 3.
 * Verbose logging in step 2 is intended to help with troubleshooting.  It would 
 * help to reduce the amount of logging and target it better.  Verbose logging also
 * occurs in step 3 because the no realms are created for the collections in step 1,
 * resulting in informational messages when an attempt is made to remove the realms.  
 */
protected void testResourceByTypePaging() {
    // test 
    List<String> collectionIdList = new ArrayList<String>();
    List<String> resourceIdList = new ArrayList<String>();
    String collectionId = "/group/";
    String siteid = "site_";
    String fileid = "image_";
    String extension = "jpg";
    String resourceType = "org.sakaiproject.content.mock.resource-type";
    String contentType = "image/jpeg";
    byte[] content = new byte[(Byte.MAX_VALUE - Byte.MIN_VALUE) * 4];
    int index = 0;
    for (int i = 0; i < 4 && index < content.length; i++) {
        for (byte b = Byte.MIN_VALUE; b <= Byte.MAX_VALUE && index < content.length; b++) {
            content[index] = b;
            index++;
        }
    }

    try {
        //enableSecurityAdvisor();
        Session s = sessionManager.getCurrentSession();
        s.setUserId(UserDirectoryService.ADMIN_ID);

        for (char ch = 'A'; ch <= 'Z'; ch++) {
            try {
                String name = siteid + ch;
                ContentCollectionEdit collection = this.addCollection(collectionId, name);
                ResourcePropertiesEdit props = collection.getPropertiesEdit();
                props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
                this.commitCollection(collection);
                collectionIdList.add(collection.getId());

                for (char ch1 = 'a'; ch1 <= 'z'; ch1++) {
                    try {
                        String resourceName = fileid + ch1;
                        ContentResourceEdit resource = this.addResource(collection.getId(), resourceName,
                                extension, MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
                        ResourcePropertiesEdit properties = resource.getPropertiesEdit();
                        properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, resourceName);
                        resource.setContent(content);
                        resource.setContentType(contentType);
                        resource.setResourceType(resourceType);
                        this.commitResource(resource);
                        resourceIdList.add(resource.getId());
                    } catch (Exception e) {
                        M_log.error(
                                "TEMPORARY LOG MESSAGE WITH STACK TRACE: Failed to create all resources; ch1 = "
                                        + ch1,
                                e);
                    }
                }
            } catch (Exception e) {
                M_log.error(
                        "TEMPORARY LOG MESSAGE WITH STACK TRACE: Failed to create all collections; ch = " + ch,
                        e);
            }
        }

        int successCount = 0;
        int failCount = 0;
        int pageSize = 64;
        for (int p = 0; p * pageSize < resourceIdList.size(); p++) {
            Collection<ContentResource> page = this.getResourcesOfType(resourceType, pageSize, p);
            int r = 0;
            for (ContentResource cr : page) {
                if (p * pageSize + r >= resourceIdList.size()) {
                    M_log.info("TEMPORARY LOG MESSAGE: test failed ====> p = " + p + " r = " + r
                            + " index out of range: p * pageSize + r = " + (p * pageSize + r)
                            + " resourceIdList.size() = " + resourceIdList.size());
                    failCount++;
                } else if (cr.getId().equals(resourceIdList.get(p * pageSize + r))) {
                    successCount++;
                } else {
                    M_log.info("TEMPORARY LOG MESSAGE: test failed ====> p = " + p + " r = " + r
                            + " resource-id doesn't match: cr.getId() = " + cr.getId()
                            + " resourceIdList.get(p * pageSize + r) = resourceIdList.get(" + (p * pageSize + r)
                            + ") = " + resourceIdList.get(p * pageSize + r));
                    failCount++;
                }
                r++;
            }
            M_log.info("TEMPORARY LOG MESSAGE: Testing getResourcesOfType() completed page " + p + " of "
                    + (resourceIdList.size() / pageSize));
        }
        M_log.info("TEMPORARY LOG MESSAGE: Testing getResourcesOfType() SUCCEEDED: " + successCount
                + " FAILED: " + failCount);

        for (String resourceId : resourceIdList) {
            ContentResourceEdit edit = this.editResource(resourceId);
            this.removeResource(edit);
        }

        M_log.info(
                "TEMPORARY LOG MESSAGE: Will delete 26 collections and 676 resources.  Some log messages will appear.  This block of code will be removed in trunk within a few days and the log messages will disappear.");
        for (String collId : collectionIdList) {
            ContentCollectionEdit edit = this.editCollection(collId);
            this.removeCollection(edit);
        }
    } catch (Exception e) {
        M_log.debug("TEMPORARY LOG MESSAGE WITH STACK TRACE: TEST FAILED ", e);
    }
}

From source file:org.apache.carbondata.core.indexstore.blockletindex.BlockletDataMap.java

/**
 * Fill the measures max values with maximum , this is needed for backward version compatability
 * as older versions don't store max values for measures
 *///from w  w w  .j  a  va 2  s  .com
private byte[][] updateMaxValues(byte[][] maxValues, int[] minMaxLen) {
    byte[][] updatedValues = maxValues;
    if (maxValues.length < minMaxLen.length) {
        updatedValues = new byte[minMaxLen.length][];
        System.arraycopy(maxValues, 0, updatedValues, 0, maxValues.length);
        List<CarbonMeasure> measures = segmentProperties.getMeasures();
        ByteBuffer buffer = ByteBuffer.allocate(8);
        for (int i = 0; i < measures.size(); i++) {
            buffer.rewind();
            DataType dataType = measures.get(i).getDataType();
            if (dataType == DataTypes.BYTE) {
                buffer.putLong(Byte.MAX_VALUE);
                updatedValues[maxValues.length + i] = buffer.array().clone();
            } else if (dataType == DataTypes.SHORT) {
                buffer.putLong(Short.MAX_VALUE);
                updatedValues[maxValues.length + i] = buffer.array().clone();
            } else if (dataType == DataTypes.INT) {
                buffer.putLong(Integer.MAX_VALUE);
                updatedValues[maxValues.length + i] = buffer.array().clone();
            } else if (dataType == DataTypes.LONG) {
                buffer.putLong(Long.MAX_VALUE);
                updatedValues[maxValues.length + i] = buffer.array().clone();
            } else if (DataTypes.isDecimal(dataType)) {
                updatedValues[maxValues.length + i] = DataTypeUtil
                        .bigDecimalToByte(BigDecimal.valueOf(Long.MAX_VALUE));
            } else {
                buffer.putDouble(Double.MAX_VALUE);
                updatedValues[maxValues.length + i] = buffer.array().clone();
            }
        }
    }
    return updatedValues;
}