Example usage for java.lang Class getConstructor

List of usage examples for java.lang Class getConstructor

Introduction

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

Prototype

@CallerSensitive
public Constructor<T> getConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Usage

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Helper method to create an object based on a class name specified in the properties file. Note
 * that all classes instantiated here must provide an empty constructor.
 *
 * @param clazz the super class of the object to be created
 * @param property the property that has the class name as a value
 * @param context holding shared objects during the optimization process
 * @return the instantiated object/*from w w w  . ja  v a2s .  co  m*/
 * @throws KeywordOptimizerException in case of a problem lading the specified object
 */
@SuppressWarnings(value = "unchecked")
private static <Type> Type createObjectBasedOnProperty(Class<Type> clazz, KeywordOptimizerProperty property,
        OptimizationContext context) throws KeywordOptimizerException {
    String className = context.getConfiguration().getString(property.getName());
    if (className == null || className.isEmpty()) {
        throw new KeywordOptimizerException("Mandatory property '" + property.getName() + "' is missing");
    }

    try {
        Class<Type> dynamicClazz = (Class<Type>) Class.forName(className);

        // First try if there is a constructor expecting the optimization context.
        try {
            Constructor<Type> constructor = dynamicClazz.getConstructor(OptimizationContext.class);
            Type obj = constructor.newInstance(context);
            return clazz.cast(obj);
        } catch (NoSuchMethodException e) {
            // Ignore.
        }

        // Else use default constructor.
        Constructor<Type> constructor = dynamicClazz.getConstructor();
        Type obj = constructor.newInstance();
        return clazz.cast(obj);
    } catch (ReflectiveOperationException e) {
        throw new KeywordOptimizerException("Error constructing '" + className + "'");
    }
}

From source file:com.log4ic.compressor.utils.MemcachedUtils.java

