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:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;/*  w w w.j a  v  a  2s.co  m*/

    try {
        String configFilePath = null;
        String json = null;
        JSONObject jObj = null;

        parseJson: {
            //If a command line argument is passed then assume it is the config file.
            //Otherwise use the default location
            if (args.length > 0) {
                configFilePath = args[0];
            } else {
                configFilePath = DBMojoServer.defaultConfigPath;
            }

            try {
                json = Util.fileToString(configFilePath);
            } catch (Exception fileEx) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', could not be found and/or read");
            }

            if (json == null || json.equals("")) {
                throw new Exception("the specified config file, '" + configFilePath + "', is empty");
            }

            try {
                jObj = new JSONObject(json);
            } catch (Exception je) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', does not contain valid JSON");
            }
        }

        //Load basic config data
        short serverPort = (short) jObj.optInt("serverPort");
        boolean useGzip = jObj.optBoolean("useGzip");
        short maxConcReq = (short) jObj.optInt("maxConcurrentRequests");
        String accessLogPath = jObj.optString("accessLogPath");
        String errorLogPath = jObj.optString("errorLogPath");
        String debugLogPath = jObj.optString("debugLogPath");

        checkMaxConcurrentReqeusts: {
            if (maxConcReq <= 0) {
                throw new Exception("please set the max concurrent requests to " + "a resonable number");
            }
        }

        checkServerPort: {
            //Make sure serverPort was specified
            if (serverPort <= 0) {
                throw new Exception("the server port was not specified");
            }

            //Make sure serverPort is not in use
            ServerSocket tSocket = null;
            try {
                tSocket = new ServerSocket(serverPort);
            } catch (Exception se) {
                tSocket = null;
                throw new Exception("the server port specified is already in use");
            } finally {
                if (tSocket != null) {
                    tSocket.close();
                }
                tSocket = null;
            }
        }

        startLogs: {
            if (!accessLogPath.equals("")) {
                //Make sure accessLogPath exists
                Util.pathExists(accessLogPath, true);
                //Start logging
                AccessLog.start(accessLogPath);
            }

            if (!errorLogPath.equals("")) {
                //Make sure errorLogPath exists
                Util.pathExists(errorLogPath, true);
                //Start logging
                ErrorLog.start(errorLogPath);
            }

            if (!debugLogPath.equals("")) {
                //Make sure debugLogPath exists
                Util.pathExists(debugLogPath, true);
                //Start logging
                DebugLog.start(debugLogPath);
            }
        }

        ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>();
        loadDbAlaises: {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            final JSONArray dbAliases = jObj.getJSONArray("dbAliases");

            for (int i = 0; i < dbAliases.length(); i++) {
                final JSONObject tObj = dbAliases.getJSONObject(i);
                final String tAlias = tObj.getString("alias");
                final String tDriver = tObj.getString("driver");
                final String tDsn = tObj.getString("dsn");
                final String tUsername = tObj.getString("username");
                final String tPassword = tObj.getString("password");
                int tMaxConnections = tObj.getInt("maxConnections");
                //Seconds
                int tExpirationTime = tObj.getInt("expirationTime") * 1000;
                //Seconds
                int tConnectTimeout = tObj.getInt("connectTimeout");

                //Make sure each alias is named
                if (tAlias.equals("")) {
                    throw new Exception("alias #" + i + " is missing a name");
                }

                //Attempt to load each JDBC driver to ensure they are on the class path
                try {
                    Class aClass = classLoader.loadClass(tDriver);
                } catch (ClassNotFoundException cnf) {
                    throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path");
                }

                //Make sure each alias has a JDBC connection string
                if (tDsn.equals("")) {
                    throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'");
                }

                //Attempt to create a JDBC Connection
                ConnectionPool tPool;
                try {
                    tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias);
                    tPool.checkOut(false);
                } catch (Exception e) {
                    throw new Exception(
                            "JDBC Connection cannot be established " + "for database '" + tAlias + "'");
                } finally {
                    tPool = null;
                }

                //If the max connections option is not set for this alias 
                //then set it to 25
                if (tMaxConnections <= 0) {
                    tMaxConnections = 25;
                    System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '"
                            + tAlias + "' using 25");
                }

                //If the connection expiration time is not set for this alias then 
                //set it to 30 seconds
                if (tExpirationTime <= 0) {
                    tExpirationTime = 30;
                    System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '"
                            + tAlias + "' using 30 seconds");
                }

                //If the connection timeout is not set for this alias then 
                //set it to 10 seconds
                if (tConnectTimeout <= 0) {
                    tConnectTimeout = 10;
                    System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '"
                            + tAlias + "' using 10 seconds");
                }

                //Make sure another alias with the same name is not already 
                //defined in the config
                if (dbPools.containsKey(tAlias)) {
                    throw new Exception(
                            "the alias '" + tAlias + "' is already defined in " + " the provided config file");
                }

                //Everything is nicely set! Lets add a connection pool to the 
                //dbPool Hashtable keyed by this alias name
                dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections,
                        tExpirationTime, tConnectTimeout, tAlias));
            }
        }

        loadClusters: {
            final JSONArray tClusters = jObj.optJSONArray("clusters");

            if (tClusters != null) {
                for (int c = 0; c < tClusters.length(); c++) {
                    final JSONObject tObj = tClusters.getJSONObject(c);
                    final String tAlias = tObj.getString("alias");
                    final String tWriteTo = tObj.getString("writeTo");

                    if (dbPools.containsKey(tAlias)) {
                        throw new Exception("the alias '" + tAlias + "' is already defined.");
                    }

                    if (!dbPools.containsKey(tWriteTo)) {
                        throw new Exception(
                                "the alias '" + tWriteTo + "' is not present in the valid dbAliases. "
                                        + "This alias cannot be used for a cluster.");
                    }

                    //Add the dbAlias to the cluster writeTo list
                    ConnectionPool writeTo = dbPools.get(tWriteTo);

                    final JSONArray tReadFrom = tObj.getJSONArray("readFrom");
                    ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>();
                    for (int r = 0; r < tReadFrom.length(); r++) {
                        final String tRead = tReadFrom.getString(r);
                        if (!dbPools.containsKey(tRead)) {
                            throw new Exception(
                                    "the alias '" + tRead + "' is not present in the valid dbAliases. "
                                            + "This alias cannot be used for a cluster.");
                        }
                        //Add the dbAlias to the cluster readFrom list
                        readFromList.add(dbPools.get(tRead));
                    }

                    dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList));
                }
            }
        }

        server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools);

    } catch (Exception jsonEx) {
        System.out.println("DBMojoServer: Config error, " + jsonEx);
        System.exit(-1);
    }

    return server;
}

