Example usage for java.lang InstantiationException getMessage

List of usage examples for java.lang InstantiationException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.flycraft.vkontakteapi.model.ParseUtils.java

/**
 * Parses object with follow rules:// www .  ja  v  a2 s .  c o m
 * <p/>
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 * arrays of primitive types, {@link java.lang.String}s and {@link org.flycraft.vkontakteapi.model.VKApiModel}s,
 * list implementation line {@link org.flycraft.vkontakteapi.model.VKList}, {@link org.flycraft.vkontakteapi.model.VKAttachments.VKApiAttachment} or {@link org.flycraft.vkontakteapi.model.VKPhotoSizes},
 * {@link org.flycraft.vkontakteapi.model.VKApiModel}s.
 * <p/>
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T>    type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules:// ww w . j  a  va2s.c om
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.tmall.wireless.tangram.util.Utils.java

public static <T> T newInstance(Class<T> clz) {
    if (clz != null) {
        try {/*from   ww  w  .j  a v  a 2 s  .  c  o m*/
            return clz.newInstance();
        } catch (InstantiationException e) {
            if (TangramBuilder.isPrintLog())
                Log.e("ClassResolver", e.getMessage(), e);
        } catch (IllegalAccessException e) {
            if (TangramBuilder.isPrintLog())
                Log.e("ClassResolver", e.getMessage(), e);
        }
    }
    return null;
}

From source file:com.servioticy.queueclient.QueueClient.java

private static QueueClient createInstance(String configPath, String type, String baseAddress,
        String relativeAddress) throws QueueClientException {

    QueueClient instance;/*from   w  w  w.  ja v  a 2  s.  c  o m*/

    try {
        File f = new File(configPath);
        if (!f.exists()) {
            if (Thread.currentThread().getContextClassLoader().getResource(configPath) == null) {
                KestrelMemcachedClient kInstance = new KestrelMemcachedClient();
                kInstance.setBaseAddress(baseAddress);
                kInstance.setRelativeAddress(relativeAddress);
                kInstance.setExpire(0);
                return kInstance;
            }
        }
        String className;
        HierarchicalConfiguration config, queueConfig;

        config = new XMLConfiguration(configPath);
        config.setExpressionEngine(new XPathExpressionEngine());

        className = config.getString("queue[type='" + type + "']/className");
        instance = (QueueClient) Class.forName(className).newInstance();
        instance.setBaseAddress(baseAddress);
        instance.setRelativeAddress(relativeAddress);
        queueConfig = (HierarchicalConfiguration) config
                .configurationAt("queue[type='" + type + "']/concreteConf");
        instance.init(queueConfig);

    } catch (InstantiationException e) {
        String errMsg = "Unable to instantiate the queue class (" + e.getMessage() + ").";
        logger.error(errMsg);
        throw new QueueClientException(errMsg);
    } catch (IllegalAccessException e) {
        String errMsg = "Unable to load the queue class (" + e.getMessage() + ").";
        logger.error(errMsg);
        throw new QueueClientException(errMsg);
    } catch (ClassNotFoundException e) {
        String errMsg = "The queue class does not exist (" + e.getMessage() + ").";
        logger.error(errMsg);
        throw new QueueClientException(errMsg);
    } catch (ConfigurationException e) {
        String errMsg = "'" + configPath + "' configuration file is malformed (" + e.getMessage() + ").";
        logger.error(errMsg);
        throw new QueueClientException(errMsg);
    }

    return instance;
}

From source file:com.genentech.chemistry.tool.sdfAggregator.SDFAggregator.java