@SuppressWarnings("unchecked")
private static MemcachedConfig getMemcachedConfig(InputStream in) throws DocumentException {
    SAXReader reader = new SAXReader();

    MemcachedConfig config = new MemcachedConfig();

    Document doc = reader.read(in);

    logger.debug("??...");
    List<Node> nodeList = doc.selectNodes("/memcached/servers/server");
    if (nodeList.isEmpty()) {
        throw new DocumentException(CONFIG_FILE_PATH + " file memcached.servers server element empty!");
    } else {//from  w w w . j ava  2  s.  c  o  m
        logger.debug("???" + nodeList.size() + ".");
    }

    AddressConfig addrConf = biludAddrMapConfig(nodeList);

    config.builder = new XMemcachedClientBuilder(addrConf.addressMap, addrConf.widgets);

    Element el = (Element) doc.selectSingleNode("/memcached");
    logger.debug("??...");
    Attribute attr = el.attribute("connectionPoolSize");
    if (attr != null) {
        String connPoolSize = attr.getValue();
        if (StringUtils.isNotBlank(connPoolSize)) {
            try {
                config.builder.setConnectionPoolSize(Integer.parseInt(connPoolSize));
                logger.debug("?" + connPoolSize);
            } catch (Exception e) {
                logger.error("???", e);
            }
        } else {
            logger.error("???");
        }
    } else {
        logger.warn("??");
    }
    logger.debug("??...");
    attr = el.attribute("enableHeartBeat");
    if (attr != null) {
        String enableHeartBeatS = attr.getValue();
        if (StringUtils.isNotBlank(enableHeartBeatS)) {
            try {
                config.enableHeartBeat = Boolean.parseBoolean(enableHeartBeatS);
                logger.debug("???" + enableHeartBeatS);
            } catch (Exception e) {
                logger.error("?????", e);
            }
        } else {
            logger.error("?????");
        }
    } else {
        logger.warn("????");
    }
    logger.debug("?...");
    attr = el.attribute("sessionIdleTimeout");
    if (attr != null) {
        String sessionIdleTimeout = attr.getValue();
        if (StringUtils.isNotBlank(sessionIdleTimeout)) {
            try {
                config.builder.getConfiguration().setSessionIdleTimeout(Long.parseLong(sessionIdleTimeout));
                logger.debug("?" + sessionIdleTimeout);
            } catch (Exception e) {
                logger.error("???", e);
            }
        } else {
            logger.error("???");
        }
    } else {
        logger.warn("??");
    }
    //?
    logger.debug("?...");
    attr = el.attribute("statisticsServer");
    if (attr != null) {
        String statisticsServer = attr.getValue();
        if (StringUtils.isNotBlank(statisticsServer)) {
            try {
                config.builder.getConfiguration().setStatisticsServer(Boolean.parseBoolean(statisticsServer));
                logger.debug("?" + statisticsServer);
            } catch (Exception e) {
                logger.error("???", e);
            }
        } else {
            logger.error("???");
        }
    } else {
        logger.warn("??");
    }
    logger.debug("?...");
    attr = el.attribute("statisticsInterval");
    if (attr != null) {
        String statisticsInterval = attr.getValue();
        if (StringUtils.isNotBlank(statisticsInterval)) {
            try {
                config.builder.getConfiguration().setStatisticsInterval(Long.parseLong(statisticsInterval));
                logger.debug("?" + statisticsInterval);
            } catch (Exception e) {
                logger.error("???", e);
            }
        } else {
            logger.error("???");
        }
    } else {
        logger.warn("??");
    }
    logger.debug("????...");
    attr = el.attribute("optimizeMergeBuffer");
    if (attr != null) {
        String optimizeMergeBufferS = attr.getValue();
        if (StringUtils.isNotBlank(optimizeMergeBufferS)) {
            try {
                config.optimizeMergeBuffer = Boolean.parseBoolean(optimizeMergeBufferS);
                logger.debug("????" + optimizeMergeBufferS);
            } catch (Exception e) {
                logger.error("??????", e);
            }
        } else {
            logger.error("??????");
        }
    } else {
        logger.warn("?????");
    }
    logger.debug("??...");
    attr = el.attribute("mergeFactor");
    if (attr != null) {
        String mergeFactorS = attr.getValue();
        if (StringUtils.isNotBlank(mergeFactorS)) {
            try {
                config.mergeFactor = Integer.parseInt(mergeFactorS);
                logger.debug("?" + mergeFactorS);
            } catch (Exception e) {
                logger.error("???", e);
            }
        } else {
            logger.error("???");
        }
    } else {
        logger.warn("??");
    }
    logger.debug("??...");
    attr = el.attribute("commandFactory");
    if (attr != null) {
        String commandFactory = attr.getValue();
        if (StringUtils.isNotBlank(commandFactory)) {
            try {
                config.builder.setCommandFactory((CommandFactory) Class.forName(commandFactory).newInstance());
                logger.debug("??" + commandFactory);
            } catch (Exception e) {
                logger.error("????", e);
            }
        } else {
            logger.error("????");
        }
    } else {
        logger.warn("???");
    }
    config.builder.setCommandFactory(new BinaryCommandFactory());
    logger.debug("...");
    nodeList = doc.selectNodes("/memcached/socketOption/*");
    if (!nodeList.isEmpty()) {
        for (Node n : nodeList) {
            try {
                attr = ((Element) n).attribute("type");
                if (attr == null) {
                    logger.error("type attribute undefined");
                } else {
                    String type = attr.getValue();
                    if (StringUtils.isNotBlank(type)) {
                        String name = n.getName();
                        String value = n.getStringValue();
                        Class valueType = Class.forName(type);
                        Constructor constructor = SocketOption.class.getConstructor(String.class, Class.class);
                        SocketOption socketOption = (SocketOption) constructor.newInstance(name, valueType);
                        constructor = valueType.getConstructor(String.class);
                        config.builder.setSocketOption(socketOption, constructor.newInstance(value));
                        logger.debug("[" + name + "]" + value);
                    }
                }
            } catch (NoSuchMethodException e) {
                logger.error("NoSuchMethodException", e);
            } catch (InvocationTargetException e) {
                logger.error("InvocationTargetException", e);
            } catch (InstantiationException e) {
                logger.error("InstantiationException", e);
            } catch (IllegalAccessException e) {
                logger.error("IllegalAccessException", e);
            } catch (ClassNotFoundException e) {
                logger.error("ClassNotFoundException", e);
            }
        }
    } else {
        logger.warn("?");
    }
    logger.debug("Failure?...");
    attr = el.attribute("failureMode");
    if (attr != null) {
        String failureMode = attr.getValue();
        if (StringUtils.isNotBlank(failureMode)) {
            try {
                config.builder.setFailureMode(Boolean.parseBoolean(failureMode));
                logger.debug("Failure?" + failureMode);
            } catch (Exception e) {
                logger.error("Failure???", e);
            }
        } else {
            logger.error("Failure???");
        }
    } else {
        logger.warn("Failure??");
    }
    return config;
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

public static Object constructNew(Class<?> clazz, Object[] args)
        throws NoSuchMethodException, InstantiationException, IllegalArgumentException, IllegalAccessException {
    if (args.length < 1) {
        return clazz.newInstance();
    } else {/*from w  w  w  .ja v a 2s.  com*/
        Class<?>[] paramTypes = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            paramTypes[i] = args[i].getClass();
        }

        Constructor<?> con = clazz.getConstructor(paramTypes);

        try {
            return con.newInstance(args);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }
}

From source file:lapin.load.Loader.java

static private Subr _toSubr(Symbol name, Class clazz, Env env) throws InstantiationException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (Logger.debuglevelp(env)) {
        Logger.debug("[toSubr] name  : ~S", Lists.list(name), env);
        Logger.debug("[toSubr] class : ~S", Lists.list(clazz), env);
        Logger.debug("[toSubr] loader: ~S", Lists.list(clazz.getClassLoader()), env);
    }/*from  w  ww .j  av a 2 s .co  m*/
    Constructor c = clazz.getConstructor(CONSTRUCTOR_PARAM_TYPES);
    return Data.subr(c.newInstance(new Object[] { env }));
}

