Example usage for java.lang Long TYPE

List of usage examples for java.lang Long TYPE

Introduction

In this page you can find the example usage for java.lang Long TYPE.

Prototype

Class TYPE

To view the source code for java.lang Long TYPE.

Click Source Link

Document

The Class instance representing the primitive type long .

Usage

From source file:org.apache.syncope.core.provisioning.java.ConnectorFacadeProxy.java

private Object getPropertyValue(final String propType, final List<?> values) {
    Object value = null;/*from   w w w . j  a v a2  s .c  o  m*/

    try {
        Class<?> propertySchemaClass = ClassUtils.forName(propType, ClassUtils.getDefaultClassLoader());

        if (GuardedString.class.equals(propertySchemaClass)) {
            value = new GuardedString(values.get(0).toString().toCharArray());
        } else if (GuardedByteArray.class.equals(propertySchemaClass)) {
            value = new GuardedByteArray((byte[]) values.get(0));
        } else if (Character.class.equals(propertySchemaClass) || Character.TYPE.equals(propertySchemaClass)) {
            value = values.get(0) == null || values.get(0).toString().isEmpty() ? null
                    : values.get(0).toString().charAt(0);
        } else if (Integer.class.equals(propertySchemaClass) || Integer.TYPE.equals(propertySchemaClass)) {
            value = Integer.parseInt(values.get(0).toString());
        } else if (Long.class.equals(propertySchemaClass) || Long.TYPE.equals(propertySchemaClass)) {
            value = Long.parseLong(values.get(0).toString());
        } else if (Float.class.equals(propertySchemaClass) || Float.TYPE.equals(propertySchemaClass)) {
            value = Float.parseFloat(values.get(0).toString());
        } else if (Double.class.equals(propertySchemaClass) || Double.TYPE.equals(propertySchemaClass)) {
            value = Double.parseDouble(values.get(0).toString());
        } else if (Boolean.class.equals(propertySchemaClass) || Boolean.TYPE.equals(propertySchemaClass)) {
            value = Boolean.parseBoolean(values.get(0).toString());
        } else if (URI.class.equals(propertySchemaClass)) {
            value = URI.create(values.get(0).toString());
        } else if (File.class.equals(propertySchemaClass)) {
            value = new File(values.get(0).toString());
        } else if (String[].class.equals(propertySchemaClass)) {
            value = values.toArray(new String[] {});
        } else {
            value = values.get(0) == null ? null : values.get(0).toString();
        }
    } catch (Exception e) {
        LOG.error("Invalid ConnConfProperty specified: {} {}", propType, values, e);
    }

    return value;
}

From source file:Main.java

/**
 * <p>Inserts the specified element at the specified position in the array.
 * Shifts the element currently at that position (if any) and any subsequent
 * elements to the right (adds one to their indices).</p>
 *
 * <p>This method returns a new array with the same elements of the input
 * array plus the given element on the specified position. The component
 * type of the returned array is always the same as that of the input
 * array.</p>/*w  w  w.ja  v  a2s  .c om*/
 *
 * <p>If the input array is {@code null}, a new one element array is returned
 *  whose component type is the same as the element.</p>
 *
 * <pre>
 * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]
 * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]
 * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]
 * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]
 * </pre>
 *
 * @param array  the array to add the element to, may be {@code null}
 * @param index  the position of the new object
 * @param element  the object to add
 * @return A new array containing the existing elements and the new element
 * @throws IndexOutOfBoundsException if the index is out of range
 * (index < 0 || index > array.length).
 */
public static long[] add(long[] array, int index, long element) {
    return (long[]) add(array, index, Long.valueOf(element), Long.TYPE);
}

From source file:Main.java

/**
 * <p>Inserts the specified element at the specified position in the array.
 * Shifts the element currently at that position (if any) and any subsequent
 * elements to the right (adds one to their indices).</p>
 *
 * <p>This method returns a new array with the same elements of the input
 * array plus the given element on the specified position. The component
 * type of the returned array is always the same as that of the input
 * array.</p>//from   w w  w .  jav a  2s.  co m
 *
 * <p>If the input array is {@code null}, a new one element array is returned
 *  whose component type is the same as the element.</p>
 *
 * <pre>
 * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]
 * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]
 * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]
 * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]
 * </pre>
 *
 * @param array  the array to add the element to, may be {@code null}
 * @param index  the position of the new object
 * @param element  the object to add
 * @return A new array containing the existing elements and the new element
 * @throws IndexOutOfBoundsException if the index is out of range
 * (index < 0 || index > array.length).
 */
