Search in sources :

Example 56 with Constructor

use of java.lang.reflect.Constructor in project opennms by OpenNMS.

the class DataSourceFactory method parseDataSource.

private static ClosableDataSource parseDataSource(final String dsName) {
    String factoryClass = null;
    ConnectionPool connectionPool = m_dataSourceConfigFactory.getConnectionPool();
    factoryClass = connectionPool.getFactory();
    ClosableDataSource dataSource = null;
    final String defaultClassName = DEFAULT_FACTORY_CLASS.getName();
    try {
        final Class<?> clazz = Class.forName(factoryClass);
        final Constructor<?> constructor = clazz.getConstructor(new Class<?>[] { JdbcDataSource.class });
        dataSource = (ClosableDataSource) constructor.newInstance(new Object[] { m_dataSourceConfigFactory.getJdbcDataSource(dsName) });
    } catch (final Throwable t) {
        LOG.debug("Unable to load {}, falling back to the default dataSource ({})", factoryClass, defaultClassName, t);
        try {
            final Constructor<?> constructor = ((Class<?>) DEFAULT_FACTORY_CLASS).getConstructor(new Class<?>[] { JdbcDataSource.class });
            dataSource = (ClosableDataSource) constructor.newInstance(new Object[] { m_dataSourceConfigFactory.getJdbcDataSource(dsName) });
        } catch (final Throwable cause) {
            LOG.error("Unable to load {}.", DEFAULT_FACTORY_CLASS.getName(), cause);
            throw new IllegalArgumentException("Unable to load " + defaultClassName + ".", cause);
        }
    }
    if (connectionPool != null) {
        dataSource.setIdleTimeout(connectionPool.getIdleTimeout());
        try {
            dataSource.setLoginTimeout(connectionPool.getLoginTimeout());
        } catch (SQLException e) {
            LOG.warn("Exception thrown while trying to set login timeout on datasource", e);
        }
        dataSource.setMinPool(connectionPool.getMinPool());
        dataSource.setMaxPool(connectionPool.getMaxPool());
        dataSource.setMaxSize(connectionPool.getMaxSize());
    }
    return dataSource;
}
Also used : ConnectionPool(org.opennms.netmgt.config.opennmsDataSources.ConnectionPool) SQLException(java.sql.SQLException) Constructor(java.lang.reflect.Constructor) JdbcDataSource(org.opennms.netmgt.config.opennmsDataSources.JdbcDataSource)

Example 57 with Constructor

use of java.lang.reflect.Constructor in project OpenAM by OpenRock.

the class LoginContext method invoke.

/**
     * Attempts to invoke the method described by methodName against each module within the stack.
     *
     * @param methodName
     *         String method name to be invoked on each module.
     * @throws LoginException
     *         Throw in the case of some login failure.
     */