private static AggInterface[] createAggregationFunction(String[] funcStrs) {
    String outTag = null;/*from   w ww.  j a  v a2  s  .  c  om*/
    String resFormat = null;
    String functionName = null;
    String fnargs = null;
    AggInterface[] ret = new AggInterface[funcStrs.length];

    for (int i = 0; i < funcStrs.length; i++) {
        String funcstr = funcStrs[i];

        Pattern pat = Pattern.compile(" *([^:]+)(:.*)? *= *(\\w+) *\\( *(.*)\\) *");
        Matcher mat = pat.matcher(funcstr);
        if (mat.matches()) {
            outTag = mat.group(1);
            resFormat = mat.group(2);
            functionName = mat.group(3);
            fnargs = mat.group(4);

            if (resFormat != null)
                resFormat = resFormat.substring(1);

        } else // no output name given => construct from function name
        {
            pat = Pattern.compile(" *(\\w+) *\\( *(.+) *\\) *");
            mat = pat.matcher(funcstr);

            if (mat.matches()) {
                functionName = mat.group(2);
                fnargs = mat.group(3);
                outTag = functionName + '-' + fnargs;

            } else if (funcstr.matches(" *count\\( *\\) *")) {
                functionName = "count"; // for backward compatibility
                fnargs = groups.get(0); // just first group by column
                outTag = "ClusterCount";

            } else {
                System.err.printf("Invalid aggregation function: %s\n", funcstr);
                exitWithHelp(options);
            }
        }

        try {
            @SuppressWarnings("unchecked")
            Class<AggInterface> aFunctClass = (Class<AggInterface>) Class
                    .forName(PACKAGEName + "." + functionName);
            Constructor<AggInterface> constr = aFunctClass.getConstructor(String.class, String.class,
                    String.class, String.class);

            ret[i] = constr.newInstance(outTag, resFormat, functionName, fnargs);

        } catch (InstantiationException e) {
            System.err.println(e.getMessage());
            System.err.println("Function does not exist: " + functionName);
            exitWithHelp(options);

        } catch (IllegalAccessException e) {
            System.err.println(e.getMessage());
            System.err.println("Function does not exist: " + functionName);
            exitWithHelp(options);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
            System.err.println("Function does not exist: " + functionName);
            exitWithHelp(options);

        } catch (NoSuchMethodException e) {
            System.err.println("Function is not implemented correctly: " + functionName);
            System.err.println(e.getMessage());
            exitWithHelp(options);

        } catch (InvocationTargetException e) {
            System.err.println(e.getTargetException().getMessage());
            exitWithHelp(options);

        } catch (Throwable e) {
            System.err.println(e.getMessage());
            exitWithHelp(options);
        }
    }

    return ret;
}

From source file:com.rockagen.commons.util.ClassUtil.java

/**
 * Create new instance of specified class and type
 * //from   w  ww  .  j a va2s  .  c o  m
 * @param clazz class
 * @param accessible accessible
 * @param <T> t                      
 * @return instance
 */