public static long[] add(final long[] array, final int index, final long element) {
    return (long[]) add(array, index, Long.valueOf(element), Long.TYPE);
}

From source file:org.apache.syncope.core.provisioning.java.MappingManagerImpl.java

@Transactional(readOnly = true)
@Override/*  w  w w. ja  v  a 2 s. c  om*/
public List<PlainAttrValue> getIntValues(final Provision provision, final Item mapItem,
        final IntAttrName intAttrName, final Any<?> any) {

    LOG.debug("Get internal values for {} as '{}' on {}", any, mapItem.getIntAttrName(),
            provision.getResource());

    Any<?> reference = null;
    Membership<?> membership = null;
    if (intAttrName.getEnclosingGroup() == null && intAttrName.getRelatedAnyObject() == null) {
        reference = any;
    }
    if (any instanceof GroupableRelatable) {
        GroupableRelatable<?, ?, ?, ?, ?> groupableRelatable = (GroupableRelatable<?, ?, ?, ?, ?>) any;

        if (intAttrName.getEnclosingGroup() != null) {
            Group group = groupDAO.findByName(intAttrName.getEnclosingGroup());
            if (group == null || !groupableRelatable.getMembership(group.getKey()).isPresent()) {
                LOG.warn("No membership for {} in {}, ignoring", intAttrName.getEnclosingGroup(),
                        groupableRelatable);
            } else {
                reference = group;
            }
        } else if (intAttrName.getRelatedAnyObject() != null) {
            AnyObject anyObject = anyObjectDAO.findByName(intAttrName.getRelatedAnyObject());
            if (anyObject == null || groupableRelatable.getRelationships(anyObject.getKey()).isEmpty()) {
                LOG.warn("No relationship for {} in {}, ignoring", intAttrName.getRelatedAnyObject(),
                        groupableRelatable);
            } else {
                reference = anyObject;
            }
        } else if (intAttrName.getMembershipOfGroup() != null) {
            Group group = groupDAO.findByName(intAttrName.getMembershipOfGroup());
            membership = groupableRelatable.getMembership(group.getKey()).orElse(null);
        }
    }
    if (reference == null) {
        LOG.warn("Could not determine the reference instance for {}", mapItem.getIntAttrName());
        return Collections.emptyList();
    }

    List<PlainAttrValue> values = new ArrayList<>();
    boolean transform = true;

    AnyUtils anyUtils = anyUtilsFactory.getInstance(reference);
    if (intAttrName.getField() != null) {
        PlainAttrValue attrValue = anyUtils.newPlainAttrValue();

        switch (intAttrName.getField()) {
        case "key":
            attrValue.setStringValue(reference.getKey());
            values.add(attrValue);
            break;

        case "realm":
            attrValue.setStringValue(reference.getRealm().getFullPath());
            values.add(attrValue);
            break;

        case "password":
            // ignore
            break;

        case "userOwner":
        case "groupOwner":
            Mapping uMapping = provision.getAnyType().equals(anyTypeDAO.findUser()) ? provision.getMapping()
                    : null;
            Mapping gMapping = provision.getAnyType().equals(anyTypeDAO.findGroup()) ? provision.getMapping()
                    : null;

            if (reference instanceof Group) {
                Group group = (Group) reference;
                String groupOwnerValue = null;
                if (group.getUserOwner() != null && uMapping != null) {
                    groupOwnerValue = getGroupOwnerValue(provision, group.getUserOwner());
                }
                if (group.getGroupOwner() != null && gMapping != null) {
                    groupOwnerValue = getGroupOwnerValue(provision, group.getGroupOwner());
                }

                if (StringUtils.isNotBlank(groupOwnerValue)) {
                    attrValue.setStringValue(groupOwnerValue);
                    values.add(attrValue);
                }
            }
            break;

        case "suspended":
            if (reference instanceof User) {
                attrValue.setBooleanValue(((User) reference).isSuspended());
                values.add(attrValue);
            }
            break;

        case "mustChangePassword":
            if (reference instanceof User) {
                attrValue.setBooleanValue(((User) reference).isMustChangePassword());
                values.add(attrValue);
            }
            break;

        default:
            try {
                Object fieldValue = FieldUtils.readField(reference, intAttrName.getField(), true);
                if (fieldValue instanceof Date) {
                    // needed because ConnId does not natively supports the Date type
                    attrValue.setStringValue(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT
                            .format((Date) fieldValue));
                } else if (Boolean.TYPE.isInstance(fieldValue)) {
                    attrValue.setBooleanValue((Boolean) fieldValue);
                } else if (Double.TYPE.isInstance(fieldValue) || Float.TYPE.isInstance(fieldValue)) {
                    attrValue.setDoubleValue((Double) fieldValue);
                } else if (Long.TYPE.isInstance(fieldValue) || Integer.TYPE.isInstance(fieldValue)) {
                    attrValue.setLongValue((Long) fieldValue);
                } else {
                    attrValue.setStringValue(fieldValue.toString());
                }
                values.add(attrValue);
            } catch (Exception e) {
                LOG.error("Could not read value of '{}' from {}", intAttrName.getField(), reference, e);
            }
        }
    } else if (intAttrName.getSchemaType() != null) {
        switch (intAttrName.getSchemaType()) {
        case PLAIN:
            PlainAttr<?> attr;
            if (membership == null) {
                attr = reference.getPlainAttr(intAttrName.getSchemaName()).orElse(null);
            } else {
                attr = ((GroupableRelatable<?, ?, ?, ?, ?>) reference)
                        .getPlainAttr(intAttrName.getSchemaName(), membership).orElse(null);
            }
            if (attr != null) {
                if (attr.getUniqueValue() != null) {
                    values.add(anyUtils.clonePlainAttrValue(attr.getUniqueValue()));
                } else if (attr.getValues() != null) {
                    attr.getValues().forEach(value -> values.add(anyUtils.clonePlainAttrValue(value)));
                }
            }
            break;

        case DERIVED:
            DerSchema derSchema = derSchemaDAO.find(intAttrName.getSchemaName());
            if (derSchema != null) {
                String value = membership == null ? derAttrHandler.getValue(reference, derSchema)
                        : derAttrHandler.getValue(reference, membership, derSchema);
                if (value != null) {
                    PlainAttrValue attrValue = anyUtils.newPlainAttrValue();
                    attrValue.setStringValue(value);
                    values.add(attrValue);
                }
            }
            break;

        case VIRTUAL:
            // virtual attributes don't get transformed
            transform = false;

            VirSchema virSchema = virSchemaDAO.find(intAttrName.getSchemaName());
            if (virSchema != null) {
                LOG.debug("Expire entry cache {}-{}", reference, intAttrName.getSchemaName());
                virAttrCache.expire(reference.getType().getKey(), reference.getKey(),
                        intAttrName.getSchemaName());

                List<String> virValues = membership == null ? virAttrHandler.getValues(reference, virSchema)
                        : virAttrHandler.getValues(reference, membership, virSchema);
                virValues.stream().map(value -> {
                    PlainAttrValue attrValue = anyUtils.newPlainAttrValue();
                    attrValue.setStringValue(value);
                    return attrValue;
                }).forEachOrdered(attrValue -> values.add(attrValue));
            }
            break;

        default:
        }
    }

    LOG.debug("Internal values: {}", values);

    List<PlainAttrValue> transformed = values;
    if (transform) {
        for (ItemTransformer transformer : MappingUtils.getItemTransformers(mapItem)) {
            transformed = transformer.beforePropagation(mapItem, any, transformed);
        }
        LOG.debug("Transformed values: {}", values);
    } else {
        LOG.debug("No transformation occurred");
    }

    return transformed;
}

