Example usage for java.lang ClassCastException ClassCastException

List of usage examples for java.lang ClassCastException ClassCastException

Introduction

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

Prototype

public ClassCastException(String s) 

Source Link

Document

Constructs a ClassCastException with the specified detail message.

Usage

From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java

/** Loads strategy class and creates instance by calling constructor.
    @param strategyText contains full class name followed by
    parameter list for constructor.  Constructor parameters may be
    int, double, boolean, String.  Constructor parameters are parsed by
    splitting on commas and trimming whitespace.
    <pre>//from ww  w  . ja va  2s.com
    mypkg.MyStrategy(12, -345.67, true, false, Alpha Strategy)
    </pre>
**/
protected TradingStrategy loadStrategy(String strategyText)
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
        ExceptionInInitializerError, InstantiationException, InvocationTargetException {
    Pattern strategyPattern = // matches full.class.Name(args...)
            Pattern.compile("^([A-Za-z](?:[A-Za-z0-9_.]*))\\s*[(](.*)[)]$");
    Matcher matcher = strategyPattern.matcher(strategyText);
    if (!matcher.matches())
        throw new IllegalArgumentException(
                "Bad Strategy: " + strategyText + "\n" + "Expected: full.class.name(-123.45, 67, true, false)");

    final String strategyClassName = matcher.group(1).trim();
    String parameters[] = matcher.group(2).split(",");

    // clean parameters
    for (int i = 0; i < parameters.length; i++)
        parameters[i] = parameters[i].trim();
    if (parameters.length == 1 && parameters[0].length() == 0)
        parameters = new String[] {}; // 0 parameters

    // build classpath
    String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator);
    ArrayList<URL> classPathURLs = new ArrayList<URL>();
    for (int i = 0; i < classPath.length; i++) {
        String path = classPath[i];
        if (".".equals(path))
            path = System.getProperty("user.dir");
        path = path.replace(File.separatorChar, '/');
        if (!path.endsWith("/") && !path.endsWith(".jar"))
            path += "/";
        try {
            classPathURLs.add(new File(path).toURL());
        } catch (MalformedURLException e) {
            // bad directory in class path, skip
        }
    }
    final String strategyPackagePrefix = strategyClassName.substring(0,
            Math.max(0, strategyClassName.lastIndexOf('.') + 1));
    ClassLoader loader = new URLClassLoader(classPathURLs.toArray(new URL[] {}),
            this.getClass().getClassLoader()) {
        /** Don't search parent for classes with strategyPackagePrefix.
            Exception: interface TradingStrategy **/
        protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
            Class<?> loadedClass = findLoadedClass(className);
            if (loadedClass != null)
                return loadedClass;
            if (!className.startsWith(strategyPackagePrefix)
                    || className.equals(TradingStrategy.class.getName())) {
                loadedClass = this.getParent().loadClass(className);
                if (loadedClass != null)
                    return loadedClass;
            }
            loadedClass = findClass(className);
            if (loadedClass != null) {
                if (resolve)
                    resolveClass(loadedClass);
                return loadedClass;
            } else
                throw new ClassNotFoundException(className);
        }
    };
    // load class.  Throws ClassNotFoundException if not found.
    Class<?> strategyClass = loader.loadClass(strategyClassName);

    // Make sure it is a TradingStrategy.
    if (!TradingStrategy.class.isAssignableFrom(strategyClass))
        throw new ClassCastException(strategyClass.getName() + " does not implement TradingStrategy");

    // Find constructor compatible with parameters
    Constructor[] constructors = strategyClass.getConstructors();
    findConstructor: for (Constructor constructor : constructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length != parameters.length)
            continue;
        Object[] values = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            if (boolean.class.equals(parameterTypes[i])) {
                String parameter = parameters[i].toLowerCase();
                if ("false".equals(parameter))
                    values[i] = Boolean.FALSE;
                else if ("true".equals(parameter))
                    values[i] = Boolean.TRUE;
                else
                    continue findConstructor;
            } else if (int.class.equals(parameterTypes[i])) {
                try {
                    values[i] = new Integer(parameters[i]);
                } catch (NumberFormatException e) {
                    continue findConstructor;
                }
            } else if (double.class.equals(parameterTypes[i])) {
                try {
                    values[i] = new Double(parameters[i]);
                } catch (NumberFormatException e) {
                    continue findConstructor;
                }
            } else if (String.class.equals(parameterTypes[i])) {
                values[i] = parameters[i];
            } else
                continue findConstructor; // unsupported parameter type, skip
        }
        // all values matched types, so create instance
        return (TradingStrategy) constructor.newInstance(values);
    }
    throw new NoSuchMethodException(strategyText);
}

