Example usage for java.lang Class getDeclaredMethod

List of usage examples for java.lang Class getDeclaredMethod

Introduction

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

Prototype

@CallerSensitive
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

Usage

From source file:com.gh.bmd.jrt.android.v4.core.DefaultObjectContextRoutineBuilder.java

@Nonnull
public <INPUT, OUTPUT> Routine<INPUT, OUTPUT> method(@Nonnull final String name,
        @Nonnull final Class<?>... parameterTypes) {

    Method targetMethod;/* w w w.j  a va  2s  . c  om*/
    final Class<?> targetClass = mTargetClass;

    try {

        targetMethod = targetClass.getMethod(name, parameterTypes);

    } catch (final NoSuchMethodException ignored) {

        try {

            targetMethod = targetClass.getDeclaredMethod(name, parameterTypes);

        } catch (final NoSuchMethodException e) {

            throw new IllegalArgumentException(e);
        }
    }

    final RoutineConfiguration configuration = mConfiguration;

    if (configuration != null) {

        warn(configuration);
    }

    final MethodSignatureToken<INPUT, OUTPUT> classToken = new MethodSignatureToken<INPUT, OUTPUT>();
    final Object[] args = mArgs;
    final String shareGroup = withShareAnnotation(mShareGroup, targetMethod);
    final RoutineConfiguration routineConfiguration = withTimeoutAnnotation(configuration, targetMethod)
            .withInputOrder(OrderType.PASSING_ORDER).buildConfiguration();
    final int invocationId = withIdAnnotation(mInvocationId, targetMethod);
    final ClashResolutionType resolutionType = withClashAnnotation(mClashResolutionType, targetMethod);
    final CacheStrategyType strategyType = withCacheAnnotation(mCacheStrategyType, targetMethod);
    return getBuilder(mContext, classToken)
            .withArgs(targetClass.getName(), args, shareGroup, name, toNames(parameterTypes))
            .withConfiguration(routineConfiguration).withId(invocationId).onClash(resolutionType)
            .onComplete(strategyType).buildRoutine();
}

From source file:org.mwc.debrief.editable.test.EditableTests.java