From source file:com.sun.faces.el.impl.Coercions.java

/**
 * Coerces a String to the given primitive number class
 *//*www.ja  v a  2s.c o  m*/
static Number coerceToPrimitiveNumber(String pValue, Class pClass) throws ElException {
    if (pClass == Byte.class || pClass == Byte.TYPE) {
        return Byte.valueOf(pValue);
    } else if (pClass == Short.class || pClass == Short.TYPE) {
        return Short.valueOf(pValue);
    } else if (pClass == Integer.class || pClass == Integer.TYPE) {
        return Integer.valueOf(pValue);
    } else if (pClass == Long.class || pClass == Long.TYPE) {
        return Long.valueOf(pValue);
    } else if (pClass == Float.class || pClass == Float.TYPE) {
        return Float.valueOf(pValue);
    } else if (pClass == Double.class || pClass == Double.TYPE) {
        return Double.valueOf(pValue);
    } else if (pClass == BigInteger.class) {
        return new BigInteger(pValue);
    } else if (pClass == BigDecimal.class) {
        return new BigDecimal(pValue);
    } else {
        return PrimitiveObjects.getInteger(0);
    }
}

From source file:com.ricemap.spateDB.operations.RangeQuery.java

/**
 * Performs a range query using MapReduce
 * /*from w w  w. j av  a  2 s.c  o  m*/
 * @param fs
 * @param inputFile
 * @param queryRange
 * @param shape
 * @param output
 * @return
 * @throws IOException
 */