From source file:net.naijatek.myalumni.util.fileupload.FileUpload.java

/**
 * <p> Returns the <code>Method</code> object to_email be used to_email obtain a new
 * <code>FileItem</code> instance.
 * //from ww w  .  j  a va 2  s  .  co m
 * <p> For performance reasons, we cache the method once it has been
 * looked up, since method lookup is one of the more expensive aspects
 * of reflection.
 * 
 * @return The <code>newInstance()</code> method to_email be invoked.
 * 
 * @exception FileUploadException if an error occurs.
 */
protected Method getNewInstanceMethod() throws FileUploadException {
    // If the method is already cached, just return it.
    if (this.newInstanceMethod != null) {
        return this.newInstanceMethod;
    }

    // Load the FileUpload implementation class.
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Class fileItemClass = null;

    if (classLoader == null) {
        classLoader = getClass().getClassLoader();
    }

    try {
        fileItemClass = classLoader.loadClass(fileItemClassName);
    } catch (Exception e) {
        throw new FileUploadException(e.toString());
    }

    if (fileItemClass == null) {
        throw new FileUploadException("Failed to load FileItem class: " + fileItemClassName);
    }

    // Find the newInstance() method.
    Class[] parameterTypes = new Class[] { String.class, String.class, String.class, Integer.TYPE,
            Integer.TYPE };
    Method newInstanceMethod = MethodUtils.getAccessibleMethod(fileItemClass, "newInstance", parameterTypes);

    if (newInstanceMethod == null) {
        throw new FileUploadException(
                "Failed find newInstance() method in FileItem class: " + fileItemClassName);
    }

    // Cache the method so that all this only happens once.
    this.newInstanceMethod = newInstanceMethod;
    return newInstanceMethod;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

private Object attemptToConvertStringToEnum(Class<?> requiredType, String trimmedValue,
        Object currentConvertedValue) {
    Object convertedValue = currentConvertedValue;

    if (Enum.class.equals(requiredType)) {
        // target type is declared as raw enum, treat the trimmed value as <enum.fqn>.FIELD_NAME
        int index = trimmedValue.lastIndexOf(".");
        if (index > -1) {
            String enumType = trimmedValue.substring(0, index);
            String fieldName = trimmedValue.substring(index + 1);
            ClassLoader loader = this.targetObject.getClass().getClassLoader();
            try {
                Class<?> enumValueType = loader.loadClass(enumType);
                Field enumField = enumValueType.getField(fieldName);
                convertedValue = enumField.get(null);
            } catch (ClassNotFoundException ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Enum class [" + enumType + "] cannot be loaded from [" + loader + "]", ex);
                }//from w ww  .  j  a v a  2 s. c o m
            } catch (Throwable ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Field [" + fieldName + "] isn't an enum value for type [" + enumType + "]",
                            ex);
                }
            }
        }
    }

    if (convertedValue == currentConvertedValue) {
        // Try field lookup as fallback: for JDK 1.5 enum or custom enum
        // with values defined as static fields. Resulting value still needs
        // to be checked, hence we don't return it right away.
        try {
            Field enumField = requiredType.getField(trimmedValue);
            convertedValue = enumField.get(null);
        } catch (Throwable ex) {
            if (logger.isTraceEnabled()) {
                logger.trace("Field [" + convertedValue + "] isn't an enum value", ex);

            }
        }
    }

    return convertedValue;
}

