Example usage for java.lang ClassLoader loadClass

List of usage examples for java.lang ClassLoader loadClass

Introduction

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

Prototype

public Class<?> loadClass(String name) throws ClassNotFoundException 

Source Link

Document

Loads the class with the specified binary name.

Usage

From source file:edu.brown.utils.ArgumentsParser.java

/**
 * @param args/*w  ww .j a  v a 2s  .  co  m*/
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public void process(String[] args, String... required) throws Exception {
    final boolean debug = LOG.isDebugEnabled();

    if (debug)
        LOG.debug("Processing " + args.length + " parameters...");
    final Pattern p = Pattern.compile("=");
    for (int i = 0, cnt = args.length; i < cnt; i++) {
        final String arg = args[i];
        final String[] parts = p.split(arg, 2);
        if (parts[0].startsWith("-"))
            parts[0] = parts[0].substring(1);

        if (parts.length == 1) {
            if (parts[0].startsWith("${") == false)
                this.opt_params.add(parts[0]);
            continue;
        } else if (parts[0].equalsIgnoreCase("tag")) {
            continue;
        } else if (parts[1].startsWith("${") || parts[0].startsWith("#")) {
            continue;
        }
        if (debug)
            LOG.debug(String.format("%-35s = %s", parts[0], parts[1]));

        // DesignerHints Override
        if (parts[0].startsWith(PARAM_DESIGNER_HINTS_PREFIX)) {
            String param = parts[0].replace(PARAM_DESIGNER_HINTS_PREFIX, "").toLowerCase();
            try {
                Field f = DesignerHints.class.getField(param);
                this.hints_params.put(f.getName(), parts[1]);
                if (debug)
                    LOG.debug(String.format("DesignerHints.%s = %s", param, parts[1]));
            } catch (NoSuchFieldException ex) {
                throw new Exception("Unknown DesignerHints parameter: " + param, ex);
            }

        }
        // HStoreConf Parameter
        else if (HStoreConf.isConfParameter(parts[0])) {
            this.conf_params.put(parts[0].toLowerCase(), parts[1]);
        }
        // ArgumentsParser Parameter
        else if (PARAMS.contains(parts[0].toLowerCase())) {
            this.params.put(parts[0].toLowerCase(), parts[1]);
        }
        // Invalid!
        else {
            String suggestions = "";
            i = 0;
            String end = CollectionUtil.last(parts[0].split("\\."));
            for (String param : PARAMS) {
                String param_end = CollectionUtil.last(param.split("\\."));
                if (param.startsWith(parts[0]) || (end != null && param.endsWith(end))
                        || (end != null && param_end != null && param_end.startsWith(end))) {
                    if (suggestions.isEmpty())
                        suggestions = ". Possible Matches:";
                    suggestions += String.format("\n [%02d] %s", ++i, param);
                }
            } // FOR
            throw new Exception("Unknown parameter '" + parts[0] + "'" + suggestions);
        }
    } // FOR

    // -------------------------------------------------------
    // CATALOGS
    // -------------------------------------------------------

    // Text File
    if (this.params.containsKey(PARAM_CATALOG)) {
        String path = this.params.get(PARAM_CATALOG);
        if (debug)
            LOG.debug("Loading catalog from file '" + path + "'");
        Catalog catalog = CatalogUtil.loadCatalog(path);
        if (catalog == null)
            throw new Exception("Failed to load catalog object from file '" + path + "'");
        this.updateCatalog(catalog, new File(path));
    }
    // Jar File
    else if (this.params.containsKey(PARAM_CATALOG_JAR)) {
        String path = this.params.get(PARAM_CATALOG_JAR);
        this.params.put(PARAM_CATALOG, path);
        File jar_file = new File(path);
        Catalog catalog = CatalogUtil.loadCatalogFromJar(path);
        if (catalog == null)
            throw new Exception("Failed to load catalog object from jar file '" + path + "'");
        if (debug)
            LOG.debug("Loaded catalog from jar file '" + path + "'");
        this.updateCatalog(catalog, jar_file);

        if (!this.params.containsKey(PARAM_CATALOG_TYPE)) {
            String jar_name = jar_file.getName();
            int jar_idx = jar_name.lastIndexOf(".jar");
            if (jar_idx != -1) {
                ProjectType type = ProjectType.get(jar_name.substring(0, jar_idx));
                if (type != null) {
                    if (debug)
                        LOG.debug("Set catalog type '" + type + "' from catalog jar file name");
                    this.catalog_type = type;
                    this.params.put(PARAM_CATALOG_TYPE, this.catalog_type.toString());
                }
            }
        }

        // HACK: Extract the ParameterMappings embedded in jar and write them to a temp file
        // This is terrible, confusing, and a total mess...
        // I have no one to blame but myself...
        JarReader reader = new JarReader(jar_file.getAbsolutePath());
        for (String file : reader.getContentsFromJarfile()) {
            if (file.endsWith(".mappings")) {
                String contents = new String(JarReader.readFileFromJarAtURL(jar_file.getAbsolutePath(), file));
                File copy = FileUtil.writeStringToTempFile(contents, "mappings", true);
                this.params.put(PARAM_MAPPINGS, copy.toString());
                break;
            }
        } // FOR
    }
    // Schema File
    else if (this.params.containsKey(PARAM_CATALOG_SCHEMA)) {
        String path = this.params.get(PARAM_CATALOG_SCHEMA);
        Catalog catalog = CompilerUtil.compileCatalog(path);
        if (catalog == null)
            throw new Exception("Failed to load schema from '" + path + "'");
        if (debug)
            LOG.debug("Loaded catalog from schema file '" + path + "'");
        this.updateCatalog(catalog, new File(path));
    }

    // Catalog Type
    if (this.params.containsKey(PARAM_CATALOG_TYPE)) {
        String catalog_type = this.params.get(PARAM_CATALOG_TYPE);
        ProjectType type = ProjectType.get(catalog_type);
        if (type == null) {
            throw new Exception("Unknown catalog type '" + catalog_type + "'");
        }
        this.catalog_type = type;
    }

    // Update Cluster Configuration
    if (this.params.containsKey(ArgumentsParser.PARAM_CATALOG_HOSTS) && DISABLE_UPDATE_CATALOG == false) {
        ClusterConfiguration cc = new ClusterConfiguration(this.getParam(ArgumentsParser.PARAM_CATALOG_HOSTS));
        this.updateCatalog(FixCatalog.cloneCatalog(this.catalog, cc), null);
    }

    // Check the requirements after loading the catalog, because some of the
    // above parameters will set the catalog one
    if (required != null && required.length > 0)
        this.require(required);

    // -------------------------------------------------------
    // PHYSICAL DESIGN COMPONENTS
    // -------------------------------------------------------
    if (this.params.containsKey(PARAM_PARTITION_PLAN)) {
        assert (this.catalog_db != null);
        File path = new File(this.params.get(PARAM_PARTITION_PLAN));
        boolean ignoreMissing = this.getBooleanParam(ArgumentsParser.PARAM_PARTITION_PLAN_IGNORE_MISSING,
                false);
        if (path.exists() || (path.exists() == false && ignoreMissing == false)) {
            if (debug)
                LOG.debug("Loading in partition plan from '" + path + "'");
            this.pplan = new PartitionPlan();
            this.pplan.load(path, this.catalog_db);

            // Apply!
            if (this.params.containsKey(PARAM_PARTITION_PLAN_APPLY)
                    && this.getBooleanParam(PARAM_PARTITION_PLAN_APPLY)) {
                boolean secondaryIndexes = this.getBooleanParam(PARAM_PARTITION_PLAN_NO_SECONDARY,
                        false) == false;
                LOG.info(String.format("Applying PartitionPlan '%s' to catalog [enableSecondaryIndexes=%s]",
                        path.getName(), secondaryIndexes));
                this.pplan.apply(this.catalog_db, secondaryIndexes);
            }
        }
    }

    // -------------------------------------------------------
    // DESIGNER COMPONENTS
    // -------------------------------------------------------

    if (this.params.containsKey(PARAM_DESIGNER_THREADS)) {
        this.max_concurrent = Integer.valueOf(this.params.get(PARAM_DESIGNER_THREADS));
    }
    if (this.params.containsKey(PARAM_DESIGNER_INTERVALS)) {
        this.num_intervals = Integer.valueOf(this.params.get(PARAM_DESIGNER_INTERVALS));
    }
    if (this.params.containsKey(PARAM_DESIGNER_HINTS)) {
        File path = this.getFileParam(PARAM_DESIGNER_HINTS);
        if (debug)
            LOG.debug("Loading in designer hints from '" + path + "'.\nForced Values:\n"
                    + StringUtil.formatMaps(this.hints_params));
        this.designer_hints.load(path, catalog_db, this.hints_params);
    }
    if (this.params.containsKey(PARAM_DESIGNER_CHECKPOINT)) {
        this.designer_checkpoint = new File(this.params.get(PARAM_DESIGNER_CHECKPOINT));
    }

    String designer_attributes[] = { PARAM_DESIGNER_PARTITIONER, PARAM_DESIGNER_MAPPER, PARAM_DESIGNER_INDEXER,
            PARAM_DESIGNER_COSTMODEL };
    ClassLoader loader = ClassLoader.getSystemClassLoader();
    for (String key : designer_attributes) {
        if (this.params.containsKey(key)) {
            String target_name = this.params.get(key);
            Class<?> target_class = loader.loadClass(target_name);
            assert (target_class != null);
            if (debug)
                LOG.debug("Set " + key + " class to " + target_class.getName());

            if (key.equals(PARAM_DESIGNER_PARTITIONER)) {
                this.partitioner_class = (Class<? extends AbstractPartitioner>) target_class;
            } else if (key.equals(PARAM_DESIGNER_MAPPER)) {
                this.mapper_class = (Class<? extends AbstractMapper>) target_class;
            } else if (key.equals(PARAM_DESIGNER_INDEXER)) {
                this.indexer_class = (Class<? extends AbstractIndexSelector>) target_class;
            } else if (key.equals(PARAM_DESIGNER_COSTMODEL)) {
                this.costmodel_class = (Class<? extends AbstractCostModel>) target_class;

                // Special Case: TimeIntervalCostModel
                if (target_name.endsWith(TimeIntervalCostModel.class.getSimpleName())) {
                    this.costmodel = new TimeIntervalCostModel<SingleSitedCostModel>(this.catalogContext,
                            SingleSitedCostModel.class, this.num_intervals);
                } else {
                    this.costmodel = ClassUtil.newInstance(this.costmodel_class,
                            new Object[] { this.catalogContext }, new Class[] { Database.class });
                }
            } else {
                assert (false) : "Invalid key '" + key + "'";
            }
        }
    } // FOR

    // -------------------------------------------------------
    // TRANSACTION ESTIMATION COMPONENTS
    // -------------------------------------------------------
    if (this.params.containsKey(PARAM_MAPPINGS) && DISABLE_UPDATE_CATALOG == false) {
        assert (this.catalog_db != null);
        File path = new File(this.params.get(PARAM_MAPPINGS));
        if (path.exists()) {
            this.param_mappings.load(path, this.catalog_db);
        } else {
            LOG.warn("The ParameterMappings file '" + path + "' does not exist");
        }
    }
    if (this.params.containsKey(PARAM_MARKOV_THRESHOLDS_VALUE)) {
        assert (this.catalog_db != null);
        float defaultValue = this.getDoubleParam(PARAM_MARKOV_THRESHOLDS_VALUE).floatValue();
        this.thresholds = new EstimationThresholds(defaultValue);
        this.params.put(PARAM_MARKOV_THRESHOLDS, this.thresholds.toString());
        LOG.debug("CREATED THRESHOLDS: " + this.thresholds);

    } else if (this.params.containsKey(PARAM_MARKOV_THRESHOLDS)) {
        assert (this.catalog_db != null);
        this.thresholds = new EstimationThresholds();
        File path = new File(this.params.get(PARAM_MARKOV_THRESHOLDS));
        if (path.exists()) {
            this.thresholds.load(path, this.catalog_db);
        } else {
            LOG.warn("The estimation thresholds file '" + path + "' does not exist");
        }
        LOG.debug("LOADED THRESHOLDS: " + this.thresholds);
    }

    // -------------------------------------------------------
    // HASHER
    // -------------------------------------------------------
    if (this.catalog != null) {
        if (this.params.containsKey(PARAM_HASHER_CLASS)) {
            String hasherClassName = this.params.get(PARAM_HASHER_CLASS);
            this.hasher_class = (Class<? extends AbstractHasher>) loader.loadClass(hasherClassName);
        }
        Class<?> paramClasses[] = new Class[] { CatalogContext.class, int.class };
        Object paramValues[] = new Object[] { this.catalogContext, this.catalogContext.numberOfPartitions };

        Constructor<? extends AbstractHasher> constructor = this.hasher_class.getConstructor(paramClasses);
        this.hasher = constructor.newInstance(paramValues);

        if (!(this.hasher instanceof DefaultHasher))
            LOG.debug("Loaded hasher " + this.hasher.getClass());

        if (this.params.containsKey(PARAM_HASHER_PROFILE)) {
            this.hasher.load(this.getFileParam(PARAM_HASHER_PROFILE), null);
        }
    }

    // -------------------------------------------------------
    // SAMPLE WORKLOAD TRACE
    // -------------------------------------------------------
    this.loadWorkload();
}