public static long rangeQueryMapReduce(FileSystem fs, Path inputFile, Path userOutputPath, Shape queryShape,
        Shape shape, boolean overwrite, boolean background, QueryInput query) throws IOException {
    JobConf job = new JobConf(FileMBR.class);

    FileSystem outFs = inputFile.getFileSystem(job);
    Path outputPath = userOutputPath;
    if (outputPath == null) {
        do {
            outputPath = new Path(
                    inputFile.toUri().getPath() + ".rangequery_" + (int) (Math.random() * 1000000));
        } while (outFs.exists(outputPath));
    } else {
        if (outFs.exists(outputPath)) {
            if (overwrite) {
                outFs.delete(outputPath, true);
            } else {
                throw new RuntimeException("Output path already exists and -overwrite flag is not set");
            }
        }
    }

    job.setJobName("RangeQuery");
    job.setClass(SpatialSite.FilterClass, RangeFilter.class, BlockFilter.class);
    RangeFilter.setQueryRange(job, queryShape); // Set query range for
    // filter

    ClusterStatus clusterStatus = new JobClient(job).getClusterStatus();
    job.setNumMapTasks(clusterStatus.getMaxMapTasks() * 5);
    job.setNumReduceTasks(3);

    // Decide which map function to use depending on how blocks are indexed
    // And also which input format to use
    if (SpatialSite.isRTree(fs, inputFile)) {
        // RTree indexed file
        LOG.info("Searching an RTree indexed file");
        job.setInputFormat(RTreeInputFormat.class);
    } else {
        // A file with no local index
        LOG.info("Searching a non local-indexed file");
        job.setInputFormat(ShapeInputFormat.class);
    }

    GlobalIndex<Partition> gIndex = SpatialSite.getGlobalIndex(fs, inputFile);
    // if (gIndex != null && gIndex.isReplicated()){
    // job.setMapperClass(RangeQueryMap.class);

    Class<?> OutputKey = NullWritable.class;
    try {
        Class<?> c = shape.getClass();
        Field f = c.getDeclaredField(query.field);
        f.setAccessible(true);
        if (f.getType().equals(Integer.TYPE)) {
            OutputKey = IntWritable.class;
        } else if (f.getType().equals(Double.TYPE)) {
            OutputKey = DoubleWritable.class;
        } else if (f.getType().equals(Long.TYPE)) {
            OutputKey = LongWritable.class;
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    job.setMapOutputKeyClass(OutputKey);
    switch (query.type) {
    case Distinct:
        job.setMapperClass(DistinctQueryMap.class);
        job.setReducerClass(DistinctQueryReduce.class);
        job.setMapOutputValueClass(NullWritable.class);
        break;
    case Distribution:
        job.setMapperClass(DistributionQueryMap.class);
        job.setReducerClass(DistributionQueryReduce.class);
        job.setMapOutputValueClass(IntWritable.class);
        break;
    default:
        break;
    }
    // }
    // else
    // job.setMapperClass(RangeQueryMapNoDupAvoidance.class);

    // Set query range for the map function
    job.set(QUERY_SHAPE_CLASS, queryShape.getClass().getName());
    job.set(QUERY_SHAPE, queryShape.toText(new Text()).toString());
    job.set(QUERY_FIELD, query.field);

    // Set shape class for the SpatialInputFormat
    SpatialSite.setShapeClass(job, shape.getClass());

    job.setOutputFormat(TextOutputFormat.class);

    ShapeInputFormat.setInputPaths(job, inputFile);
    TextOutputFormat.setOutputPath(job, outputPath);

    // Submit the job
    if (!background) {
        RunningJob runningJob = JobClient.runJob(job);
        Counters counters = runningJob.getCounters();
        Counter outputRecordCounter = counters.findCounter(Task.Counter.MAP_OUTPUT_RECORDS);
        final long resultCount = outputRecordCounter.getValue();

        // If outputPath not set by user, automatically delete it
        if (userOutputPath == null)
            outFs.delete(outputPath, true);

        return resultCount;
    } else {
        JobClient jc = new JobClient(job);
        lastRunningJob = jc.submitJob(job);
        return -1;
    }
}

From source file:org.apache.hadoop.hbase.regionserver.wal.TestHLog.java

@Test(timeout = 300000)
public void testAppendClose() throws Exception {
    TableName tableName = TableName.valueOf(getName());
    HRegionInfo regioninfo = new HRegionInfo(tableName, HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW,
            false);//from   ww  w .  j a  v a 2s. co m

    HLog wal = HLogFactory.createHLog(fs, dir, "hlogdir", "hlogdir_archive", conf);
    final AtomicLong sequenceId = new AtomicLong(1);
    final int total = 20;

    HTableDescriptor htd = new HTableDescriptor();
    htd.addFamily(new HColumnDescriptor(tableName.getName()));

    for (int i = 0; i < total; i++) {
        WALEdit kvs = new WALEdit();
        kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), tableName.getName()));
        wal.append(regioninfo, tableName, kvs, System.currentTimeMillis(), htd, sequenceId);
    }
    // Now call sync to send the data to HDFS datanodes
    wal.sync();
    int namenodePort = cluster.getNameNodePort();
    final Path walPath = ((FSHLog) wal).computeFilename();

    // Stop the cluster.  (ensure restart since we're sharing MiniDFSCluster)
    try {
        DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
        dfs.setSafeMode(FSConstants.SafeModeAction.SAFEMODE_ENTER);
        TEST_UTIL.shutdownMiniDFSCluster();
        try {
            // wal.writer.close() will throw an exception,
            // but still call this since it closes the LogSyncer thread first
            wal.close();
        } catch (IOException e) {
            LOG.info(e);
        }
        fs.close(); // closing FS last so DFSOutputStream can't call close
        LOG.info("STOPPED first instance of the cluster");
    } finally {
        // Restart the cluster
        while (cluster.isClusterUp()) {
            LOG.error("Waiting for cluster to go down");
            Thread.sleep(1000);
        }
        assertFalse(cluster.isClusterUp());
        cluster = null;
        for (int i = 0; i < 100; i++) {
            try {
                cluster = TEST_UTIL.startMiniDFSClusterForTestHLog(namenodePort);
                break;
            } catch (BindException e) {
                LOG.info("Sleeping.  BindException bringing up new cluster");
                Threads.sleep(1000);
            }
        }
        cluster.waitActive();
        fs = cluster.getFileSystem();
        LOG.info("STARTED second instance.");
    }

    // set the lease period to be 1 second so that the
    // namenode triggers lease recovery upon append request
    Method setLeasePeriod = cluster.getClass().getDeclaredMethod("setLeasePeriod",
            new Class[] { Long.TYPE, Long.TYPE });
    setLeasePeriod.setAccessible(true);
    setLeasePeriod.invoke(cluster, 1000L, 1000L);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        LOG.info(e);
    }

    // Now try recovering the log, like the HMaster would do
    final FileSystem recoveredFs = fs;
    final Configuration rlConf = conf;

    class RecoverLogThread extends Thread {
        public Exception exception = null;

        public void run() {
            try {
                FSUtils.getInstance(fs, rlConf).recoverFileLease(recoveredFs, walPath, rlConf, null);
            } catch (IOException e) {
                exception = e;
            }
        }
    }

    RecoverLogThread t = new RecoverLogThread();
    t.start();
    // Timeout after 60 sec. Without correct patches, would be an infinite loop
    t.join(60 * 1000);
    if (t.isAlive()) {
        t.interrupt();
        throw new Exception("Timed out waiting for HLog.recoverLog()");
    }

    if (t.exception != null)
        throw t.exception;

    // Make sure you can read all the content
    HLog.Reader reader = HLogFactory.createReader(fs, walPath, conf);
    int count = 0;
    HLog.Entry entry = new HLog.Entry();
    while (reader.next(entry) != null) {
        count++;
        assertTrue("Should be one KeyValue per WALEdit", entry.getEdit().getKeyValues().size() == 1);
    }
    assertEquals(total, count);
    reader.close();

    // Reset the lease period
    setLeasePeriod.invoke(cluster, new Object[] { new Long(60000), new Long(3600000) });
}