From source file:com.streamsets.pipeline.maven.rbgen.RBGenMojo.java

@Override
@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
    try {/*from   www. jav a  2 s  .c om*/
        ClassLoader projectCL = getProjectClassLoader();
        if (usesDataCollectorAPI(projectCL)) {
            File file = new File(project.getBuild().getOutputDirectory(), BUNDLES_TO_GEN_FILE);
            if (file.exists() && file.isFile()) {
                Map<String, File> bundles = new HashMap<>();
                List<String> classNames = new ObjectMapper().readValue(file, List.class);
                if (!classNames.isEmpty()) {
                    for (String e : classNames) {
                        Class klass = projectCL.loadClass(e);
                        String bundleName = klass.getName().replace(".", "/") + "-bundle.properties";
                        File bundleFile = generateDefaultBundleForClass(klass, bundleName);
                        bundles.put(bundleName, bundleFile);
                    }
                    File jarFile = new File(project.getBuild().getDirectory(),
                            project.getArtifactId() + "-" + project.getVersion() + "-bundles.jar");
                    getLog().info("Building bundles jar: " + jarFile.getAbsolutePath());
                    createBundlesJar(jarFile, bundles);
                } else {
                    getLog().debug(BUNDLES_TO_GEN_FILE
                            + "' file does not have any class, no bundles jar will be generated");
                }
            } else {
                getLog().debug("Project does not have '" + BUNDLES_TO_GEN_FILE
                        + "' file, no bundles jar will be generated");
            }
        } else {
            getLog().debug("Project does not use DataCollector API, no bundles jar will be generated");
        }
    } catch (Throwable ex) {
        throw new MojoExecutionException(ex.toString(), ex);
    }
}

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