private Editable getEditable(IType type) {
    Editable editable = null;// w w  w.  j a  v  a2  s. c om
    switch (type.getFullyQualifiedName()) {
    case "Debrief.Wrappers.SensorWrapper":
        SensorWrapper sensor = new SensorWrapper("tester");
        final java.util.Calendar cal = new java.util.GregorianCalendar(2001, 10, 4, 4, 4, 0);

        // and create the list of sensor contact data items
        cal.set(2001, 10, 4, 4, 4, 0);
        sensor.add(new SensorContactWrapper("tester", new HiResDate(cal.getTime().getTime()), null, null, null,
                null, null, 1, sensor.getName()));

        cal.set(2001, 10, 4, 4, 4, 23);
        sensor.add(new SensorContactWrapper("tester", new HiResDate(cal.getTime().getTime()), null, null, null,
                null, null, 1, sensor.getName()));
        editable = sensor;
        break;
    case "MWC.GUI.Shapes.ChartFolio":
        editable = new ChartFolio(false, Color.white);
        break;
    case "org.mwc.cmap.naturalearth.wrapper.NELayer":
        editable = new NELayer(Activator.getDefault().getDefaultStyleSet());
        break;
    case "MWC.GUI.VPF.CoverageLayer$ReferenceCoverageLayer":
        final LibrarySelectionTable LST = null;
        final DebriefFeatureWarehouse myWarehouse = new DebriefFeatureWarehouse();
        final FeaturePainter fp = new FeaturePainter("libref", "Coastline");
        fp.setVisible(true);
        editable = new CoverageLayer.ReferenceCoverageLayer(LST, myWarehouse, "libref", "libref", "Coastline",
                fp);
        break;
    case "MWC.GUI.Chart.Painters.ETOPOPainter":
        editable = new ETOPOPainter("etopo", null);
        break;
    case "MWC.GUI.ETOPO.ETOPO_2_Minute":
        editable = new ETOPO_2_Minute("etopo");
        break;
    case "MWC.GUI.ExternallyManagedDataLayer":
        editable = new ExternallyManagedDataLayer("test", "test", "test");
        break;
    case "MWC.GUI.Shapes.CircleShape":
        editable = new CircleShape(new WorldLocation(2d, 2d, 2d), 2d);
        break;
    case "Debrief.Wrappers.Track.SplittableLayer":
        editable = new SplittableLayer(true);
        break;
    case "org.mwc.debrief.satc_interface.data.SATC_Solution":
        final ISolversManager solvMgr = SATC_Activator.getDefault().getService(ISolversManager.class, true);
        final ISolver newSolution = solvMgr.createSolver("test");
        editable = new SATC_Solution(newSolution);
        break;
    case "MWC.GUI.Shapes.PolygonShape":
        editable = new PolygonShape(null);
        break;
    case "ASSET.GUI.Painters.NoiseSourcePainter":
        editable = new ASSET.GUI.Painters.NoiseSourcePainter.PainterTest().getEditable();
        break;
    case "ASSET.GUI.Painters.ScenarioNoiseLevelPainter":
        editable = new ASSET.GUI.Painters.ScenarioNoiseLevelPainter.NoiseLevelTest().getEditable();
        break;
    case "ASSET.GUI.Workbench.Plotters.ScenarioParticipantWrapper":
        editable = new ScenarioParticipantWrapper(new SSN(12), null);
        break;
    case "Debrief.Wrappers.PolygonWrapper":
        // get centre of area
        WorldLocation centre = new WorldLocation(12, 12, 12);
        // create the shape, based on the centre
        final Vector<PolygonNode> path2 = new Vector<PolygonNode>();
        final PolygonShape newShape = new PolygonShape(path2);
        // and now wrap the shape
        final PolygonWrapper theWrapper = new PolygonWrapper("New Polygon", newShape, PlainShape.DEFAULT_COLOR,
                null);
        // store the new point
        newShape.add(new PolygonNode("1", centre, (PolygonShape) theWrapper.getShape()));
        editable = theWrapper;
        break;
    case "Debrief.Wrappers.Track.AbsoluteTMASegment":
        WorldSpeed speed = new WorldSpeed(5, WorldSpeed.Kts);
        double course = 33;
        WorldLocation origin = new WorldLocation(12, 12, 12);
        HiResDate startTime = new HiResDate(11 * 60 * 1000);
        HiResDate endTime = new HiResDate(17 * 60 * 1000);
        editable = new AbsoluteTMASegment(course, speed, origin, startTime, endTime);
        break;
    case "Debrief.Wrappers.Track.RelativeTMASegment":
        speed = new WorldSpeed(5, WorldSpeed.Kts);
        course = 33;
        final WorldVector offset = new WorldVector(12, 12, 0);
        editable = new RelativeTMASegment(course, speed, offset, null);
        break;
    case "Debrief.Wrappers.Track.PlanningSegment":
        speed = new WorldSpeed(5, WorldSpeed.Kts);
        course = 33;
        final WorldDistance worldDistance = new WorldDistance(5, WorldDistance.MINUTES);
        editable = new PlanningSegment("test", course, speed, worldDistance, Color.WHITE);
        break;
    case "org.mwc.debrief.satc_interface.data.wrappers.BMC_Wrapper":
        BearingMeasurementContribution bmc = new BearingMeasurementContribution();
        bmc.setName("Measured bearing");
        bmc.setAutoDetect(false);
        editable = new BMC_Wrapper(bmc);
        break;
    case "org.mwc.debrief.satc_interface.data.wrappers.FMC_Wrapper":
        FrequencyMeasurementContribution fmc = new FrequencyMeasurementContribution();
        fmc.setName("Measured frequence");
        editable = new FMC_Wrapper(fmc);
        break;
    case "Debrief.Wrappers.SensorContactWrapper":
        origin = new WorldLocation(0, 0, 0);
        editable = new SensorContactWrapper("blank track", new HiResDate(new java.util.Date().getTime()),
                new WorldDistance(1, WorldDistance.DEGS), 55d, origin, java.awt.Color.red, "my label", 1,
                "theSensorName");
        break;
    case "Debrief.Wrappers.FixWrapper":
        final Fix fx = new Fix(new HiResDate(12, 0), new WorldLocation(2d, 2d, 2d), 2d, 2d);
        final TrackWrapper tw = new TrackWrapper();
        tw.setName("here ew arw");
        FixWrapper ed = new FixWrapper(fx);
        ed.setTrackWrapper(tw);
        editable = ed;
        break;
    case "Debrief.Wrappers.ShapeWrapper":
        centre = new WorldLocation(2d, 2d, 2d);
        editable = new ShapeWrapper("new ellipse", new EllipseShape(centre, 0,
                new WorldDistance(0, WorldDistance.DEGS), new WorldDistance(0, WorldDistance.DEGS)),
                java.awt.Color.red, null);
        break;
    case "Debrief.GUI.Tote.Painters.PainterManager":
        final StepControl stepper = new Debrief.GUI.Tote.Swing.SwingStepControl(null, null, null, null, null,
                null);
        editable = new PainterManager(stepper);
        break;
    case "Debrief.Wrappers.TMAContactWrapper":
        origin = new WorldLocation(2, 2, 0);
        final HiResDate theDTG = new HiResDate(new java.util.Date().getTime());
        final EllipseShape theEllipse = new EllipseShape(origin, 45, new WorldDistance(10, WorldDistance.DEGS),
                new WorldDistance(5, WorldDistance.DEGS));
        theEllipse.setName("test ellipse");
        editable = new TMAContactWrapper("blank sensor", "blank track", theDTG, origin, 5d, 6d, 1d, Color.pink,
                "my label", theEllipse, "some symbol");
        break;
    case "MWC.GUI.JFreeChart.NewFormattedJFreeChart":
        XYPlot plot = new XYPlot();
        DefaultXYItemRenderer renderer = new DefaultXYItemRenderer();
        plot.setRenderer(renderer);
        editable = new NewFormattedJFreeChart("test", new java.awt.Font("Dialog", 0, 18), plot, false);
        break;
    case "org.mwc.cmap.core.ui_support.swt.SWTCanvasAdapter":
        final Editable[] edit = new Editable[1];
        Display.getDefault().syncExec(new Runnable() {

            @Override
            public void run() {
                edit[0] = new SWTCanvasAdapter(null);
            }
        });
        editable = edit[0];
        break;
    case "ASSET.Models.Decision.Conditions.OrCondition":
        System.out.println(type.getFullyQualifiedName() + " hasn't public constructor.");
        return null;
    case "ASSET.Models.Decision.Movement.RectangleWander":
        final WorldLocation topLeft = SupportTesting.createLocation(0, 10000);
        final WorldLocation bottomRight = SupportTesting.createLocation(10000, 0);
        final WorldArea theArea = new WorldArea(topLeft, bottomRight);
        editable = new RectangleWander(theArea, "rect wander");
        break;
    case "org.mwc.debrief.satc_interface.data.wrappers.BMC_Wrapper$BearingMeasurementWrapper":
        bmc = new BearingMeasurementContribution();
        bmc.setName("Measured bearing");
        bmc.setAutoDetect(false);
        CoreMeasurement cm = new CoreMeasurement(new Date());
        BMC_Wrapper bmcw = new BMC_Wrapper(bmc);
        editable = bmcw.new BearingMeasurementWrapper(cm);
        break;
    case "org.mwc.debrief.satc_interface.data.wrappers.FMC_Wrapper$FrequencyMeasurementEditable":
        fmc = new FrequencyMeasurementContribution();
        fmc.setName("Measured frequence");
        FMC_Wrapper fmcw = new FMC_Wrapper(fmc);
        cm = new CoreMeasurement(new Date());
        editable = fmcw.new FrequencyMeasurementEditable(cm);
        break;
    case "ASSET.GUI.SuperSearch.Plotters.SSGuiSupport$ParticipantListener":
        SSGuiSupport ssgs = new SSGuiSupport();
        ssgs.setScenario(new MultiForceScenario());
        editable = new SSGuiSupport.ParticipantListener(new CoreParticipant(12), ssgs);
        break;
    case "ASSET.GUI.Workbench.Plotters.BasePlottable":
        // skip it
        return null;
    case "MWC.TacticalData.GND.GTrack":
        // skip it
        return null;
    default:
        break;
    }

    if (editable != null) {
        return editable;
    }
    Class<?> clazz;
    try {
        clazz = Class.forName(type.getFullyQualifiedName());
    } catch (ClassNotFoundException e1) {
        //e1.printStackTrace();
        System.out.println("CNFE " + e1.getMessage() + " " + type.getFullyQualifiedName());
        return null;
    }
    try {
        @SuppressWarnings("unused")
        Method infoMethod = clazz.getDeclaredMethod("getInfo", new Class[0]);
    } catch (Exception e) {
        return null;
    }
    try {
        editable = (Editable) clazz.newInstance();
    } catch (Exception e) {
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            try {
                Class<?>[] paramTypes = constructor.getParameterTypes();
                Object[] params = new Object[paramTypes.length];
                for (int i = 0; i < paramTypes.length; i++) {
                    Class<?> paramType = paramTypes[i];
                    if (HiResDate.class.equals(paramType)) {
                        params[i] = new HiResDate(new Date());
                    } else if (WorldDistance.class.equals(paramType)) {
                        params[i] = new WorldDistance(12d, WorldDistance.DEGS);
                    } else if (WorldSpeed.class.equals(paramType)) {
                        params[i] = new WorldSpeed(12, WorldSpeed.M_sec);
                    } else if (WorldLocation.class.equals(paramType)) {
                        params[i] = new WorldLocation(12, 12, 12);
                    } else if ("java.lang.String".equals(paramType.getName())) {
                        params[i] = "test";
                    } else if (!paramType.isPrimitive()) {
                        params[i] = null;
                    } else {
                        if (paramType.equals(int.class)) {
                            params[i] = new Integer("0");
                        }
                        if (paramType.equals(boolean.class)) {
                            params[i] = Boolean.FALSE;
                        }
                        if (paramType.equals(long.class)) {
                            params[i] = new Long("0");
                        }
                        if (paramType.equals(double.class)) {
                            params[i] = new Double("0");
                        }
                        if (paramType.equals(float.class)) {
                            params[i] = new Float("0");
                        }
                        if (paramType.equals(short.class)) {
                            params[i] = new Short("0");
                        }
                    }
                }
                editable = (Editable) constructor.newInstance(params);
                break;
            } catch (Exception e1) {
                // ignore
                //System.out.println(e1.getMessage());
                //e1.printStackTrace();
            }
        }
    }
    if (editable == null) {
        System.out.println("Can't instantiate type " + type.getFullyQualifiedName());
    }
    return editable;
}