From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java

/**
 * Read a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding.// w ww. jav  a 2  s .  co m
 * @param in
 * @param objectWritable
 * @param conf
 * @return the object
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static Object readObject(DataInput in, HbaseObjectWritable objectWritable, Configuration conf)
        throws IOException {
    Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in));
    Object instance;
    if (declaredClass.isPrimitive()) { // primitive types
        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isArray()) { // array
        if (declaredClass.equals(byte[].class)) {
            instance = Bytes.readByteArray(in);
        } else if (declaredClass.equals(Result[].class)) {
            instance = Result.readArray(in);
        } else {
            int length = in.readInt();
            instance = Array.newInstance(declaredClass.getComponentType(), length);
            for (int i = 0; i < length; i++) {
                Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE
        Class<?> componentType = readClass(conf, in);
        int length = in.readInt();
        instance = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(instance, i, readObject(in, conf));
        }
    } else if (List.class.isAssignableFrom(declaredClass)) { // List
        int length = in.readInt();
        instance = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ((ArrayList) instance).add(readObject(in, conf));
        }
    } else if (declaredClass == String.class) { // String
        instance = Text.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in));
    } else if (declaredClass == Message.class) {
        String className = Text.readString(in);
        try {
            declaredClass = getClassByName(conf, className);
            instance = tryInstantiateProtobuf(declaredClass, in);
        } catch (ClassNotFoundException e) {
            LOG.error("Can't find class " + className, e);
            throw new IOException("Can't find class " + className, e);
        }
    } else { // Writable or Serializable
        Class instanceClass = null;
        int b = (byte) WritableUtils.readVInt(in);
        if (b == NOT_ENCODED) {
            String className = Text.readString(in);
            try {
                instanceClass = getClassByName(conf, className);
            } catch (ClassNotFoundException e) {
                LOG.error("Can't find class " + className, e);
                throw new IOException("Can't find class " + className, e);
            }
        } else {
            instanceClass = CODE_TO_CLASS.get(b);
        }
        if (Writable.class.isAssignableFrom(instanceClass)) {
            Writable writable = WritableFactories.newInstance(instanceClass, conf);
            try {
                writable.readFields(in);
            } catch (Exception e) {
                LOG.error("Error in readFields", e);
                throw new IOException("Error in readFields", e);
            }
            instance = writable;
            if (instanceClass == NullInstance.class) { // null
                declaredClass = ((NullInstance) instance).declaredClass;
                instance = null;
            }
        } else {
            int length = in.readInt();
            byte[] objectBytes = new byte[length];
            in.readFully(objectBytes);
            ByteArrayInputStream bis = null;
            ObjectInputStream ois = null;
            try {
                bis = new ByteArrayInputStream(objectBytes);
                ois = new ObjectInputStream(bis);
                instance = ois.readObject();
            } catch (ClassNotFoundException e) {
                LOG.error("Class not found when attempting to deserialize object", e);
                throw new IOException("Class not found when attempting to " + "deserialize object", e);
            } finally {
                if (bis != null)
                    bis.close();
                if (ois != null)
                    ois.close();
            }
        }
    }
    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }
    return instance;
}

From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java

/**
 * Read a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding.//from w ww.j a  v a2 s . co  m
 * @param in
 * @param objectWritable
 * @param conf
 * @return the object
 * @throws IOException
 */