public static <T> T getInstance(Class<T> clazz, boolean accessible) {
    if (clazz == null)
        return null;

    T t = null;

    try {
        Constructor<T> constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(accessible);
        t = constructor.newInstance();
    } catch (InstantiationException e) {
        log.error("{}", e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.error("{}", e.getMessage(), e);
    } catch (SecurityException e) {
        log.error("{}", e.getMessage(), e);
    } catch (NoSuchMethodException e) {
        log.error("{}", e.getMessage(), e);
    } catch (IllegalArgumentException e) {
        log.error("{}", e.getMessage(), e);
    } catch (InvocationTargetException e) {
        log.error("{}", e.getMessage(), e);
    }

    return t;
}

From source file:com.threewks.thundr.module.Modules.java

protected static Module loadModule(Class<? extends Module> moduleClass) {
    try {//from  www  .ja va  2s  .c o  m
        Object newInstance = moduleClass.newInstance();
        Module configuration = Cast.as(newInstance, Module.class);
        if (configuration == null) {
            throw new ModuleLoadingException(
                    "Failed to load module '%s' - the configuration class %s does not implement '%s'",
                    moduleClass.getName(), Module.class.getName());
        }
        return configuration;
    } catch (InstantiationException e) {
        throw new ModuleLoadingException(e, moduleClass.getPackage().getName(),
                "failed to instantiate configuration class %s: %s", moduleClass.getName(), e.getMessage());
    } catch (IllegalAccessException e) {
        throw new ModuleLoadingException(e, moduleClass.getPackage().getName(),
                "cannot instantiate configuration class %s: %s", moduleClass.getName(), e.getMessage());
    }
}

From source file:com.cloud.consoleproxy.ConsoleProxy.java

public static ConsoleProxyServerFactory getHttpServerFactory() {
    try {/*  w  ww. j a v a 2 s.co m*/
        Class<?> clz = Class.forName(factoryClzName);
        try {
            ConsoleProxyServerFactory factory = (ConsoleProxyServerFactory) clz.newInstance();
            factory.init(ConsoleProxy.ksBits, ConsoleProxy.ksPassword);
            return factory;
        } catch (InstantiationException e) {
            s_logger.error(e.getMessage(), e);
            return null;
        } catch (IllegalAccessException e) {
            s_logger.error(e.getMessage(), e);
            return null;
        }
    } catch (ClassNotFoundException e) {
        s_logger.warn("Unable to find http server factory class: " + factoryClzName);
        return new ConsoleProxyBaseServerFactoryImpl();
    }
}

From source file:org.apache.fop.render.afp.AFPFontConfig.java

private static Typeface getTypeFace(String base14Name) throws ClassNotFoundException {
    try {//from ww w  .j  av a  2  s . co m
        Class<? extends Typeface> clazz = Class.forName("org.apache.fop.fonts.base14." + base14Name)
                .asSubclass(Typeface.class);
        return clazz.newInstance();
    } catch (IllegalAccessException iae) {
        LOG.error(iae.getMessage());
    } catch (ClassNotFoundException cnfe) {
        LOG.error(cnfe.getMessage());
    } catch (InstantiationException ie) {
        LOG.error(ie.getMessage());
    }
    throw new ClassNotFoundException("Couldn't load file for AFP font with base14 name: " + base14Name);
}

From source file:org.apache.beehive.netui.pageflow.MultipartRequestUtils.java

/**
 * Create an implementation of a {@link MultipartRequestHandler} for this
 * mulitpart request.// ww  w  . j  ava  2  s.co  m
 *
 * @param request the current request object
 * @return the handler
 * @throws ServletException if an error occurs loading this file.  These exception messages
 * are not internationalized as Struts does not internationalize them either.
 */
// @Struts: org.apache.struts.util.RequestUtils.getMultipartHandler
private static final MultipartRequestHandler getMultipartHandler(HttpServletRequest request)
        throws ServletException {
    MultipartRequestHandler multipartHandler = null;
    String multipartClass = (String) request.getAttribute(Globals.MULTIPART_KEY);
    request.removeAttribute(Globals.MULTIPART_KEY);

    // Try to initialize the mapping specific request handler
    if (multipartClass != null) {
        try {
            multipartHandler = (MultipartRequestHandler) RequestUtils.applicationInstance(multipartClass);
        } catch (ClassNotFoundException cnfe) {
            _log.error("MultipartRequestHandler class \"" + multipartClass + "\" in mapping class not found, "
                    + "defaulting to global multipart class");
        } catch (InstantiationException ie) {
            _log.error(
                    "InstantiaionException when instantiating " + "MultipartRequestHandler \"" + multipartClass
                            + "\", " + "defaulting to global multipart class, exception: " + ie.getMessage());
        } catch (IllegalAccessException iae) {
            _log.error(
                    "IllegalAccessException when instantiating " + "MultipartRequestHandler \"" + multipartClass
                            + "\", " + "defaulting to global multipart class, exception: " + iae.getMessage());
        }

        if (multipartHandler != null)
            return multipartHandler;
    }

    ModuleConfig moduleConfig = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
    multipartClass = moduleConfig.getControllerConfig().getMultipartClass();

    // Try to initialize the global request handler
    if (multipartClass != null) {
        try {
            multipartHandler = (MultipartRequestHandler) RequestUtils.applicationInstance(multipartClass);
        } catch (ClassNotFoundException cnfe) {
            throw new ServletException("Cannot find multipart class \"" + multipartClass + "\""
                    + ", exception: " + cnfe.getMessage());
        } catch (InstantiationException ie) {
            throw new ServletException("InstantiaionException when instantiating " + "multipart class \""
                    + multipartClass + "\", exception: " + ie.getMessage());
        } catch (IllegalAccessException iae) {
            throw new ServletException("IllegalAccessException when instantiating " + "multipart class \""
                    + multipartClass + "\", exception: " + iae.getMessage());
        }

        if (multipartHandler != null)
            return multipartHandler;
    }

    return multipartHandler;
}