From source file:jp.sf.fess.solr.plugin.suggest.util.SolrConfigUtil.java

public static SuggestUpdateConfig getUpdateHandlerConfig(final SolrConfig config) {
    final SuggestUpdateConfig suggestUpdateConfig = new SuggestUpdateConfig();

    final Node solrServerNode = config.getNode("updateHandler/suggest/solrServer", false);
    if (solrServerNode != null) {
        try {/*from w ww .  j av a2 s. com*/
            final Node classNode = solrServerNode.getAttributes().getNamedItem("class");
            String className;
            if (classNode != null) {
                className = classNode.getTextContent();
            } else {
                className = "org.codelibs.solr.lib.server.SolrLibHttpSolrServer";
            }
            @SuppressWarnings("unchecked")
            final Class<? extends SolrServer> clazz = (Class<? extends SolrServer>) Class.forName(className);
            final String arg = config.getVal("updateHandler/suggest/solrServer/arg", false);
            SolrServer solrServer;
            if (StringUtils.isNotBlank(arg)) {
                final Constructor<? extends SolrServer> constructor = clazz.getConstructor(String.class);
                solrServer = constructor.newInstance(arg);
            } else {
                solrServer = clazz.newInstance();
            }

            final String username = config.getVal("updateHandler/suggest/solrServer/credentials/username",
                    false);
            final String password = config.getVal("updateHandler/suggest/solrServer/credentials/password",
                    false);
            if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)
                    && solrServer instanceof SolrLibHttpSolrServer) {
                final SolrLibHttpSolrServer solrLibHttpSolrServer = (SolrLibHttpSolrServer) solrServer;
                final URL u = new URL(arg);
                final AuthScope authScope = new AuthScope(u.getHost(), u.getPort());
                final Credentials credentials = new UsernamePasswordCredentials(username, password);
                solrLibHttpSolrServer.setCredentials(authScope, credentials);
                solrLibHttpSolrServer.addRequestInterceptor(new PreemptiveAuthInterceptor());
            }

            final NodeList childNodes = solrServerNode.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                final Node node = childNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    final String name = node.getNodeName();
                    if (!"arg".equals(name) && !"credentials".equals(name)) {
                        final String value = node.getTextContent();
                        final Node typeNode = node.getAttributes().getNamedItem("type");
                        final Method method = clazz.getMethod(
                                "set" + name.substring(0, 1).toUpperCase() + name.substring(1),
                                getMethodArgClass(typeNode));
                        method.invoke(solrServer, getMethodArgValue(typeNode, value));
                    }
                }
            }
            if (solrServer instanceof SolrLibHttpSolrServer) {
                ((SolrLibHttpSolrServer) solrServer).init();
            }
            suggestUpdateConfig.setSolrServer(solrServer);
        } catch (final Exception e) {
            throw new FessSuggestException("Failed to load SolrServer.", e);
        }
    }

    final String labelFields = config.getVal("updateHandler/suggest/labelFields", false);
    if (StringUtils.isNotBlank(labelFields)) {
        suggestUpdateConfig.setLabelFields(labelFields.trim().split(","));
    }
    final String roleFields = config.getVal("updateHandler/suggest/roleFields", false);
    if (StringUtils.isNotBlank(roleFields)) {
        suggestUpdateConfig.setRoleFields(roleFields.trim().split(","));
    }

    final String expiresField = config.getVal("updateHandler/suggest/expiresField", false);
    if (StringUtils.isNotBlank(expiresField)) {
        suggestUpdateConfig.setExpiresField(expiresField);
    }
    final String segmentField = config.getVal("updateHandler/suggest/segmentField", false);
    if (StringUtils.isNotBlank(segmentField)) {
        suggestUpdateConfig.setSegmentField(segmentField);
    }
    final String updateInterval = config.getVal("updateHandler/suggest/updateInterval", false);
    if (StringUtils.isNotBlank(updateInterval) && StringUtils.isNumeric(updateInterval)) {
        suggestUpdateConfig.setUpdateInterval(Long.parseLong(updateInterval));
    }

    //set suggestFieldInfo
    final NodeList nodeList = config.getNodeList("updateHandler/suggest/suggestFieldInfo", true);
    for (int i = 0; i < nodeList.getLength(); i++) {
        try {
            final SuggestUpdateConfig.FieldConfig fieldConfig = new SuggestUpdateConfig.FieldConfig();
            final Node fieldInfoNode = nodeList.item(i);
            final NamedNodeMap fieldInfoAttributes = fieldInfoNode.getAttributes();
            final Node fieldNameNode = fieldInfoAttributes.getNamedItem("fieldName");
            final String fieldName = fieldNameNode.getNodeValue();
            if (StringUtils.isBlank(fieldName)) {
                continue;
            }
            fieldConfig.setTargetFields(fieldName.trim().split(","));
            if (logger.isInfoEnabled()) {
                for (final String s : fieldConfig.getTargetFields()) {
                    logger.info("fieldName : " + s);
                }
            }

            final NodeList fieldInfoChilds = fieldInfoNode.getChildNodes();
            for (int j = 0; j < fieldInfoChilds.getLength(); j++) {
                final Node fieldInfoChildNode = fieldInfoChilds.item(j);
                final String fieldInfoChildNodeName = fieldInfoChildNode.getNodeName();

                if ("tokenizerFactory".equals(fieldInfoChildNodeName)) {
                    //field tokenier settings
                    final SuggestUpdateConfig.TokenizerConfig tokenizerConfig = new SuggestUpdateConfig.TokenizerConfig();

                    final NamedNodeMap tokenizerFactoryAttributes = fieldInfoChildNode.getAttributes();
                    final Node tokenizerClassNameNode = tokenizerFactoryAttributes.getNamedItem("class");
                    final String tokenizerClassName = tokenizerClassNameNode.getNodeValue();
                    tokenizerConfig.setClassName(tokenizerClassName);
                    if (logger.isInfoEnabled()) {
                        logger.info("tokenizerFactory : " + tokenizerClassName);
                    }

                    final Map<String, String> args = new HashMap<String, String>();
                    for (int k = 0; k < tokenizerFactoryAttributes.getLength(); k++) {
                        final Node attribute = tokenizerFactoryAttributes.item(k);
                        final String key = attribute.getNodeName();
                        final String value = attribute.getNodeValue();
                        if (!"class".equals(key)) {
                            args.put(key, value);
                        }
                    }
                    if (!args.containsKey(USER_DICT_PATH)) {
                        final String userDictPath = System.getProperty(SuggestConstants.USER_DICT_PATH, "");
                        if (StringUtils.isNotBlank(userDictPath)) {
                            args.put(USER_DICT_PATH, userDictPath);
                        }
                        final String userDictEncoding = System.getProperty(SuggestConstants.USER_DICT_ENCODING,
                                "");
                        if (StringUtils.isNotBlank(userDictEncoding)) {
                            args.put(USER_DICT_ENCODING, userDictEncoding);
                        }
                    }
                    tokenizerConfig.setArgs(args);

                    fieldConfig.setTokenizerConfig(tokenizerConfig);
                } else if ("suggestReadingConverter".equals(fieldInfoChildNodeName)) {
                    //field reading converter settings
                    final NodeList converterNodeList = fieldInfoChildNode.getChildNodes();
                    for (int k = 0; k < converterNodeList.getLength(); k++) {
                        final SuggestUpdateConfig.ConverterConfig converterConfig = new SuggestUpdateConfig.ConverterConfig();

                        final Node converterNode = converterNodeList.item(k);
                        if (!"converter".equals(converterNode.getNodeName())) {
                            continue;
                        }

                        final NamedNodeMap converterAttributes = converterNode.getAttributes();
                        final Node classNameNode = converterAttributes.getNamedItem("class");
                        final String className = classNameNode.getNodeValue();
                        converterConfig.setClassName(className);
                        if (logger.isInfoEnabled()) {
                            logger.info("converter : " + className);
                        }

                        final Map<String, String> properties = new HashMap<String, String>();
                        for (int l = 0; l < converterAttributes.getLength(); l++) {
                            final Node attribute = converterAttributes.item(l);
                            final String key = attribute.getNodeName();
                            final String value = attribute.getNodeValue();
                            if (!"class".equals(key)) {
                                properties.put(key, value);
                            }
                        }
                        converterConfig.setProperties(properties);
                        if (logger.isInfoEnabled()) {
                            logger.info("converter properties = " + properties);
                        }
                        fieldConfig.addConverterConfig(converterConfig);
                    }
                } else if ("suggestNormalizer".equals(fieldInfoChildNodeName)) {
                    //field normalizer settings
                    final NodeList normalizerNodeList = fieldInfoChildNode.getChildNodes();
                    for (int k = 0; k < normalizerNodeList.getLength(); k++) {
                        final SuggestUpdateConfig.NormalizerConfig normalizerConfig = new SuggestUpdateConfig.NormalizerConfig();

                        final Node normalizerNode = normalizerNodeList.item(k);
                        if (!"normalizer".equals(normalizerNode.getNodeName())) {
                            continue;
                        }

                        final NamedNodeMap normalizerAttributes = normalizerNode.getAttributes();
                        final Node classNameNode = normalizerAttributes.getNamedItem("class");
                        final String className = classNameNode.getNodeValue();
                        normalizerConfig.setClassName(className);
                        if (logger.isInfoEnabled()) {
                            logger.info("normalizer : " + className);
                        }

                        final Map<String, String> properties = new HashMap<String, String>();
                        for (int l = 0; l < normalizerAttributes.getLength(); l++) {
                            final Node attribute = normalizerAttributes.item(l);
                            final String key = attribute.getNodeName();
                            final String value = attribute.getNodeValue();
                            if (!"class".equals(key)) {
                                properties.put(key, value);
                            }
                        }
                        normalizerConfig.setProperties(properties);
                        if (logger.isInfoEnabled()) {
                            logger.info("normalize properties = " + properties);
                        }
                        fieldConfig.addNormalizerConfig(normalizerConfig);
                    }
                }
            }

            suggestUpdateConfig.addFieldConfig(fieldConfig);
        } catch (final Exception e) {
            throw new FessSuggestException("Failed to load Suggest Field Info.", e);
        }
    }

    return suggestUpdateConfig;
}

