Search in sources :

Example 61 with URLClassLoader

use of java.net.URLClassLoader in project OpenAM by OpenRock.

the class AdminToolLauncher method launchAdminTool.

private static void launchAdminTool(List args) throws Exception {
    String fullName = AdminToolLauncher.class.getName();
    int index = fullName.lastIndexOf('.');
    String shortClassName = fullName;
    if (index != -1) {
        shortClassName = fullName.substring(index + 1);
    }
    String classFileName = shortClassName + ".class";
    URL url = AdminToolLauncher.class.getResource(classFileName);
    if (url == null) {
        throw new Exception("Failed to locate resource: " + classFileName);
    }
    String urlString = url.toString();
    // This urlString is URL-encoded, decode it.
    urlString = URLDecoder.decode(urlString, "UTF-8");
    String jarFileName = null;
    String jarFilePath = null;
    if (urlString.startsWith(STR_JAR_FILE_URL_PREFIX)) {
        int entryIndex = urlString.indexOf('!');
        if (entryIndex != -1) {
            jarFilePath = urlString.substring(STR_JAR_FILE_URL_PREFIX.length(), entryIndex);
            int jarNameIndex = jarFilePath.lastIndexOf('/');
            if (jarNameIndex != -1) {
                jarFileName = jarFilePath.substring(jarNameIndex + 1);
            } else {
                jarFileName = jarFilePath;
            }
        } else {
            throw new Exception("Failed to locate jar entry in: " + urlString);
        }
    }
    if (jarFileName == null) {
        throw new Exception("Failed to locate launcher jar: " + urlString);
    }
    setLauncherJarFileName(jarFileName);
    ArrayList pathURLs = new ArrayList();
    String relativePath = STR_LIB_DIR_PREFIX + jarFileName;
    String productHome = jarFilePath.substring(0, jarFilePath.length() - relativePath.length());
    debug("product home=" + productHome);
    // allowed in Agent deployment directory.
    if (productHome.matches(".*[% #+].*")) {
        throw new IOException("Agent deployment directory may have special " + "character(% #+), rename it to a new directory name.");
    }
    // Product home must exist
    setProductHomeDir(getRequiredDirectory(productHome, false));
    // Product bin dir must exist
    setProductBinDir(getRequiredDirectory(productHome + STR_BIN_DIR_PREFIX, false));
    // Config dir must exist
    setProductConfigDir(getRequiredDirectory(productHome + STR_CONFIG_DIR_PREFIX, false));
    // Data dir: create if does not exist
    setProductDataDir(getRequiredDirectory(productHome + STR_DATA_DIR_PREFIX, true));
    // Etc dir: create if does not exist
    setProductEtcDir(getRequiredDirectory(productHome + STR_ETC_DIR_PREFIX, true));
    // Set JCE dir
    if (isDirectoryExisting(productHome + STR_JCE_DIR_PREFIX)) {
        setProductJCEDir(getRequiredDirectory(productHome + STR_JCE_DIR_PREFIX, false));
    }
    // Set JSSE dir
    if (isDirectoryExisting(productHome + STR_JSSE_DIR_PREFIX)) {
        setProductJSSEDir(getRequiredDirectory(productHome + STR_JSSE_DIR_PREFIX, false));
    }
    // Lib dir must exist
    setProductLibDir(getRequiredDirectory(productHome + STR_LIB_DIR_PREFIX, false));
    // Locale dir must exist
    setProductLocaleDir(getRequiredDirectory(productHome + STR_LOCALE_DIR_PREFIX, false));
    // pathURLs.add(getProductLocaleDir().toURL());
    // Logs dir: create if does not exist
    setProductLogsDir(getRequiredDirectory(productHome + STR_LOGS_DIR_PREFIX, true));
    initJavaVersion();
    ArrayList excludedFileList = new ArrayList();
    excludedFileList.add(getLauncherJarFileName());
    excludedFileList.add(STR_JDK_LOGGING_JAR_NAME);
    ArrayList pathElements = new ArrayList();
    addFilePaths(getProductLibDir(), pathElements, pathURLs, excludedFileList);
    pathElements.add(getProductLocaleDir().getAbsolutePath());
    pathURLs.add(getProductLocaleDir().toURL());
    pathElements.add(getProductConfigDir().getAbsolutePath());
    pathURLs.add(getProductConfigDir().toURL());
    if (!isJDK14OrAbove()) {
        addFilePaths(getProductJCEDir(), pathElements, pathURLs);
        addFilePaths(getProductJSSEDir(), pathElements, pathURLs);
        System.setProperty(IAdminTool.PROP_REGISTER_JCE_PROVIDER, "true");
        System.setProperty(IAdminTool.PROP_REGISTER_JSSE_PROVIDER, "true");
    }
    setClassPathElements(pathElements);
    initializeClassPath(pathElements);
    debug("Path URLS: " + pathURLs);
    URL[] pathEntries = new URL[pathURLs.size()];
    System.arraycopy(pathURLs.toArray(), 0, pathEntries, 0, pathURLs.size());
    URLClassLoader loader = new URLClassLoader(pathEntries);
    Thread.currentThread().setContextClassLoader(loader);
    debug("Context thread loader has been set.");
    Class toolsConfiguration = null;
    try {
        toolsConfiguration = loader.loadClass(STR_TOOLS_CONFIGURATION_CLASSNAME);
    } catch (Exception ex) {
        System.out.println("Error: the Exception might be caused by " + "special character in Agent deployment directory.");
        throw ex;
    }
    // Passing null for parameterTypes because there are no arguments and
    // it is a static method - hence no instance of class.
    Class[] parameterTypes = {};
    Method toolsMethod = toolsConfiguration.getDeclaredMethod(STR_TOOLS_CONFIGURATION_METHODNAME, parameterTypes);
    // Since the call is for static method, the first parameter to the
    // invoke method is null.
    Object[] methodArguments = {};
    IAdminTool adminTool = (IAdminTool) toolsMethod.invoke(null, methodArguments);
    adminTool.run(args);
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) Method(java.lang.reflect.Method) URL(java.net.URL) IOException(java.io.IOException) URLClassLoader(java.net.URLClassLoader)