From source file:com.s3d.webapps.util.time.DateUtils.java

/**
 * <p>Ceil this date, leaving the field specified as the most
 * significant field.</p>//from  w  w w.  ja  va 2  s .c om
 *
 * <p>For example, if you had the datetime of 28 Mar 2002
 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
 * 2002 13:00:00.000.  If this was passed with MONTH, it would
 * return 1 Mar 2002 0:00:00.000.</p>
 * 
 * @param date  the date to work with, either <code>Date</code>
 *  or <code>Calendar</code>
 * @param field  the field from <code>Calendar</code>
 *  or <code>SEMI_MONTH</code>
 * @return the rounded date
 * @throws IllegalArgumentException if the date
 *  is <code>null</code>
 * @throws ClassCastException if the object type is not a
 *  <code>Date</code> or <code>Calendar</code>
 * @throws ArithmeticException if the year is over 280 million
 * @since 2.5
 */
public static Date ceiling(Object date, int field) {
    if (date == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
    if (date instanceof Date) {
        return ceiling((Date) date, field);
    } else if (date instanceof Calendar) {
        return ceiling((Calendar) date, field).getTime();
    } else {
        throw new ClassCastException("Could not find ceiling of for type: " + date.getClass());
    }
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Reads an array from JSON, where each value is of the class clazz.  Note that while the result
 * is an array, you cannot assume that it is an array of Object, or use generics because generics
 * are always Objects - this is because arrays of primitive types are not arrays of Objects
 * @param jp/*from   w  ww.j ava 2 s. c  o m*/
 * @param clazz
 * @return
 * @throws IOException
 */
private Object readArray(JsonParser jp, Class clazz) throws IOException {
    if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
        return null;

    boolean isProxyClass = Proxied.class.isAssignableFrom(clazz);
    ArrayList result = new ArrayList();
    for (; jp.nextToken() != JsonToken.END_ARRAY;) {
        if (isProxyClass) {
            Integer id = jp.readValueAs(Integer.class);
            if (id != null) {
                Proxied obj = getProxied(id);
                if (obj == null)
                    log.fatal("Cannot read object of class " + clazz + " from id=" + id);
                else if (!clazz.isInstance(obj))
                    throw new ClassCastException(
                            "Cannot cast " + obj + " class " + obj.getClass() + " to " + clazz);
                else
                    result.add(obj);
            } else
                result.add(null);
        } else {
            Object obj = readSimpleValue(jp, clazz);
            result.add(obj);
        }
    }

    Object arr = Array.newInstance(clazz, result.size());
    for (int i = 0; i < result.size(); i++)
        Array.set(arr, i, result.get(i));
    return arr;
    //return result.toArray(Array.newInstance(clazz, result.size()));
}

From source file:com.irccloud.android.fragment.MessageViewFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {/* ww  w .jav  a  2 s  .  c o  m*/
        mListener = (MessageViewListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement MessageViewListener");
    }
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Reads an array from JSON, where each value is of the class clazz.  Note that while the result
 * is an array, you cannot assume that it is an array of Object, or use generics because generics
 * are always Objects - this is because arrays of primitive types are not arrays of Objects
 * @param jp/*from   w  ww.ja va2s  .  c  o m*/
 * @param clazz
 * @return
 * @throws IOException
 */
private Map readMap(JsonParser jp, Class keyClazz, Class clazz) throws IOException {
    if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
        return null;

    boolean isProxyClass = Proxied.class.isAssignableFrom(clazz);
    if (keyClazz == null)
        keyClazz = String.class;
    HashMap result = new HashMap();
    for (; jp.nextToken() != JsonToken.END_OBJECT;) {
        Object key = readSimpleValue(jp, keyClazz);

        jp.nextToken();

        if (isProxyClass) {
            Integer id = jp.readValueAs(Integer.class);
            if (id != null) {
                Proxied obj = getProxied(id);
                if (!clazz.isInstance(obj))
                    throw new ClassCastException(
                            "Cannot cast " + obj + " class " + obj.getClass() + " to " + clazz);
                result.put(key, obj);
            } else
                result.put(key, null);
        } else {
            Object obj = readSimpleValue(jp, clazz);
            result.put(key, obj);
        }
    }

    return result;
}

From source file:com.xwtec.xwserver.util.json.JSONObject.java

private static JSONObject _fromJSONObject(JSONObject object, JsonConfig jsonConfig) {
    if (object == null || object.isNullObject()) {
        fireObjectStartEvent(jsonConfig);
        fireObjectEndEvent(jsonConfig);/*from   w w  w .j a  v a2 s  .c  om*/
        return new JSONObject(true);
    }

    if (!addInstance(object)) {
        try {
            return jsonConfig.getCycleDetectionStrategy().handleRepeatedReferenceAsObject(object);
        } catch (JSONException jsone) {
            removeInstance(object);
            fireErrorEvent(jsone, jsonConfig);
            throw jsone;
        } catch (RuntimeException e) {
            removeInstance(object);
            JSONException jsone = new JSONException(e);
            fireErrorEvent(jsone, jsonConfig);
            throw jsone;
        }
    }
    fireObjectStartEvent(jsonConfig);

    JSONArray sa = object.names(jsonConfig);
    Collection exclusions = jsonConfig.getMergedExcludes();
    JSONObject jsonObject = new JSONObject();
    PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
    for (Iterator i = sa.iterator(); i.hasNext();) {
        Object k = i.next();
        if (k == null) {
            throw new JSONException("JSON keys cannot be null.");
        }
        if (!(k instanceof String) && !jsonConfig.isAllowNonStringKeys()) {
            throw new ClassCastException("JSON keys must be strings.");
        }
        String key = String.valueOf(k);
        if ("null".equals(key)) {
            throw new NullPointerException("JSON keys must not be null nor the 'null' string.");
        }
        if (exclusions.contains(key)) {
            continue;
        }
        Object value = object.opt(key);
        if (jsonPropertyFilter != null && jsonPropertyFilter.apply(object, key, value)) {
            continue;
        }
        if (jsonObject.properties.containsKey(key)) {
            jsonObject.accumulate(key, value, jsonConfig);
            firePropertySetEvent(key, value, true, jsonConfig);
        } else {
            jsonObject.setInternal(key, value, jsonConfig);
            firePropertySetEvent(key, value, false, jsonConfig);
        }
    }

    removeInstance(object);
    fireObjectEndEvent(jsonConfig);
    return jsonObject;
}

From source file:com.mellanox.r4h.DFSClient.java

/**
 * Get block location information about a list of {@link HdfsBlockLocation}.
 * Used by {@link DistributedFileSystem#getFileBlockStorageLocations(List)} to
 * get {@link BlockStorageLocation}s for blocks returned by
 * {@link DistributedFileSystem#getFileBlockLocations(org.apache.hadoop.fs.FileStatus, long, long)} .
 * //from   w w  w  .  jav a  2s .  c  o  m
 * This is done by making a round of RPCs to the associated datanodes, asking
 * the volume of each block replica. The returned array of {@link BlockStorageLocation} expose this information as a {@link VolumeId}.
 * 
 * @param blockLocations
 *            target blocks on which to query volume location information
 * @return volumeBlockLocations original block array augmented with additional
 *         volume location information for each replica.
 */
public BlockStorageLocation[] getBlockStorageLocations(List<BlockLocation> blockLocations)
        throws IOException, UnsupportedOperationException, InvalidBlockTokenException {
    if (!getConf().isHdfsBlocksMetadataEnabled()) {
        throw new UnsupportedOperationException("Datanode-side support for "
                + "getVolumeBlockLocations() must also be enabled in the client " + "configuration.");
    }
    // Downcast blockLocations and fetch out required LocatedBlock(s)
    List<LocatedBlock> blocks = new ArrayList<LocatedBlock>();
    for (BlockLocation loc : blockLocations) {
        if (!(loc instanceof HdfsBlockLocation)) {
            throw new ClassCastException(
                    "DFSClient#getVolumeBlockLocations " + "expected to be passed HdfsBlockLocations");
        }
        HdfsBlockLocation hdfsLoc = (HdfsBlockLocation) loc;
        blocks.add(hdfsLoc.getLocatedBlock());
    }

    // Re-group the LocatedBlocks to be grouped by datanodes, with the values
    // a list of the LocatedBlocks on the datanode.
    Map<DatanodeInfo, List<LocatedBlock>> datanodeBlocks = new LinkedHashMap<DatanodeInfo, List<LocatedBlock>>();
    for (LocatedBlock b : blocks) {
        for (DatanodeInfo info : b.getLocations()) {
            if (!datanodeBlocks.containsKey(info)) {
                datanodeBlocks.put(info, new ArrayList<LocatedBlock>());
            }
            List<LocatedBlock> l = datanodeBlocks.get(info);
            l.add(b);
        }
    }

    // Make RPCs to the datanodes to get volume locations for its replicas
    TraceScope scope = Trace.startSpan("getBlockStorageLocations", traceSampler);
    Map<DatanodeInfo, HdfsBlocksMetadata> metadatas;
    try {
        metadatas = BlockStorageLocationUtilBridge.queryDatanodesForHdfsBlocksMetadata(conf, datanodeBlocks,
                getConf().getFileBlockStorageLocationsNumThreads(),
                getConf().getFileBlockStorageLocationsTimeoutMs(), getConf().getConnectToDnViaHostname());
        if (LOG.isTraceEnabled()) {
            LOG.trace("metadata returned: " + Joiner.on("\n").withKeyValueSeparator("=").join(metadatas));
        }
    } finally {
        scope.close();
    }

    // Regroup the returned VolumeId metadata to again be grouped by
    // LocatedBlock rather than by datanode
    Map<LocatedBlock, List<VolumeId>> blockVolumeIds = BlockStorageLocationUtilBridge
            .associateVolumeIdsWithBlocks(blocks, metadatas);

    // Combine original BlockLocations with new VolumeId information
    BlockStorageLocation[] volumeBlockLocations = BlockStorageLocationUtilBridge
            .convertToVolumeBlockLocations(blocks, blockVolumeIds);

    return volumeBlockLocations;
}

From source file:com.irccloud.android.fragment.BuffersListFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {/*from  w w  w .  ja  v  a  2s.c o m*/
        mListener = (OnBufferSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnBufferSelectedListener");
    }
}

From source file:com.s3d.webapps.util.time.DateUtils.java

/**
 * <p>This constructs an <code>Iterator</code> over each day in a date
 * range defined by a focus date and range style.</p>
 *
 * <p>For instance, passing Thursday, July 4, 2002 and a
 * <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code>
 * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
 * 2002, returning a Calendar instance for each intermediate day.</p>
 *
 * @param focus  the date to work with, either
 *  <code>Date</code> or <code>Calendar</code>
 * @param rangeStyle  the style constant to use. Must be one of the range
 * styles listed for the {@link #iterator(Calendar, int)} method.
 * @return the date iterator//from w  ww. ja va 2 s  .c  o m
 * @throws IllegalArgumentException if the date
 *  is <code>null</code>
 * @throws ClassCastException if the object type is
 *  not a <code>Date</code> or <code>Calendar</code>
 */
@SuppressWarnings("rawtypes")
public static Iterator iterator(Object focus, int rangeStyle) {
    if (focus == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
    if (focus instanceof Date) {
        return iterator((Date) focus, rangeStyle);
    } else if (focus instanceof Calendar) {
        return iterator((Calendar) focus, rangeStyle);
    } else {
        throw new ClassCastException("Could not iterate based on " + focus);
    }
}

From source file:com.xwtec.xwserver.util.json.JSONObject.java

private static JSONObject _fromMap(Map map, JsonConfig jsonConfig) {
    if (map == null) {
        fireObjectStartEvent(jsonConfig);
        fireObjectEndEvent(jsonConfig);// w  ww  .  j  a  va 2 s. co  m
        return new JSONObject(true);
    }

    if (!addInstance(map)) {
        try {
            return jsonConfig.getCycleDetectionStrategy().handleRepeatedReferenceAsObject(map);
        } catch (JSONException jsone) {
            removeInstance(map);
            fireErrorEvent(jsone, jsonConfig);
            throw jsone;
        } catch (RuntimeException e) {
            removeInstance(map);
            JSONException jsone = new JSONException(e);
            fireErrorEvent(jsone, jsonConfig);
            throw jsone;
        }
    }
    fireObjectStartEvent(jsonConfig);

    Collection exclusions = jsonConfig.getMergedExcludes();
    JSONObject jsonObject = new JSONObject();
    PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
    try {
        for (Iterator entries = map.entrySet().iterator(); entries.hasNext();) {
            boolean bypass = false;
            Map.Entry entry = (Map.Entry) entries.next();
            Object k = entry.getKey();
            if (k == null) {
                throw new JSONException("JSON keys cannot be null.");
            }
            if (!(k instanceof String) && !jsonConfig.isAllowNonStringKeys()) {
                throw new ClassCastException("JSON keys must be strings.");
            }
            String key = String.valueOf(k);
            if ("null".equals(key)) {
                throw new NullPointerException("JSON keys must not be null nor the 'null' string.");
            }
            if (exclusions.contains(key)) {
                continue;
            }
            Object value = entry.getValue();
            if (jsonPropertyFilter != null && jsonPropertyFilter.apply(map, key, value)) {
                continue;
            }
            if (value != null) {
                JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(value.getClass(),
                        key);
                if (jsonValueProcessor != null) {
                    value = jsonValueProcessor.processObjectValue(key, value, jsonConfig);
                    bypass = true;
                    if (!JsonVerifier.isValidJsonValue(value)) {
                        throw new JSONException("Value is not a valid JSON value. " + value);
                    }
                }
                setValue(jsonObject, key, value, value.getClass(), jsonConfig, bypass);
            } else {
                if (jsonObject.properties.containsKey(key)) {
                    jsonObject.accumulate(key, JSONNull.getInstance());
                    firePropertySetEvent(key, JSONNull.getInstance(), true, jsonConfig);
                } else {
                    jsonObject.element(key, JSONNull.getInstance());
                    firePropertySetEvent(key, JSONNull.getInstance(), false, jsonConfig);
                }
            }
        }
    } catch (JSONException jsone) {
        removeInstance(map);
        fireErrorEvent(jsone, jsonConfig);
        throw jsone;
    } catch (RuntimeException e) {
        removeInstance(map);
        JSONException jsone = new JSONException(e);
        fireErrorEvent(jsone, jsonConfig);
        throw jsone;
    }

    removeInstance(map);
    fireObjectEndEvent(jsonConfig);
    return jsonObject;
}