private void invoke(String methodName) throws LoginException {
    for (int i = 0; i < moduleStack.length; i++) {
        ModuleInfo info = moduleStack[i];
        LoginModuleControlFlag controlFlag = info.entry.getControlFlag();
        AuditRequestContext.putProperty(LOGIN_MODULE_CONTROL_FLAG, getControlFlagAsString(controlFlag));
        try {
            int mIndex = 0;
            Method[] methods = null;
            if (info.module != null) {
                methods = info.module.getClass().getMethods();
            } else {
                // instantiate the LoginModule
                Class c = Class.forName(info.entry.getLoginModuleName(), true, Thread.currentThread().getContextClassLoader());
                Constructor constructor = c.getConstructor(PARAMS);
                Object[] args = {};
                // allow any object to be a LoginModule
                // as long as it conforms to the interface
                info.module = constructor.newInstance(args);
                methods = info.module.getClass().getMethods();
                // call the LoginModule's initialize method
                for (mIndex = 0; mIndex < methods.length; mIndex++) {
                    if (methods[mIndex].getName().equals(INIT_METHOD))
                        break;
                }
                // Invoke the LoginModule initialize method
                Object[] initArgs = { subject, callbackHandler, state, info.entry.getOptions() };
                methods[mIndex].invoke(info.module, initArgs);
            }
            // find the requested method in the LoginModule
            for (mIndex = 0; mIndex < methods.length; mIndex++) {
                if (methods[mIndex].getName().equals(methodName))
                    break;
            }
            // set up the arguments to be passed to the LoginModule method
            Object[] args = {};
            // invoke the LoginModule method
            boolean status = (Boolean) methods[mIndex].invoke(info.module, args);
            if (status) {
                // if SUFFICIENT, return if no prior REQUIRED errors
                if (!requiredExceptionHolder.hasException() && controlFlag == LoginModuleControlFlag.SUFFICIENT && (methodName.equals(LOGIN_METHOD) || methodName.equals(COMMIT_METHOD))) {
                    if (debug.messageEnabled()) {
                        debug.message(methodName + " SUFFICIENT success");
                    }
                    return;
                }
                if (debug.messageEnabled()) {
                    debug.message(methodName + " success");
                }
                success = true;
            } else {
                if (debug.messageEnabled()) {
                    debug.message(methodName + " ignored");
                }
            }
        } catch (NoSuchMethodException nsme) {
            throw new LoginException("unable to instantiate LoginModule, module, because it does " + "not provide a no-argument constructor:" + info.entry.getLoginModuleName());
        } catch (InstantiationException ie) {
            throw new LoginException("unable to instantiate LoginModule: " + ie.getMessage());
        } catch (ClassNotFoundException cnfe) {
            throw new LoginException("unable to find LoginModule class: " + cnfe.getMessage());
        } catch (IllegalAccessException iae) {
            throw new LoginException("unable to access LoginModule: " + iae.getMessage());
        } catch (InvocationTargetException ite) {
            if (ite.getTargetException() instanceof Error) {
                if (debug.messageEnabled()) {
                    debug.message("LoginContext.invoke(): Handling expected java.lang.Error");
                }
                throw (Error) ite.getTargetException();
            }
            // failure cases
            LoginException le = null;
            if (ite.getTargetException() instanceof LoginException) {
                le = (LoginException) ite.getTargetException();
            } else if (ite.getTargetException() instanceof SecurityException) {
                // do not want privacy leak
                // (e.g., sensitive file path in exception msg)
                le = new LoginException("Security Exception");
                // le.initCause(new SecurityException());
                if (debug.messageEnabled()) {
                    debug.message("original security exception with detail msg " + "replaced by new exception with empty detail msg");
                    debug.message("original security exception: " + ite.getTargetException().toString());
                }
            } else {
                // capture an unexpected LoginModule exception
                StringWriter sw = new StringWriter();
                ite.getTargetException().printStackTrace(new PrintWriter(sw));
                sw.flush();
                le = new LoginException(sw.toString());
            }
            if (debug.messageEnabled()) {
                debug.message(String.format("Method %s %s failure.", methodName, controlFlag));
            }
            if (controlFlag == LoginModuleControlFlag.OPTIONAL || controlFlag == LoginModuleControlFlag.SUFFICIENT) {
                // mark down that an OPTIONAL module failed
                optionalExceptionHolder.setException(le);
            } else {
                requiredExceptionHolder.setException(le);
                if (controlFlag == LoginModuleControlFlag.REQUISITE && (methodName.equals(LOGIN_METHOD) || methodName.equals(COMMIT_METHOD))) {
                    // if REQUISITE, then immediately throw an exception
                    throw requiredExceptionHolder.getException();
                }
            }
        } finally {
            AuditRequestContext.removeProperty(LOGIN_MODULE_CONTROL_FLAG);
        }
    }
    if (requiredExceptionHolder.hasException()) {
        // a REQUIRED module failed -- return the error
        throw requiredExceptionHolder.getException();
    } else if (success == false && optionalExceptionHolder.hasException()) {
        // no module succeeded -- return the first optional error
        throw optionalExceptionHolder.getException();
    } else if (success == false) {
        // no module succeeded -- all modules were IGNORED
        throw new LoginException("Login Failure: all modules ignored");
    }
}
Also used : Constructor(java.lang.reflect.Constructor) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) StringWriter(java.io.StringWriter) LoginModuleControlFlag(javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag) PrintWriter(java.io.PrintWriter)

Example 58 with Constructor

use of java.lang.reflect.Constructor in project android_frameworks_base by DirtyUnicorns.

the class TransitionInflater method createCustom.