@SuppressWarnings("unchecked")
static Object readObject(DataInput in, HbaseObjectWritableFor96Migration objectWritable, Configuration conf)
        throws IOException {
    Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in));
    Object instance;
    if (declaredClass.isPrimitive()) { // primitive types
        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isArray()) { // array
        if (declaredClass.equals(byte[].class)) {
            instance = Bytes.readByteArray(in);
        } else {
            int length = in.readInt();
            instance = Array.newInstance(declaredClass.getComponentType(), length);
            for (int i = 0; i < length; i++) {
                Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE
        Class<?> componentType = readClass(conf, in);
        int length = in.readInt();
        instance = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(instance, i, readObject(in, conf));
        }
    } else if (List.class.isAssignableFrom(declaredClass)) { // List
        int length = in.readInt();
        instance = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ((ArrayList) instance).add(readObject(in, conf));
        }
    } else if (declaredClass == String.class) { // String
        instance = Text.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in));
    } else if (declaredClass == Message.class) {
        String className = Text.readString(in);
        try {
            declaredClass = getClassByName(conf, className);
            instance = tryInstantiateProtobuf(declaredClass, in);
        } catch (ClassNotFoundException e) {
            LOG.error("Can't find class " + className, e);
            throw new IOException("Can't find class " + className, e);
        }
    } else if (Scan.class.isAssignableFrom(declaredClass)) {
        int length = in.readInt();
        byte[] scanBytes = new byte[length];
        in.readFully(scanBytes);
        ClientProtos.Scan.Builder scanProto = ClientProtos.Scan.newBuilder();
        instance = ProtobufUtil.toScan(scanProto.mergeFrom(scanBytes).build());
    } else { // Writable or Serializable
        Class instanceClass = null;
        int b = (byte) WritableUtils.readVInt(in);
        if (b == NOT_ENCODED) {
            String className = Text.readString(in);
            try {
                instanceClass = getClassByName(conf, className);
            } catch (ClassNotFoundException e) {
                LOG.error("Can't find class " + className, e);
                throw new IOException("Can't find class " + className, e);
            }
        } else {
            instanceClass = CODE_TO_CLASS.get(b);
        }
        if (Writable.class.isAssignableFrom(instanceClass)) {
            Writable writable = WritableFactories.newInstance(instanceClass, conf);
            try {
                writable.readFields(in);
            } catch (Exception e) {
                LOG.error("Error in readFields", e);
                throw new IOException("Error in readFields", e);
            }
            instance = writable;
            if (instanceClass == NullInstance.class) { // null
                declaredClass = ((NullInstance) instance).declaredClass;
                instance = null;
            }
        } else {
            int length = in.readInt();
            byte[] objectBytes = new byte[length];
            in.readFully(objectBytes);
            ByteArrayInputStream bis = null;
            ObjectInputStream ois = null;
            try {
                bis = new ByteArrayInputStream(objectBytes);
                ois = new ObjectInputStream(bis);
                instance = ois.readObject();
            } catch (ClassNotFoundException e) {
                LOG.error("Class not found when attempting to deserialize object", e);
                throw new IOException("Class not found when attempting to " + "deserialize object", e);
            } finally {
                if (bis != null)
                    bis.close();
                if (ois != null)
                    ois.close();
            }
        }
    }
    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }
    return instance;
}