@Override
public StorageResults visit(Select select) {
    // TMDM-4654: Checks if entity has a composite PK.
    Set<ComplexTypeMetadata> compositeKeyTypes = new HashSet<ComplexTypeMetadata>();
    // TMDM-7496: Search should include references to reused types
    Collection<ComplexTypeMetadata> types = new HashSet<ComplexTypeMetadata>(
            select.accept(new SearchTransitiveClosure(storage)));
    for (ComplexTypeMetadata type : types) {
        if (type.getKeyFields().size() > 1) {
            compositeKeyTypes.add(type);
        }//from w  w  w.j  ava 2s . c o  m
    }
    if (!compositeKeyTypes.isEmpty()) {
        StringBuilder message = new StringBuilder();
        Iterator it = compositeKeyTypes.iterator();
        while (it.hasNext()) {
            ComplexTypeMetadata compositeKeyType = (ComplexTypeMetadata) it.next();
            message.append(compositeKeyType.getName());
            if (it.hasNext()) {
                message.append(',');
            }
        }
        throw new FullTextQueryCompositeKeyException(message.toString());
    }
    // Removes Joins and joined fields.
    List<Join> joins = select.getJoins();
    if (!joins.isEmpty()) {
        Set<ComplexTypeMetadata> joinedTypes = new HashSet<ComplexTypeMetadata>();
        for (Join join : joins) {
            joinedTypes.add(join.getRightField().getFieldMetadata().getContainingType());
        }
        for (ComplexTypeMetadata joinedType : joinedTypes) {
            types.remove(joinedType);
        }
        List<TypedExpression> filteredFields = new LinkedList<TypedExpression>();
        for (TypedExpression expression : select.getSelectedFields()) {
            if (expression instanceof Field) {
                FieldMetadata fieldMetadata = ((Field) expression).getFieldMetadata();
                if (joinedTypes.contains(fieldMetadata.getContainingType())) {
                    TypeMapping mapping = mappings.getMappingFromDatabase(fieldMetadata.getContainingType());
                    filteredFields.add(new Alias(new StringConstant(StringUtils.EMPTY),
                            mapping.getUser(fieldMetadata).getName()));
                } else {
                    filteredFields.add(expression);
                }
            } else {
                filteredFields.add(expression);
            }
        }
        selectedFields.clear();
        selectedFields.addAll(filteredFields);
    }
    // Handle condition
    Condition condition = select.getCondition();
    if (condition == null) {
        throw new IllegalArgumentException("Expected a condition in select clause but got 0.");
    }
    // Create Lucene query (concatenates all sub queries together).
    FullTextSession fullTextSession = Search.getFullTextSession(session);
    Query parsedQuery = select.getCondition().accept(new LuceneQueryGenerator(types));
    // Create Hibernate Search query
    Set<Class> classes = new HashSet<Class>();
    for (ComplexTypeMetadata type : types) {
        String className = ClassCreator.getClassName(type.getName());
        try {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            classes.add(contextClassLoader.loadClass(className));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not find class '" + className + "'.", e);
        }
    }
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(parsedQuery,
            classes.toArray(new Class<?>[classes.size()]));
    // Very important to leave this null (would disable ability to search across different types)
    fullTextQuery.setCriteriaQuery(null);
    fullTextQuery.setSort(Sort.RELEVANCE); // Default sort (if no order by specified).
    query = EntityFinder.wrap(fullTextQuery, (HibernateStorage) storage, session, select.getTypes()); // ensures only MDM entity objects are returned.
    // Order by
    for (OrderBy current : select.getOrderBy()) {
        current.accept(this);
    }
    // Paging
    Paging paging = select.getPaging();
    paging.accept(this);
    pageSize = paging.getLimit();
    boolean hasPaging = pageSize < Integer.MAX_VALUE;
    if (!hasPaging) {
        return createResults(query.scroll(ScrollMode.FORWARD_ONLY));
    } else {
        return createResults(query.list());
    }
}

From source file:majordodo.worker.TaskModeAwareExecutorFactory.java