From source file:com.app.server.EJBDeployer.java

public void scanJar(FileObject jarFile, HashSet<Class<?>>[] classanotwith, Class[] annot, ClassLoader cL)
        throws FileSystemException {
    //FileObject[] childs=jarFile.getChildren();
    //for(FileObject child:childs){
    FileObject[] classes = jarFile.findFiles(new FileSelector() {

        @Override/*from w ww.j av  a2  s  .  c  o  m*/
        public boolean includeFile(FileSelectInfo arg0) throws Exception {
            return arg0.getFile().getName().getBaseName().endsWith(".class");
        }

        @Override
        public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
            // TODO Auto-generated method stub
            return true;
        }

    });
    //}
    int index = 0;
    for (FileObject cls : classes) {
        try {
            Class<?> clz = cL.loadClass(cls.getURL().toURI().toString()
                    .replace(jarFile.getURL().toURI().toString(), "").replace("/", ".").replace(".class", ""));
            index = 0;
            for (Class annotclz : annot) {
                if (clz.getAnnotation(annotclz) != null) {
                    classanotwith[index].add(clz);
                }
                index++;
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.amalto.core.storage.hibernate.ScatteredTypeMapping.java

private Object getReferencedObject(ClassLoader storageClassLoader, Session session,
        ComplexTypeMetadata referencedType, Object referencedIdValue) {
    Class<?> referencedClass;
    try {//from  w w w  .  j  ava2s.com
        referencedClass = ((StorageClassLoader) storageClassLoader).getClassFromType(referencedType);
    } catch (Exception e) {
        throw new RuntimeException("Could not get class for type '" + referencedType.getName() + "'", e);
    }
    try {
        if (referencedIdValue == null) {
            return null; // Means no reference (reference is null).
        }
        if (referencedIdValue instanceof Wrapper) {
            return referencedIdValue; // It's already the referenced object.
        }
        // Try to load object from current session
        if (referencedIdValue instanceof List) {
            // Handle composite id values
            Serializable result;
            try {
                Class<?> idClass = storageClassLoader.loadClass(referencedClass.getName() + "_ID"); //$NON-NLS-1$
                Class[] parameterClasses = new Class[((List) referencedIdValue).size()];
                int i = 0;
                for (Object o : (List) referencedIdValue) {
                    if (o == null) {
                        throw new IllegalStateException("Id cannot have a null value.");
                    }
                    parameterClasses[i++] = o.getClass();
                }
                Constructor<?> constructor = idClass.getConstructor(parameterClasses);
                result = (Serializable) constructor.newInstance(((List) referencedIdValue).toArray());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Serializable referencedValueId = result;
            // should actually load the object to validate the FK (for Record Validation), check by ThreadLocal won't affect performance or block function
            if (DataRecord.ValidateRecord.get()) {
                Object sessionObject = session.get(referencedClass, referencedValueId);
                if (sessionObject == null) {
                    throw new ValidateException(
                            "Invalid foreign key: [" + referencedClass.getName() + "#" + referencedValueId //$NON-NLS-1$ //$NON-NLS-2$
                                    + "] doesn't exist."); //$NON-NLS-1$
                } else {
                    return sessionObject;
                }
            } else {
                Object sessionObject = session.load(referencedClass, referencedValueId);
                if (sessionObject != null) {
                    return sessionObject;
                }
            }
        } else if (referencedIdValue instanceof Serializable) {
            // should actually load the object to validate the FK (for Record Validation), check by ThreadLocal won't affect performance or block function
            if (DataRecord.ValidateRecord.get()) {
                Object sessionObject = session.get(referencedClass, (Serializable) referencedIdValue);
                if (sessionObject == null) {
                    throw new ValidateException("Invalid foreign key: [" + referencedClass.getName() + "#" //$NON-NLS-1$//$NON-NLS-2$
                            + (Serializable) referencedIdValue + "] doesn't exist."); //$NON-NLS-1$
                } else {
                    return sessionObject;
                }
            } else {
                Object sessionObject = session.load(referencedClass, (Serializable) referencedIdValue);
                if (sessionObject != null) {
                    return sessionObject;
                }
            }
        } else {
            throw new NotImplementedException("Unexpected state.");
        }
        Class<?> fieldJavaType = referencedIdValue.getClass();
        // Null package might happen with proxy classes generated by Hibernate
        if (fieldJavaType.getPackage() != null && fieldJavaType.getPackage().getName().startsWith("java.")) { //$NON-NLS-1$
            Wrapper referencedObject = (Wrapper) referencedClass.newInstance();
            for (FieldMetadata fieldMetadata : referencedType.getFields()) {
                if (fieldMetadata.isKey()) {
                    referencedObject.set(fieldMetadata.getName(), referencedIdValue);
                }
            }
            return referencedObject;
        } else {
            return referencedIdValue;
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not create referenced object of type '" + referencedClass
                + "' with id '" + String.valueOf(referencedIdValue) + "'", e);
    }
}

From source file:be.fedict.eid.idp.webapp.IdentityProviderServletContextListener.java

private void initProtocolServices(ServletContextEvent event) {

    ServletContext servletContext = event.getServletContext();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    List<IdentityProviderProtocolType> identityProviderProtocolTypes = this.protocolServiceManager
            .getProtocolServices();/*from   w w w.j  a v a 2  s.  c o  m*/

    Map<String, String> wsEndpointsMap = new HashMap<String, String>();

    for (IdentityProviderProtocolType identityProviderProtocolType : identityProviderProtocolTypes) {
        String name = identityProviderProtocolType.getName();
        LOG.debug("initializing protocol service: " + name);

        // register endpoints
        EndpointsType endpoints = identityProviderProtocolType.getEndpoints();
        if (null != endpoints) {
            for (EndpointType endpoint : endpoints.getEndpoint()) {
                String contextPath = endpoint.getContextPath();
                String servletClassName = endpoint.getServletClass();
                LOG.debug("initializing on context path: " + contextPath + " servlet " + servletClassName);
                Class<?> servletClass;
                try {
                    servletClass = classLoader.loadClass(servletClassName);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("could not load the servlet class: " + servletClassName);
                }
                if (!Servlet.class.isAssignableFrom(servletClass)) {
                    throw new RuntimeException("not a servlet class: " + servletClassName);
                }
                String servletName = name + contextPath;
                LOG.debug("servlet name: " + servletName);
                @SuppressWarnings("unchecked")
                Dynamic dynamic = servletContext.addServlet(servletName,
                        (Class<? extends Servlet>) servletClass);
                String urlPattern = IdentityProviderProtocolService.ENDPOINT_CONTEXT_PATH + contextPath;
                dynamic.addMapping(urlPattern);
            }
        }

        // WS endpoints
        WSEndpointsType wsEndpoints = identityProviderProtocolType.getWSEndpoints();
        if (null != wsEndpoints) {
            for (WSEndpointType wsEndpoint : wsEndpoints.getWSEndpoint()) {

                String contextPath = wsEndpoint.getContextPath();
                String wsImplClass = wsEndpoint.getWSImplClass();
                LOG.debug("WS Endpoint: path=" + contextPath + " impl=" + wsImplClass);
                wsEndpointsMap.put(contextPath, wsImplClass);
            }
        }

        // initialize protocol specific attribute URIs
        LOG.debug("initializing protocol specific attribute URIs");
        IdentityProviderProtocolService protocolService = this.protocolServiceManager
                .getProtocolService(identityProviderProtocolType);

        for (AttributeEntity attribute : this.attributeService.listAttributes()) {

            this.attributeService.createAttributeUri(protocolService.getId(), attribute.getUri(),
                    protocolService.findAttributeUri(attribute.getUri()));
        }
    }

    // register JAX-WS runtime if necessary
    if (!wsEndpointsMap.isEmpty()) {

        // WSServlet class
        Class<?> wsServletClass;
        try {
            wsServletClass = classLoader.loadClass("com.sun.xml.ws.transport.http.servlet.WSServlet");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        @SuppressWarnings("unchecked")
        Dynamic dynamic = servletContext.addServlet("WSServlet", (Class<? extends Servlet>) wsServletClass);
        String urlPattern = IdentityProviderProtocolService.WS_ENDPOINT_CONTEXT_PATH + "/*";
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping(urlPattern);

        // intialize WS endpoints
        initWsEndpoints(servletContext, wsEndpointsMap);

    }
}

From source file:com.moviejukebox.MovieJukebox.java

public static synchronized MovieImagePlugin getImagePlugin(String className) {
    try {//from   w ww  . ja  va 2s  . c o  m
        Thread t = Thread.currentThread();
        ClassLoader cl = t.getContextClassLoader();
        Class<? extends MovieImagePlugin> pluginClass = cl.loadClass(className)
                .asSubclass(MovieImagePlugin.class);
        return pluginClass.newInstance();
    } catch (InstantiationException ex) {
        LOG.error("Failed instanciating ImagePlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (IllegalAccessException ex) {
        LOG.error("Failed accessing ImagePlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (ClassNotFoundException ex) {
        LOG.error("ImagePlugin class not found: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    }
    LOG.error("Default poster plugin will be used instead.");
    return new DefaultImagePlugin();
}

From source file:com.moviejukebox.MovieJukebox.java

public static MovieImagePlugin getBackgroundPlugin(String className) {
    try {/* w  ww  .j a  v a2  s.co  m*/
        Thread t = Thread.currentThread();
        ClassLoader cl = t.getContextClassLoader();
        Class<? extends MovieImagePlugin> pluginClass = cl.loadClass(className)
                .asSubclass(MovieImagePlugin.class);
        return pluginClass.newInstance();
    } catch (InstantiationException ex) {
        LOG.error("Failed instantiating BackgroundPlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (IllegalAccessException ex) {
        LOG.error("Failed accessing BackgroundPlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (ClassNotFoundException ex) {
        LOG.error("BackgroundPlugin class not found: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    }

    LOG.error("Default background plugin will be used instead.");
    return new DefaultBackgroundPlugin();
}

From source file:com.moviejukebox.MovieJukebox.java

public static MovieListingPlugin getListingPlugin(String className) {
    try {/*  w  w  w  .  j  a v a  2  s .  co  m*/
        Thread t = Thread.currentThread();
        ClassLoader cl = t.getContextClassLoader();
        Class<? extends MovieListingPlugin> pluginClass = cl.loadClass(className)
                .asSubclass(MovieListingPlugin.class);
        return pluginClass.newInstance();
    } catch (InstantiationException ex) {
        LOG.error("Failed instanciating ListingPlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (IllegalAccessException ex) {
        LOG.error("Failed accessing ListingPlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (ClassNotFoundException ex) {
        LOG.error("ListingPlugin class not found: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    }

    LOG.error("No listing plugin will be used.");
    return new MovieListingPluginBase();
}

From source file:io.neba.core.spring.web.filter.NebaRequestContextFilterTest.java

@Test
public void testFilterToleratesAbsenceOfOptionalDependencyToBgHttpServletRequest() throws Exception {
    ClassLoader classLoaderWithoutBgServlets = new ClassLoader(getClass().getClassLoader()) {
        @Override/* w w  w .  ja  va 2  s.  co m*/
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (BackgroundHttpServletRequest.class.getName().equals(name)) {
                // This optional dependency is not present on the class path in this test scenario.
                throw new ClassNotFoundException(
                        "THIS IS AN EXPECTED TEST EXCEPTION. The dependency to bgservlets is optional.");
            }
            if (NebaRequestContextFilter.class.getName().equals(name)) {
                // Define the test subject's class class in this class loader, thus its dependencies -
                // such as the background servlet request - are also loaded via this class loader.
                try {
                    byte[] classFileData = toByteArray(
                            getResourceAsStream(name.replace('.', '/').concat(".class")));
                    return defineClass(name, classFileData, 0, classFileData.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException("Unable to load " + name + ".", e);
                }
            }

            return super.loadClass(name);
        }
    };

    Class<?> filterClass = classLoaderWithoutBgServlets.loadClass(NebaRequestContextFilter.class.getName());

    assertThat(field("IS_BGSERVLETS_PRESENT").ofType(boolean.class).in(filterClass).get()).isFalse();

    Object filter = filterClass.newInstance();

    method("doFilter").withParameterTypes(ServletRequest.class, ServletResponse.class, FilterChain.class)
            .in(filter).invoke(request, response, chain);
}

From source file:io.neba.spring.web.NebaRequestContextFilterTest.java

@Test
public void testFilterToleratesAbsenceOfOptionalDependencyToBgHttpServletRequest() throws Exception {
    ClassLoader classLoaderWithoutBgServlets = new ClassLoader(getClass().getClassLoader()) {
        @Override/*w  w w .  j  a v a 2s  . com*/
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (BackgroundHttpServletRequest.class.getName().equals(name)) {
                // This optional dependency is not present on the class path in this test scenario.
                throw new ClassNotFoundException(
                        "THIS IS AN EXPECTED TEST EXCEPTION. The dependency to bgservlets is optional.");
            }
            if (NebaRequestContextFilter.class.getName().equals(name)) {
                // Define the test subject's class class in this class loader, thus its dependencies -
                // such as the background servlet request - are also loaded via this class loader.
                try {
                    byte[] classFileData = toByteArray(
                            getResourceAsStream(name.replace('.', '/').concat(".class")));
                    return defineClass(name, classFileData, 0, classFileData.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException("Unable to load " + name + ".", e);
                }
            }

            return super.loadClass(name);
        }
    };

    Class<?> filterClass = classLoaderWithoutBgServlets.loadClass(NebaRequestContextFilter.class.getName());

    assertThat(valueOfField(filterClass, "IS_BGSERVLETS_PRESENT")).isFalse();

    Object filter = filterClass.newInstance();

    invoke(filter, "doFilter", request, response, chain);
}

From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected void executeTool(String toolClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        public void checkPermission(Permission permission) {
        }/*  w ww .  j a va 2 s. com*/

        public void checkExit(int status) {
            throw new SecurityException();
        }

    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(toolClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (ite.getCause() instanceof SecurityException) {
        } else {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.clearProperty("org.apache.commons.logging.Log");

        System.setSecurityManager(currentSecurityManager);
    }
}