From source file:javadz.beanutils.ConvertUtilsBean.java

/**
 * Register the converters for primitive types.
 * </p>/*  w w  w. ja  v  a  2 s.c om*/
 * This method registers the following converters:
 * <ul>
 *     <li><code>Boolean.TYPE</code> - {@link BooleanConverter}</li>
 *     <li><code>Byte.TYPE</code> - {@link ByteConverter}</li>
 *     <li><code>Character.TYPE</code> - {@link CharacterConverter}</li>
 *     <li><code>Double.TYPE</code> - {@link DoubleConverter}</li>
 *     <li><code>Float.TYPE</code> - {@link FloatConverter}</li>
 *     <li><code>Integer.TYPE</code> - {@link IntegerConverter}</li>
 *     <li><code>Long.TYPE</code> - {@link LongConverter}</li>
 *     <li><code>Short.TYPE</code> - {@link ShortConverter}</li>
 * </ul>
 * @param throwException <code>true</code> if the converters should
 * throw an exception when a conversion error occurs, otherwise <code>
 * <code>false</code> if a default value should be used.
 */
private void registerPrimitives(boolean throwException) {
    register(Boolean.TYPE, throwException ? new BooleanConverter() : new BooleanConverter(Boolean.FALSE));
    register(Byte.TYPE, throwException ? new ByteConverter() : new ByteConverter(ZERO));
    register(Character.TYPE, throwException ? new CharacterConverter() : new CharacterConverter(SPACE));
    register(Double.TYPE, throwException ? new DoubleConverter() : new DoubleConverter(ZERO));
    register(Float.TYPE, throwException ? new FloatConverter() : new FloatConverter(ZERO));
    register(Integer.TYPE, throwException ? new IntegerConverter() : new IntegerConverter(ZERO));
    register(Long.TYPE, throwException ? new LongConverter() : new LongConverter(ZERO));
    register(Short.TYPE, throwException ? new ShortConverter() : new ShortConverter(ZERO));
}