@Override
public TaskExecutor createTaskExecutor(String taskType, Map<String, Object> parameters) {
    String mode = (String) parameters.getOrDefault("mode", Task.MODE_DEFAULT);
    if (mode.equals(Task.MODE_EXECUTE_FACTORY)) {
        return inner.createTaskExecutor(taskType, parameters);
    }/*from   w ww.  j  a  v  a  2 s  . com*/
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        String parameter = (String) parameters.getOrDefault("parameter", "");
        if (parameter.startsWith("base64:")) {
            parameter = parameter.substring("base64:".length());
            byte[] serializedObjectData = Base64.getDecoder().decode(parameter);
            ByteArrayInputStream ii = new ByteArrayInputStream(serializedObjectData);
            ObjectInputStream is = new ObjectInputStream(ii) {
                @Override
                public Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                    try {
                        return tccl.loadClass(desc.getName());
                    } catch (Exception e) {
                    }
                    return super.resolveClass(desc);
                }

            };
            TaskExecutor res = (TaskExecutor) is.readUnshared();
            return res;
        } else if (parameter.startsWith("newinstance:")) {
            parameter = parameter.substring("newinstance:".length());
            URLClassLoader cc = (URLClassLoader) tccl;
            Class clazz = Class.forName(parameter, true, tccl);
            TaskExecutor res = (TaskExecutor) clazz.newInstance();
            return res;
        } else {
            throw new RuntimeException("bad parameter: " + parameter);
        }
    } catch (Exception err) {
        return new TaskExecutor() {
            @Override
            public String executeTask(Map<String, Object> parameters) throws Exception {
                throw err;
            }

        };
    }

}

From source file:com.liferay.wsrp.proxy.ServiceHandler.java

public Object doInvoke(Object proxy, Method method, Object[] args) throws Exception {

    String methodName = method.getName();

    if (_v2 && methodName.equals("getWSRP_v2_Markup_Service")) {
        WSRP_v2_Markup_Binding_SOAPStub markupService = new WSRP_v2_Markup_Binding_SOAPStub((URL) args[0],
                _serviceLocator);/*w w w . j  a  va  2  s .c om*/

        WSRP_v2_ServiceLocator wsrpV2ServiceLocator = (WSRP_v2_ServiceLocator) _serviceLocator;

        String markupServiceName = wsrpV2ServiceLocator.getWSRP_v2_Markup_ServiceWSDDServiceName();

        markupService.setPortName(markupServiceName);

        return markupService;
    }

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    URL bindingURL = (URL) args[0];

    int x = methodName.indexOf("_v2_") + 4;
    int y = methodName.lastIndexOf("_Service");

    String serviceName = methodName.substring(x, y);

    StringBundler sb = new StringBundler(7);

    sb.append(_OASIS_PACKAGE);
    sb.append(_version);
    sb.append(".bind.WSRP_");
    sb.append(_version);
    sb.append(StringPool.UNDERLINE);
    sb.append(serviceName);
    sb.append("_Binding_SOAPStub");

    Class<?> clazz = contextClassLoader.loadClass(sb.toString());

    args = new Object[] { bindingURL, getService() };

    Object stub = ConstructorUtils.invokeConstructor(clazz, args);

    sb = new StringBundler(5);

    sb.append("getWSRP_");
    sb.append(_version);
    sb.append(StringPool.UNDERLINE);
    sb.append(serviceName);
    sb.append("_ServiceWSDDServiceName");

    Object serviceWSDDServiceName = MethodUtils.invokeMethod(_serviceLocator, sb.toString(), null);

    MethodUtils.invokeMethod(stub, "setPortName", serviceWSDDServiceName);

    if (_v2) {
        return stub;
    }

    sb.setIndex(0);

    sb.append(_OASIS_PACKAGE);
    sb.append("v2.intf.WSRP_v2_");
    sb.append(serviceName);
    sb.append("_PortType");

    Class<?> proxyInterface = contextClassLoader.loadClass(sb.toString());

    sb.setIndex(0);

    sb.append(_WSRP_PROXY_PACKAGE);
    sb.append(serviceName);
    sb.append("ServiceHandler");

    clazz = contextClassLoader.loadClass(sb.toString());

    InvocationHandler invocationHandler = (InvocationHandler) ConstructorUtils.invokeConstructor(clazz, stub);

    return ProxyUtil.newProxyInstance(ServiceHandler.class.getClassLoader(),
            new Class[] { proxyInterface, Stub.class }, invocationHandler);
}