From source file:net.authorize.api.controller.test.ApiCoreTestBase.java

@SuppressWarnings("unchecked")
private static <Q extends ANetApiRequest, S extends ANetApiResponse, T extends ApiOperationBase<Q, S>> S executeTestRequest(
        boolean successExpected, Q request, Class<T> controllerClass, Environment execEnvironment) {
    LogHelper.debug(logger, "Created %s Request: '%s'", request.getClass(), request);

    S response = null;/*from w  w  w  . j  a v a 2  s . c  o  m*/
    T controller = null;
    errorResponse = null;
    try {
        Class<?>[] parameterTypes = new Class<?>[] { request.getClass() };
        Constructor<T> constructor = controllerClass.getConstructor(parameterTypes);
        Object controllerObject = constructor.newInstance(request);
        controller = (T) controllerObject;
        ANetApiResponse baseResponse = controller.executeWithApiResponse(execEnvironment);
        LogHelper.info(logger, "%s ResultCode: %s", controllerClass, controller.getResultCode());
        LogHelper.info(logger, "%s Results:    %s", controllerClass, controller.getResults());
        response = (S) baseResponse;

    } catch (Exception e) {
        LogHelper.error(logger, "Exception : '%s' during %s", e.getMessage(), controllerClass);
    }
    if (successExpected) {
        processFailureResult(true, controller, response);
        validateSuccess(controller, response);
    } else {
        validateFailure(controller, response);
    }
    if (null == response && null != controller && null != controller.getErrorResponse()) {
        errorResponse = controller.getErrorResponse();
    }

    return response;
}