Example 62 with URLClassLoader

use of java.net.URLClassLoader in project tdi-studio-se by Talend.

the class JavaCommandController method createControl.

/*
     * (non-Javadoc)
     * 
     * @see
     * org.talend.designer.core.ui.editor.properties.controllers.AbstractElementPropertySectionController#createControl
     * (org.eclipse.swt.widgets.Composite, org.talend.core.model.process.IElementParameter, int, int, int,
     * org.eclipse.swt.widgets.Control)
     */
@Override
public Control createControl(Composite subComposite, final IElementParameter param, int numInRow, int nbInRow, int top, Control lastControl) {
    Button btnEdit;
    //$NON-NLS-1$
    btnEdit = getWidgetFactory().createButton(subComposite, "", SWT.PUSH);
    btnEdit.setImage(ImageProvider.getImage(CoreUIPlugin.getImageDescriptor(DOTS_BUTTON)));
    FormData data;
    btnEdit.setData(NAME, JAVA_COMMAND);
    btnEdit.setData(PARAMETER_NAME, param.getName());
    btnEdit.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }

        @Override
        public void widgetSelected(SelectionEvent e) {
            // execute Java Command
            ElementParameter fullParam = (ElementParameter) param;
            File jar;
            URL url;
            try {
                List<URL> listURL = new ArrayList<URL>();
                ILibraryManagerService libManager = (ILibraryManagerService) GlobalServiceRegister.getDefault().getService(ILibraryManagerService.class);
                IFolder javaLibFolder = null;
                if (GlobalServiceRegister.getDefault().isServiceRegistered(IRunProcessService.class)) {
                    IRunProcessService processService = (IRunProcessService) GlobalServiceRegister.getDefault().getService(IRunProcessService.class);
                    ITalendProcessJavaProject talendProcessJavaProject = processService.getTalendProcessJavaProject();
                    if (talendProcessJavaProject != null) {
                        javaLibFolder = talendProcessJavaProject.getLibFolder();
                    }
                }
                if (javaLibFolder == null) {
                    return;
                }
                for (String jarString : fullParam.getJar().split(";")) {
                    IPath libPath = javaLibFolder.getLocation();
                    libManager.retrieve(jarString, libPath.toPortableString(), new NullProgressMonitor());
                    jar = libPath.append(jarString).toFile();
                    url = jar.toURL();
                    listURL.add(url);
                }
                URLClassLoader urlClassLoader = new URLClassLoader(listURL.toArray(new URL[0]));
                Class<?> classLoaded = Class.forName(fullParam.getJavaClass(), true, urlClassLoader);
                Object object = classLoaded.newInstance();
                List<String> args = new ArrayList<String>();
                for (String arg : fullParam.getArgs()) {
                    args.add(ElementParameterParser.parse(elem, arg));
                }
                for (Method method : classLoaded.getDeclaredMethods()) {
                    if (method.getName().equals(fullParam.getJavaFunction())) {
                        Object[] arglist = new Object[1];
                        arglist[0] = args.toArray(new String[0]);
                        method.invoke(object, arglist);
                    }
                }
            } catch (Exception e1) {
                MessageBoxExceptionHandler.process(e1);
            }
        }
    });
    if (elem instanceof Node) {
        btnEdit.setToolTipText(VARIABLE_TOOLTIP + param.getVariableName());
    }
    CLabel labelLabel = getWidgetFactory().createCLabel(subComposite, param.getDisplayName());
    data = new FormData();
    if (lastControl != null) {
        data.left = new FormAttachment(lastControl, 0);
    } else {
        data.left = new FormAttachment((((numInRow - 1) * MAX_PERCENT) / nbInRow), 0);
    }
    data.top = new FormAttachment(0, top);
    labelLabel.setLayoutData(data);
    if (numInRow != 1) {
        labelLabel.setAlignment(SWT.RIGHT);
    }
    // **************************
    data = new FormData();
    int currentLabelWidth = STANDARD_LABEL_WIDTH;
    GC gc = new GC(labelLabel);
    Point labelSize = gc.stringExtent(param.getDisplayName());
    gc.dispose();
    if ((labelSize.x + ITabbedPropertyConstants.HSPACE) > currentLabelWidth) {
        currentLabelWidth = labelSize.x + ITabbedPropertyConstants.HSPACE;
    }
    if (numInRow == 1) {
        if (lastControl != null) {
            data.left = new FormAttachment(lastControl, currentLabelWidth);
            data.right = new FormAttachment(lastControl, currentLabelWidth + STANDARD_BUTTON_WIDTH);
        } else {
            data.left = new FormAttachment(0, currentLabelWidth);
            data.right = new FormAttachment(0, currentLabelWidth + STANDARD_BUTTON_WIDTH);
        }
    } else {
        data.left = new FormAttachment(labelLabel, 0, SWT.RIGHT);
        data.right = new FormAttachment(labelLabel, STANDARD_BUTTON_WIDTH, SWT.RIGHT);
    }
    data.top = new FormAttachment(0, top);
    btnEdit.setLayoutData(data);
    // **************************
    hashCurControls.put(param.getName(), btnEdit);
    Point initialSize = btnEdit.computeSize(SWT.DEFAULT, SWT.DEFAULT);
    dynamicProperty.setCurRowSize(initialSize.y + ITabbedPropertyConstants.VSPACE);
    return btnEdit;
}
Also used : CLabel(org.eclipse.swt.custom.CLabel) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IRunProcessService(org.talend.designer.runprocess.IRunProcessService) Node(org.talend.designer.core.ui.editor.nodes.Node) URL(java.net.URL) ITalendProcessJavaProject(org.talend.core.runtime.process.ITalendProcessJavaProject) IElementParameter(org.talend.core.model.process.IElementParameter) ElementParameter(org.talend.designer.core.model.components.ElementParameter) ILibraryManagerService(org.talend.core.ILibraryManagerService) Button(org.eclipse.swt.widgets.Button) SelectionEvent(org.eclipse.swt.events.SelectionEvent) ArrayList(java.util.ArrayList) List(java.util.List) GC(org.eclipse.swt.graphics.GC) FormAttachment(org.eclipse.swt.layout.FormAttachment) FormData(org.eclipse.swt.layout.FormData) IPath(org.eclipse.core.runtime.IPath) Method(java.lang.reflect.Method) Point(org.eclipse.swt.graphics.Point) Point(org.eclipse.swt.graphics.Point) URLClassLoader(java.net.URLClassLoader) File(java.io.File) SelectionListener(org.eclipse.swt.events.SelectionListener) IFolder(org.eclipse.core.resources.IFolder)