From source file:Classes.java

/**
 * This method acts equivalently to invoking classLoader.loadClass(className)
 * but it also supports primitive types and array classes of object types or
 * primitive types.//from w  ww  .ja  v a  2  s . co m
 * 
 * @param className
 *          the qualified name of the class or the name of primitive type or
 *          array in the same format as returned by the
 *          java.lang.Class.getName() method.
 * @param classLoader
 *          the ClassLoader used to load classes
 * @return the Class object for the requested className
 * 
 * @throws ClassNotFoundException
 *           when the <code>classLoader</code> can not find the requested
 *           class
 */
public static Class loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException {
    // ClassLoader.loadClass() does not handle primitive types:
    //
    // B byte
    // C char
    // D double
    // F float
    // I int
    // J long
    // S short
    // Z boolean
    // V void
    //
    if (className.length() == 1) {
        char type = className.charAt(0);
        if (type == 'B')
            return Byte.TYPE;
        if (type == 'C')
            return Character.TYPE;
        if (type == 'D')
            return Double.TYPE;
        if (type == 'F')
            return Float.TYPE;
        if (type == 'I')
            return Integer.TYPE;
        if (type == 'J')
            return Long.TYPE;
        if (type == 'S')
            return Short.TYPE;
        if (type == 'Z')
            return Boolean.TYPE;
        if (type == 'V')
            return Void.TYPE;
        // else throw...
        throw new ClassNotFoundException(className);
    }

    // Check for a primative type
    if (isPrimitive(className) == true)
        return (Class) Classes.PRIMITIVE_NAME_TYPE_MAP.get(className);

    // Check for the internal vm format: Lclassname;
    if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';')
        return classLoader.loadClass(className.substring(1, className.length() - 1));

    // first try - be optimistic
    // this will succeed for all non-array classes and array classes that have
    // already been resolved
    //
    try {
        return classLoader.loadClass(className);
    } catch (ClassNotFoundException e) {
        // if it was non-array class then throw it
        if (className.charAt(0) != '[')
            throw e;
    }

    // we are now resolving array class for the first time

    // count opening braces
    int arrayDimension = 0;
    while (className.charAt(arrayDimension) == '[')
        arrayDimension++;

    // resolve component type - use recursion so that we can resolve primitive
    // types also
    Class componentType = loadClass(className.substring(arrayDimension), classLoader);

    // construct array class
    return Array.newInstance(componentType, new int[arrayDimension]).getClass();
}

From source file:com.panet.imeta.job.JobEntryLoader.java

public JobEntryInterface getJobEntryClass(JobPlugin sp) throws KettleStepLoaderException {
    if (sp != null) {
        try {//from   w w w  . j  a  v a  2  s  .  c o  m
            Class<?> cl = null;
            switch (sp.getType()) {
            case JobPlugin.TYPE_NATIVE: {
                cl = Class.forName(sp.getClassname());
            }
                break;
            case JobPlugin.TYPE_PLUGIN: {
                ClassLoader ucl = getClassLoader(sp);

                // What's the protection domain of this class?
                // ProtectionDomain protectionDomain =
                // this.getClass().getProtectionDomain();

                // Load the class.
                // Thread.currentThread().setContextClassLoader(ucl);
                cl = ucl.loadClass(sp.getClassname());
            }
                break;
            default:
                throw new KettleStepLoaderException("Unknown plugin type : " + sp.getType());
            }

            JobEntryInterface res = (JobEntryInterface) cl.newInstance();

            if (sp.getType() == JobPlugin.TYPE_PLUGIN) {
                res.setPluginID(sp.getID());
            }

            res.setDescription(sp.getDescription());
            res.setName(sp.getID());
            res.setConfigId(sp.getID());

            // set the type
            if (res.getJobEntryType() == null)
                res.setJobEntryType(sp.getJobType());

            return res;
        } catch (ClassNotFoundException e) {
            throw new KettleStepLoaderException("Class not found", e);
        } catch (InstantiationException e) {
            throw new KettleStepLoaderException("Unable to instantiate class", e);
        } catch (IllegalAccessException e) {
            throw new KettleStepLoaderException("Illegal access to class", e);
        } catch (Throwable e) {
            throw new KettleStepLoaderException("Unexpected error loading class", e);
        }
    } else {
        throw new KettleStepLoaderException("No valid step/plugin specified (plugin=null).");
    }
}