private Object createCustom(AttributeSet attrs, Class expectedType, String tag) {
    String className = attrs.getAttributeValue(null, "class");
    if (className == null) {
        throw new InflateException(tag + " tag must have a 'class' attribute");
    }
    try {
        synchronized (sConstructors) {
            Constructor constructor = sConstructors.get(className);
            if (constructor == null) {
                Class c = mContext.getClassLoader().loadClass(className).asSubclass(expectedType);
                if (c != null) {
                    constructor = c.getConstructor(sConstructorSignature);
                    constructor.setAccessible(true);
                    sConstructors.put(className, constructor);
                }
            }
            return constructor.newInstance(mContext, attrs);
        }
    } catch (InstantiationException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    } catch (ClassNotFoundException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    } catch (InvocationTargetException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    } catch (NoSuchMethodException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    } catch (IllegalAccessException e) {
        throw new InflateException("Could not instantiate " + expectedType + " class " + className, e);
    }
}
Also used : Constructor(java.lang.reflect.Constructor) InflateException(android.view.InflateException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 59 with Constructor

use of java.lang.reflect.Constructor in project weex-example by KalicyZhou.

the class PlayDebugAdapter method wrapContainer.

@Override
public View wrapContainer(WXSDKInstance instance, View wxView) {
    try {
        Class scalpelClas = Class.forName("com.taobao.weex.scalpel.ScalpelFrameLayout");
        Constructor constructor = scalpelClas.getConstructor(new Class[] { Context.class });
        ViewGroup container = (ViewGroup) constructor.newInstance(wxView.getContext());
        if (container != null) {
            container.addView(wxView);
            Class cls = Class.forName("com.taobao.weex.WXDebugTool");
            Method m = cls.getMethod("updateScapleView", new Class[] { Object.class });
            m.invoke(null, new Object[] { container });
            instance.registerActivityStateListener(new DebugActivityState(wxView));
            return container;
        }
    } catch (Exception e) {
    }
    return wxView;
}
Also used : Constructor(java.lang.reflect.Constructor) ViewGroup(android.view.ViewGroup) Method(java.lang.reflect.Method)

Example 60 with Constructor

use of java.lang.reflect.Constructor in project jdk8u_jdk by JetBrains.

the class Main method launch.

private static void launch(URL[] urls, final String className, final String methodName) {
    final String uniqClassName = "testapp/Uniq" + counter;
    final boolean saveStrongRef = forgetSomeStreams ? (counter % 5 == 4) : false;
    System.out.printf("%s: launch the app\n", uniqClassName);
    Runnable launchIt = new Runnable() {

        public void run() {
            AppContext ctx = SunToolkit.createNewAppContext();
            try {
                Class appMain = ctx.getContextClassLoader().loadClass(className);
                Method launch = appMain.getDeclaredMethod(methodName, strongRefs.getClass());
                Constructor c = appMain.getConstructor(String.class, problems.getClass());
                Object o = c.newInstance(uniqClassName, problems);
                if (saveStrongRef) {
                    System.out.printf("%s: force strong ref\n", uniqClassName);
                    launch.invoke(o, strongRefs);
                } else {
                    HashMap<String, ImageInputStream> empty = null;
                    launch.invoke(o, empty);
                }
                ctx = null;
            } catch (Throwable e) {
                problems.add(e);
            } finally {
                doneSignal.countDown();
            }
        }
    };
    MyClassLoader appClassLoader = new MyClassLoader(urls, uniqClassName);
    refs.put(appClassLoader, uniqClassName);
    Thread appThread = new Thread(appsThreadGroup, launchIt, "AppThread" + counter++);
    appThread.setContextClassLoader(appClassLoader);
    appThread.start();
    launchIt = null;
    appThread = null;
    appClassLoader = null;
}
Also used : Constructor(java.lang.reflect.Constructor) AppContext(sun.awt.AppContext) ImageInputStream(javax.imageio.stream.ImageInputStream) Method(java.lang.reflect.Method)

Aggregations

Constructor (java.lang.reflect.Constructor)1314 InvocationTargetException (java.lang.reflect.InvocationTargetException)283 Method (java.lang.reflect.Method)253 IOException (java.io.IOException)128 Field (java.lang.reflect.Field)112 ArrayList (java.util.ArrayList)106 Test (org.junit.Test)92 DOMTestDocumentBuilderFactory (org.w3c.domts.DOMTestDocumentBuilderFactory)74 JUnitTestSuiteAdapter (org.w3c.domts.JUnitTestSuiteAdapter)73 List (java.util.List)61 JAXPDOMTestDocumentBuilderFactory (org.w3c.domts.JAXPDOMTestDocumentBuilderFactory)58 Map (java.util.Map)50 Type (java.lang.reflect.Type)39 Annotation (java.lang.annotation.Annotation)38 HashMap (java.util.HashMap)38 HashSet (java.util.HashSet)31 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)31 ParameterizedType (java.lang.reflect.ParameterizedType)30 File (java.io.File)20 URL (java.net.URL)20