Example 63 with URLClassLoader

use of java.net.URLClassLoader in project zm-mailbox by Zimbra.

the class L10nUtil method getClassLoader.

private static ClassLoader getClassLoader(String directory) {
    ClassLoader classLoader = null;
    try {
        URL[] urls = new URL[] { new File(directory).toURL() };
        classLoader = new URLClassLoader(urls);
    } catch (MalformedURLException e) {
        try {
            ZimbraLog.system.fatal("Unable to initialize localization", e);
        } finally {
            Runtime.getRuntime().halt(1);
        }
    }
    return classLoader;
}
Also used : MalformedURLException(java.net.MalformedURLException) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) File(java.io.File) URL(java.net.URL)

Example 64 with URLClassLoader

use of java.net.URLClassLoader in project yyl_example by Relucent.

the class JavaCompilerTest method main.

//创建一个 HelloWorld 类
public static void main(String[] args) throws Exception {
    //类名
    String className = "HelloWorld";
    //类的源码
    String source = //
    "" + "public class " + className + //
    " {" + //
    " public String toString() {" + //
    "  return \"HelloWorld\";" + //
    " }" + //
    "}" + "";
    boolean success = compile(className, source);
    if (success) {
        URLClassLoader classLoader = new URLClassLoader(new URL[] { new File(tempdir).toURI().toURL() }) {

            //加上这个方法是为了在ClassLoader被GC的时候够输出信息
            protected void finalize() throws Throwable {
                System.out.println("URLClassLoader -> Finalize!");
            }
        };
        Class<?> clazz = classLoader.loadClass(className);
        System.out.println(clazz.newInstance());
        classLoader.close();
    }
    //没有对HelloWorld的引用,所以URLClassLoader能够被回收
    System.gc();
    //等待回收
    Thread.sleep(1000);
}
Also used : URLClassLoader(java.net.URLClassLoader) File(java.io.File)