From source file:lu.softec.xwiki.macro.internal.ClassRunnerMacro.java

protected String execute(ClassLoader loader, String className, ClassRunnerMacroParameters parameters,
        Object xcontext) throws MacroExecutionException {
    StringWriter stringWriter = new StringWriter();
    boolean hasArgs = (parameters.getRawProperties() != null);
    Map<String, Object> args = (hasArgs) ? parameters.getRawProperties() : new LinkedHashMap<String, Object>();

    Class<?> klass;/*ww w .jav a 2s.  c  om*/
    try {
        klass = loader.loadClass(className);
    } catch (ClassNotFoundException e) {
        throw new MacroExecutionException(e.getMessage(), e);
    }

    Method[] methods = klass.getMethods();
    Method run1 = null;
    Method run2 = null;
    Method run3 = null;
    Method setContext1 = null;
    Method setContext2 = null;
    Method getParser = null;
    for (Method m : methods) {
        if (m.getName().equals("run")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 1 && types[0].isAssignableFrom(stringWriter.getClass())) {
                run1 = m;
            } else if (types.length == 2 && types[0].isAssignableFrom(stringWriter.getClass())
                    && types[1].isAssignableFrom(xcontext.getClass())) {
                run2 = m;
            } else if (types.length == 3 && types[0].isAssignableFrom(stringWriter.getClass())
                    && types[1].isAssignableFrom(args.getClass())
                    && types[2].isAssignableFrom(xcontext.getClass())) {
                run3 = m;
            }
        } else if (m.getName().equals("setContext")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 1 && types[0].isAssignableFrom(xcontext.getClass())) {
                setContext1 = m;
            } else if (types.length == 2 && types[0].isAssignableFrom(args.getClass())
                    && types[1].isAssignableFrom(xcontext.getClass())) {
                setContext2 = m;
            }
        } else if (m.getName().equals("getParser")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 0) {
                getParser = m;
            }
        }
        if (run2 != null && run3 != null && setContext1 != null && setContext2 != null && getParser != null)
            break;
    }

    if (run2 == null && run3 == null) {
        throw new MacroExecutionException(
                "Unable to find the appropriate run(Writer,XWikiContext) or run(Writer,Map,XWikiContext) method in the class.");
    }

    try {
        Object obj = klass.newInstance();
        if (setContext2 != null && (hasArgs || setContext1 == null)) {
            setContext2.invoke(obj, args, xcontext);
        } else if (setContext1 != null) {
            setContext1.invoke(obj, xcontext);
        }
        if (setContext2 != null || setContext1 != null) {
            if (getParser != null) {
                String parser = null;
                parser = (String) getParser.invoke(obj);
                if (parser != null) {
                    parameters.setParser(parser);
                }
            }
            run1.invoke(obj, stringWriter);
        } else {
            if (run3 != null && (hasArgs || run2 == null)) {
                run3.invoke(obj, stringWriter, args, xcontext);
            } else {
                run2.invoke(obj, stringWriter, xcontext);
            }
        }
    } catch (Exception e) {
        throw new MacroExecutionException(e.getMessage(), e);
    }

    return (stringWriter.toString());
}