From source file:com.netflix.hystrix.contrib.javanica.utils.MethodProvider.java

/**
 * Finds generic method for the given bridge method.
 *
 * @param bridgeMethod the bridge method
 * @param aClass       the type where the bridge method is declared
 * @return generic method// w w  w.  j a va 2s  . c  o  m
 * @throws IOException
 * @throws NoSuchMethodException
 * @throws ClassNotFoundException
 */
public Method unbride(final Method bridgeMethod, Class<?> aClass)
        throws IOException, NoSuchMethodException, ClassNotFoundException {
    if (bridgeMethod.isBridge() && bridgeMethod.isSynthetic()) {
        if (cache.containsKey(bridgeMethod)) {
            return cache.get(bridgeMethod);
        }

        ClassReader classReader = new ClassReader(aClass.getName());
        final MethodSignature methodSignature = new MethodSignature();
        classReader.accept(new ClassVisitor(ASM5) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                    String[] exceptions) {
                boolean bridge = (access & ACC_BRIDGE) != 0 && (access & ACC_SYNTHETIC) != 0;
                if (bridge && bridgeMethod.getName().equals(name)
                        && getParameterCount(desc) == bridgeMethod.getParameterTypes().length) {
                    return new MethodFinder(methodSignature);
                }
                return super.visitMethod(access, name, desc, signature, exceptions);
            }
        }, 0);
        Method method = aClass.getDeclaredMethod(methodSignature.name, methodSignature.getParameterTypes());
        cache.put(bridgeMethod, method);
        return method;

    } else {
        return bridgeMethod;
    }
}