From source file:com.all.shared.json.JsonConverter.java

@SuppressWarnings("unchecked")
public static <T> T toBean(String json, Class<T> clazz) {
    if (json.isEmpty()) {
        return null;
    }//w w  w  .ja v  a  2  s  .co  m
    if (json.contains(BUGGY_QUOTES)) {
        log.warn("Json contains buggy quotes, will replace them.");
        json = json.replaceAll(BUGGY_QUOTES, FIXED_QUOTES);
    }
    JsonReader<T> jsonReader = (JsonReader<T>) JSON_READERS.get(clazz);
    if (jsonReader != null) {
        return (T) jsonReader.read(json);
    }
    if (PRIMITIVES.contains(clazz)) {
        try {
            return clazz.getConstructor(String.class).newInstance(json);
        } catch (Exception e) {
            String message = "Could not convert string '" + json + "' to primtive type " + clazz;
            log.warn(message);
            throw new IllegalArgumentException(message, e);
        }
    }
    JSONObject jsonObject = JSONObject.fromObject(json);
    try {
        return (T) JSONObject.toBean(jsonObject, clazz);
    } catch (Exception e) {
        log.warn("Could not convert json to bean of class " + clazz.getName() + " directly.");
        return cleanAndConvert(jsonObject, clazz);
    }
}