Example 65 with URLClassLoader

use of java.net.URLClassLoader in project cubrid-manager by CUBRID.

the class ClassLoaderManager method getClassLoader.

/**
	 * getClassLoader
	 * 
	 * @param file full name of a file
	 * @return URLClassLoader
	 */
public ClassLoader getClassLoader(String file) {
    synchronized (this) {
        try {
            final URL[] us;
            File file2 = new File(file);
            ClassLoader result = path2Loader.get(file2.getCanonicalPath());
            if (result != null) {
                return result;
            }
            us = new URL[] { file2.toURI().toURL() };
            result = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {

                public URLClassLoader run() {
                    return new URLClassLoader(us);
                }
            });
            path2Loader.put(file2.getCanonicalPath(), result);
            return result;
        } catch (Exception e) {
            return null;
        }
    }
}
Also used : PrivilegedAction(java.security.PrivilegedAction) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) File(java.io.File) URL(java.net.URL)

Aggregations

URLClassLoader (java.net.URLClassLoader)1351 URL (java.net.URL)872 File (java.io.File)514 Test (org.junit.Test)317 IOException (java.io.IOException)256 ArrayList (java.util.ArrayList)202 MalformedURLException (java.net.MalformedURLException)186 Method (java.lang.reflect.Method)177 InvocationTargetException (java.lang.reflect.InvocationTargetException)68 JarFile (java.util.jar.JarFile)54 InputStream (java.io.InputStream)50 HashSet (java.util.HashSet)49 HashMap (java.util.HashMap)44 URISyntaxException (java.net.URISyntaxException)41 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)35 Path (java.nio.file.Path)33 QuickTest (com.hazelcast.test.annotation.QuickTest)32 Test (org.junit.jupiter.api.Test)28 URI (java.net.URI)27 List (java.util.List)27