From source file:net.sf.jabref.gui.openoffice.OOBibBase.java

private XDesktop simpleBootstrap(String pathToExecutable) throws Exception {

    ClassLoader loader = ClassLoader.getSystemClassLoader();
    if (loader instanceof URLClassLoader) {
        URLClassLoader cl = (URLClassLoader) loader;
        Class<URLClassLoader> sysclass = URLClassLoader.class;
        try {/*w w w  . j  a va  2 s  .  c  o  m*/
            Method method = sysclass.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(cl, new File(pathToExecutable).toURI().toURL());
        } catch (SecurityException | NoSuchMethodException | MalformedURLException t) {
            LOGGER.error("Error, could not add URL to system classloader", t);
            cl.close();
            throw new IOException("Error, could not add URL to system classloader", t);
        }
    } else {
        LOGGER.error("Error occured, URLClassLoader expected but " + loader.getClass()
                + " received. Could not continue.");
    }

    //Get the office component context:
    XComponentContext xContext = Bootstrap.bootstrap();
    //Get the office service manager:
    XMultiComponentFactory xServiceManager = xContext.getServiceManager();
    //Create the desktop, which is the root frame of the
    //hierarchy of frames that contain viewable components:
    Object desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
    XDesktop xD = UnoRuntime.queryInterface(XDesktop.class, desktop);

    UnoRuntime.queryInterface(XComponentLoader.class, desktop);

    return xD;

}