From source file:com.appleframework.jmx.core.services.MBeanServiceImpl.java

public static Object getTypedValue(ApplicationConfig appConfig, String value, String type) {

    if (type.equals("int")) {
        type = "java.lang.Integer";
    } else if (type.equals("long")) {
        type = "java.lang.Long";
    } else if (type.equals("short")) {
        type = "java.lang.Short";
    } else if (type.equals("float")) {
        type = "java.lang.Float";
    } else if (type.equals("double")) {
        type = "java.lang.Double";
    } else if (type.equals("char")) {
        type = "java.lang.Character";
    } else if (type.equals("boolean")) {
        type = "java.lang.Boolean";
    } else if (type.equals("byte")) {
        type = "java.lang.Byte";
    }//from  w w w .  j a v a  2  s . c  o  m

    try {
        /* handle ObjectName as a special type */
        if (type.equals("javax.management.ObjectName")) {
            Class<?> clazz = Class.forName(type, true, appConfig.getApplicationClassLoader());
            try {
                Constructor<?> ctor = clazz.getConstructor(new Class[] { String.class });
                return ctor.newInstance(new Object[] { value });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        /* other types */
        return ConvertUtils.convert(value, Class.forName(type));
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.enioka.jqm.tools.Helpers.java

/**
 * Send a mail message using a JNDI resource.<br>
 * As JNDI resource providers are inside the EXT class loader, this uses reflection. This method is basically a bonus on top of the
 * MailSessionFactory offered to payloads, making it accessible also to the engine.
 * //from www . j  a va2s .  com
 * @param to
 * @param subject
 * @param body
 * @param mailSessionJndiAlias
 * @throws MessagingException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
static void sendMessage(String to, String subject, String body, String mailSessionJndiAlias)
        throws MessagingException {
    jqmlogger.debug("sending mail to " + to + " - subject is " + subject);
    ClassLoader extLoader = getExtClassLoader();
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Object mailSession = null;

    try {
        mailSession = InitialContext.doLookup(mailSessionJndiAlias);
    } catch (NamingException e) {
        throw new MessagingException("could not find mail session description", e);
    }

    try {
        Thread.currentThread().setContextClassLoader(extLoader);
        Class transportZ = extLoader.loadClass("javax.mail.Transport");
        Class sessionZ = extLoader.loadClass("javax.mail.Session");
        Class mimeMessageZ = extLoader.loadClass("javax.mail.internet.MimeMessage");
        Class messageZ = extLoader.loadClass("javax.mail.Message");
        Class recipientTypeZ = extLoader.loadClass("javax.mail.Message$RecipientType");
        Object msg = mimeMessageZ.getConstructor(sessionZ).newInstance(mailSession);

        mimeMessageZ.getMethod("setRecipients", recipientTypeZ, String.class).invoke(msg,
                recipientTypeZ.getField("TO").get(null), to);
        mimeMessageZ.getMethod("setSubject", String.class).invoke(msg, subject);
        mimeMessageZ.getMethod("setText", String.class).invoke(msg, body);

        transportZ.getMethod("send", messageZ).invoke(null, msg);
        jqmlogger.trace("Mail was sent");
    } catch (Exception e) {
        throw new MessagingException("an exception occurred during mail sending", e);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields,
        Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth,
        SerializationType serializationType) throws Exception {

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;/*from   ww w  .  j a  v a 2s. co  m*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (!replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof org.hibernate.collection.PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((org.hibernate.collection.PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("com.ppp")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}