From source file:mercury.RootJsonHandler.java

protected <T extends DTO> T populateDtoFromJson(String jsonData, T dto) {
    try {//  w w w  .  ja v a  2  s  .co m
        JSONObject json = new JSONObject(jsonData);
        Class clazz = dto.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            try {
                String name = field.getName();
                Class fieldClass = field.getType();
                Object value = null;
                if (fieldClass.equals(String.class)) {
                    value = json.has(name) ? json.getString(name) : null;
                } else if (fieldClass.equals(Integer.class)) {
                    try {
                        value = json.has(name) ? json.getInt(name) : null;
                    } catch (Exception e) {
                        value = -1;
                    }
                } else if (fieldClass.equals(Float.class)) {
                    String sValue = json.has(name) ? json.getString(name).replaceAll(",", ".") : null;
                    value = sValue != null ? Float.valueOf(sValue) : null;
                } else if (fieldClass.equals(Date.class)) {
                    value = json.has(name) ? json.getString(name) : null;
                    value = value != null ? this.dateFormatter.parse((String) value) : null;
                }

                if (value == null) {
                    continue;
                }

                Method setter = clazz.getDeclaredMethod("set" + StringUtils.capitalize(name), fieldClass);
                if (setter != null) {
                    setter.invoke(dto, value);
                }
            } catch (Exception e) {
                continue;
            }
        }
    } catch (JSONException je) {
    }
    return dto;
}

From source file:er.extensions.ERXExtensions.java

public void bundleDidLoad(NSNotification n) {
    if (_initialized)
        return;//from w w  w  . jav  a2s  .co m
    _initialized = true;

    try {
        // This will load any optional configuration files, 
        // ensures that WOOutputPath's was processed with this @@
        // variable substitution. WOApplication uses WOOutputPath in
        // its constructor so we need to modify it before calling
        // the constructor.
        ERXConfigurationManager.defaultManager().initialize();
        EOModelGroup.setClassDelegate(this);
        ERXSystem.updateProperties();

        // AK: enable this when we're ready
        // WOEncodingDetector.sharedInstance().setFallbackEncoding(CharEncoding.UTF_8);

        // GN: configure logging with optional custom subclass of ERXLogger
        String className = ERXProperties.stringForKey("er.extensions.erxloggerclass");
        if (className != null) {
            Class loggerClass = Class.forName(className);
            Method method = loggerClass.getDeclaredMethod(ERXLogger.CONFIGURE_LOGGING_WITH_SYSTEM_PROPERTIES,
                    (Class[]) null);
            method.invoke(loggerClass, (Object[]) null);
        } else {
            // default behaviour:
            ERXLogger.configureLoggingWithSystemProperties();
        }

        ERXArrayUtilities.initialize();

        // False by default
        if (ERXValueUtilities
                .booleanValue(System.getProperty(ERXSharedEOLoader.PatchSharedEOLoadingPropertyKey))) {
            ERXSharedEOLoader.patchSharedEOLoading();
        }
        ERXExtensions.configureAdaptorContextRapidTurnAround(this);
        ERXJDBCAdaptor.registerJDBCAdaptor();

        if (EODatabaseContext.defaultDelegate() == null) {
            if (ERXProperties.booleanForKey(
                    ERXEntityDependencyOrderingDelegate.ERXEntityDependencyOrderingDelegateActiveKey)) {
                ERXDatabaseContextMulticastingDelegate
                        .addDefaultDelegate(new ERXEntityDependencyOrderingDelegate());
                ERXDatabaseContextMulticastingDelegate
                        .addDefaultDelegate(ERXDatabaseContextDelegate.defaultDelegate());
            } else {
                EODatabaseContext.setDefaultDelegate(ERXDatabaseContextDelegate.defaultDelegate());
            }
        }

        ERXAdaptorChannelDelegate.setupDelegate();
        NSNotificationCenter.defaultCenter().addObserver(this,
                new NSSelector("sharedEditingContextWasInitialized", ERXConstant.NotificationClassArray),
                EOSharedEditingContext.DefaultSharedEditingContextWasInitializedNotification, null);

        ERXEntityClassDescription.registerDescription();
        ERXPartialInitializer.registerModelGroupListener();
    } catch (Exception e) {
        throw NSForwardException._runtimeExceptionForThrowable(e);
    }
}

From source file:org.apache.camel.maven.JavadocApiMethodGeneratorMojo.java

private String getResultType(Class<?> aClass, String name, String[] types) throws MojoExecutionException {
    Class<?>[] argTypes = new Class<?>[types.length];
    final ClassLoader classLoader = getProjectClassLoader();
    for (int i = 0; i < types.length; i++) {
        try {//from   ww w .  j  a v a2s .com
            try {
                argTypes[i] = ApiMethodParser.forName(types[i], classLoader);
            } catch (ClassNotFoundException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        } catch (IllegalArgumentException e) {
            throw new MojoExecutionException(e.getCause().getMessage(), e.getCause());
        }
    }

    // return null for non-public methods, and for non-static methods if includeStaticMethods is null or false
    String result = null;
    try {
        final Method method = aClass.getMethod(name, argTypes);
        int modifiers = method.getModifiers();
        if (!Modifier.isStatic(modifiers) || Boolean.TRUE.equals(includeStaticMethods)) {
            result = method.getReturnType().getCanonicalName();
        }
    } catch (NoSuchMethodException e) {
        // could be a non-public method
        try {
            aClass.getDeclaredMethod(name, argTypes);
        } catch (NoSuchMethodException e1) {
            throw new MojoExecutionException(e1.getMessage(), e1);
        }
    }

    return result;
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    final ServletContext servletContext = servletContextEvent.getServletContext();
    stopThreads = !"false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
    stopTimerThreads = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
    executeShutdownHooks = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
    threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs",
            THREAD_WAIT_MS_DEFAULT);/*w w w.  j  a va2 s . co  m*/
    shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs",
            SHUTDOWN_HOOK_WAIT_MS_DEFAULT);

    info("Settings for " + this.getClass().getName() + " (CL: 0x"
            + Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
    info("  stopThreads = " + stopThreads);
    info("  stopTimerThreads = " + stopTimerThreads);
    info("  executeShutdownHooks = " + executeShutdownHooks);
    info("  threadWaitMs = " + threadWaitMs + " ms");
    info("  shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");

    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        // If package org.jboss is found, we may be running under JBoss
        mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
    } catch (Exception ex) {
        // Do nothing
    }

    info("Initializing context by loading some known offenders with system classloader");

    // This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener  
    // See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
    try {
        // Switch to system classloader in before we load/call some JRE stuff that will cause 
        // the current classloader to be available for garbage collection
        Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());

        java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread

        java.security.Security.getProviders();

        java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader

        javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()

        try {
            Class.forName("javax.security.auth.Policy").getMethod("getPolicy").invoke(null);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (ClassNotFoundException e) {
            // Ignore silently - class is deprecated
        }

        try {
            javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception ex) { // Example: ParserConfigurationException
            error(ex);
        }

        try {
            Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        try {
            Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        // This probably does not affect classloaders, but prevents some problems with .jar files
        try {
            // URL needs to be well-formed, but does not need to exist
            new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
        } catch (Exception ex) {
            error(ex);
        }

        /////////////////////////////////////////////////////
        // Load Sun specific classes that may cause leaks

        final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");

        try {
            Class.forName("com.sun.jndi.ldap.LdapPoolManager");
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        }

        try {
            Class.forName("sun.java2d.Disposer"); // Will start a Thread
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE && !mayBeJBoss) // JBoss blocks this package/class, so don't warn
                error(cnfex);
        }

        try {
            Class<?> gcClass = Class.forName("sun.misc.GC");
            final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
            requestLatency.invoke(null, 3600000L);
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        }

        // Cause oracle.jdbc.driver.OracleTimeoutPollingThread to be started with contextClassLoader = system classloader  
        try {
            Class.forName("oracle.jdbc.driver.OracleTimeoutThreadPerVM");
        } catch (ClassNotFoundException e) {
            // Ignore silently - class not present
        }
    } finally {
        // Reset original classloader
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:com.adito.server.DefaultAditoServerFactory.java

private void doAddContextLoaderURL(URL u) {
    try {//  w  w  w .ja v  a2  s  . com
        Class sysclass = URLClassLoader.class;
        Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true);
        method.invoke(webappContext.getClassLoader(), new Object[] { u });
        if (LOG.isInfoEnabled()) {
            LOG.info(u.toExternalForm() + " added to context classloader");
        }
    } catch (NoSuchMethodException e) {
        LOG.error("Failed to add to classpath.", e);
    } catch (SecurityException e) {
        LOG.error("Failed to add to classpath.", e);
    } catch (IllegalAccessException e) {
        LOG.error("Failed to add to classpath.", e);
    } catch (IllegalArgumentException e) {
        LOG.error("Failed to add to classpath.", e);
    } catch (InvocationTargetException e) {
        LOG.error("Failed to add to classpath.", e);
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Clean the cache of BeanELResolver/* w w  w  .  j  ava2  s. c  o  m*/
 */
protected void clearBeanELResolverCache() {
    final Class beanElResolverClass = findClass("javax.el.BeanELResolver");
    if (beanElResolverClass != null) {
        boolean cleared = false;
        try {
            final Method purgeBeanClasses = beanElResolverClass.getDeclaredMethod("purgeBeanClasses",
                    ClassLoader.class);
            purgeBeanClasses.setAccessible(true);
            purgeBeanClasses.invoke(beanElResolverClass.newInstance(), getWebApplicationClassLoader());
            cleared = true;
        } catch (NoSuchMethodException e) {
            // Version of javax.el probably > 2.2; no real need to clear
        } catch (Exception e) {
            error(e);
        }

        if (!cleared) {
            // Fallback, if purgeBeanClasses() could not be called
            final Field propertiesField = findField(beanElResolverClass, "properties");
            if (propertiesField != null) {
                try {
                    final Map properties = (Map) propertiesField.get(null);
                    properties.clear();
                } catch (Exception e) {
                    error(e);
                }
            }
        }
    }
}