package org.wso2.carbon.classloading; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; public class Main { public static void main(String[] args) throws ClassNotFoundException, MalformedURLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("file:///home/shameera/Desktop/gson-2.2.4.jar")}); Class gsonClass = urlClassLoader.loadClass("com.google.gson.Gson"); Constructor constructor = gsonClass.getConstructor(); Object gsonObj = constructor.newInstance(); Method method = gsonClass.getMethod("toJson",Object.class); Object returnObj = method.invoke(gsonObj, new Person()); String jsonString = (String)returnObj; System.out.println(jsonString); } }
classpath
Listar el classpath
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.commons.io.IOUtils; import es.depontevedra.soap.interoperabilidad.identidad.services.reflections.ClassSearchUtils; import es.depontevedra.soap.interoperabilidad.identidad.services.reflections.ReflectionsLibrary; /* * Utilizacion para comprobar qué clases y librerias se cargan en el classpath de la aplicación. * Cuando tienes problemas con librerias, puedes listar el classpath y comprobar las clases que se llaman igual * o las librerias que son similares pero con diferentes versiones. * * <dependencies> <!-- listar classpath --> <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.9-RC1</version> </dependency> <!-- fin --> */ public class ClasspathLog { private static final String FILE_PATH = "./repository/deployment/server/webapps/STRATOS_ROOT/wso2Classpath.log"; public static void listaLibrerias() throws IOException { FileOutputStream fop = null; try{ IOUtils.write("======================================================n", fop); File file = new File(FILE_PATH); fop = new FileOutputStream(file); List<?> list = ClassSearchUtils.searchClassPath("", ""); for(Object object: list){ if(null != object){ IOUtils.write(object.toString() + "n", fop); } } IOUtils.write("======================================================n", fop); IOUtils.write(ReflectionsLibrary.getAllResources(""), fop); IOUtils.write("======================================================n", fop); IOUtils.write(ReflectionsLibrary.getAllClasses(""), fop); IOUtils.write("======================================================n", fop); }finally{ if(fop != null) IOUtils.closeQuietly(fop); } } }
public class ReflectionsLibrary { public static String getAllResources(String packageStr){ String str = ""; Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(packageStr)) .setScanners(new ResourcesScanner())); Store store= reflections.getStore(); str += "============= Existen " + store.getValuesCount() + ", elementos.n"; str = print(str, store); return str; } public static String getAllClasses(String packageStr){ String str = ""; Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(packageStr)) .setScanners(new ClassScanner())); Store store= reflections.getStore(); str += "============= Existen " + store.getValuesCount() + ", clases.n"; str = print(str, store); return str; } private static String print(String str, Store store) { Map<String, Multimap<String, String>> map = store.getStoreMap(); for(Entry<String, Multimap<String, String>> entry: map.entrySet()){ str += "=================="; Multimap<String, String> value = entry.getValue(); for( Entry<String, String> entry2: value.entries()){ str += entry2.getValue() + "n"; } str += "=================================================="; } return str; } }
public class ClassScanner extends AbstractScanner{ @Override public void scan(Object cls) { @SuppressWarnings("unchecked") final String className = getMetadataAdapter().getClassName(cls); if(className != null) getStore().put(className, className); } }
package es.depontevedra.soap.interoperabilidad.identidad.services.reflections; import java.awt.HeadlessException; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Logger; @SuppressWarnings("rawtypes") public class ClassSearchUtils { private static final Logger log = Logger.getAnonymousLogger(); /** * Classloader to be used to obtain resources from file system. */ private ClassLoader classloader; /** * List of the resource found in the classpath. */ private ArrayList list; /** * Extension of the resource to be found in the classpath. */ private String extension; private String prefix; /** * Search for the resource with the extension in the classpath. Method * self-instantiate factory for every call to ensure thread safety. * @param extension Mandatory extension of the resource. If all resources * are required extension should be empty string. Null extension is not * allowed and will cause method to fail. * @return List of all resources with specified extension. */ @SuppressWarnings("unchecked") public static List<Class<?>> searchClassPath(String prefix) { return searchClassPath(prefix, ".class"); } /** * Search for the resource with the extension in the classpath. Method * self-instantiate factory for every call to ensure thread safety. * @param extension Mandatory extension of the resource. If all resources * are required extension should be empty string. Null extension is not * allowed and will cause method to fail. * @return List of all resources with specified extension. */ public static List searchClassPath(String prefix, String extension) { ClassSearchUtils factory = new ClassSearchUtils(); factory.prefix = prefix; return factory.find(extension); } /** * Search for the resource with the extension in the classpath. * @param extension Mandatory extension of the resource. If all resources * are required extension should be empty string. Null extension is not * allowed and will cause method to fail. * @return List of all resources with specified extension. */ @SuppressWarnings("unchecked") private List<Class<?>> find(String extension) { this.extension = extension; this.list = new ArrayList(); this.classloader = this.getClass().getClassLoader(); String classpath = System.getProperty("java.class.path"); try { Method method = this.classloader.getClass().getMethod("getClassPath", (Class<?>) null); if (method != null) { classpath = (String) method.invoke(this.classloader, (Object) null); } } catch (Exception e) { // ignore } if (classpath == null) { classpath = System.getProperty("java.class.path"); } StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); String token; File dir; String name; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); dir = new File(token); if (dir.isDirectory()) { lookInDirectory("", dir); } if (dir.isFile()) { name = dir.getName().toLowerCase(); if (name.endsWith(".zip") || name.endsWith(".jar")) { this.lookInArchive(dir); } } } return this.list; } /** * @param name Name of to parent directories in java class notation (dot * separator) * @param dir Directory to be searched for classes. */ @SuppressWarnings("unchecked") private void lookInDirectory(String name, File dir) { log.fine( "Looking in directory [" + dir.getName() + "]."); File[] files = dir.listFiles(); File file; String fileName; final int size = files.length; for (int i = 0; i < size; i++) { file = files[i]; fileName = file.getName(); if (file.isFile() && fileName.toLowerCase().endsWith(this.extension)) { try { if (this.extension.equalsIgnoreCase(".class")) { fileName = fileName.substring(0, fileName.length() - 6); // filter ignored resources if (!(name + fileName).startsWith(this.prefix)) { continue; } log.fine( "Found class: [" + name + fileName + "]."); this.list.add(Class.forName(name + fileName)); } else { this.list.add( this.classloader.getResource( name.replace('.', File.separatorChar) + fileName)); } } catch (ClassNotFoundException e) { // ignore } catch (NoClassDefFoundError e) { //ignore too } catch (ExceptionInInitializerError e) { if (e.getCause() instanceof HeadlessException) { // running in headless env ... ignore } else { throw e; } } } // search recursively. // I don't like that but we will see how it will work. if (file.isDirectory()) { lookInDirectory(name + fileName + ".", file); } } } /** * Search archive files for required resource. * @param archive Jar or zip to be searched for classes or other resources. */ @SuppressWarnings("unchecked") private void lookInArchive(File archive) { log.fine( "Looking in archive [" + archive.getName() + "] for extension [" + this.extension + "]."); JarFile jarFile = null; try { jarFile = new JarFile(archive); } catch (IOException e) { log.warning( "Non fatal error. Unable to read jar item."); return; } Enumeration entries = jarFile.entries(); JarEntry entry; String entryName; while (entries.hasMoreElements()) { entry = (JarEntry) entries.nextElement(); entryName = entry.getName(); if (entryName.toLowerCase().endsWith(this.extension)) { try { if (this.extension.equalsIgnoreCase(".class")) { // convert name into java classloader notation entryName = entryName.substring(0, entryName.length() - 6); entryName = entryName.replace('/', '.'); // filter ignored resources if (!entryName.startsWith(this.prefix)) { continue; } log.fine( "Found class: [" + entryName + "]. "); this.list.add(Class.forName(entryName)); } else { this.list.add(this.classloader.getResource(entryName)); log.fine( "Found appropriate resource with name [" + entryName + "]. Resource instance:" + this.classloader.getResource(entryName)); } } catch (Throwable e) { // ignore log.warning( "Unable to load resource [" + entryName + "] form file [" + archive.getAbsolutePath() + "]."); } } } } public static void main(String[] args) { List list = ClassSearchUtils.searchClassPath("", ""); for(Object object: list){ System.out.println(object); } } }
javac classpath multiple jars
Tengo esto en mi directorio:
CividasSara.jar Main.java cividas.jar cividasnotifications.jar ontimizeEN.jar ontimizeWeb.jar salida.out util-java.jar workflowEN.jara
Quiero compilar Main.java (crear Main.class):
WINDOWS javac -cp "cividas.jar;cividasnotifications.java;CividasSara.jar;ontimizeEN.jar;ontimizeWeb.jar;util-java.jar;workflowEN.jar;." Main.java LINUX javac -cp "cividas.jar:cividasnotifications.java:CividasSara.jar:ontimizeEN.jar:ontimizeWeb.jar:util-java.jar:workflowEN.jar:." Main.java
Con lo que ya se ha generado el compilado:
CividasSara.jar Main.class Main.java cividas.jar cividasnotifications.jar ontimizeEN.jar ontimizeWeb.jar salida.out util-java.jar workflowEN.jara
Ahora quiero ejecutarlo:
WINDOWS java -cp "cividas.jar;cividasnotifications.java;CividasSara.jar;ontimizeEN.jar;ontimizeWeb.jar;util-java.jar;workflowEN.jar;." Main LINUX java -cp "cividas.jar:cividasnotifications.java:CividasSara.jar:ontimizeEN.jar:ontimizeWeb.jar:util-java.jar:workflowEN.jar:." Main
ANEXO I
Ejecucion de una clase, pasando un parametro como argumento. Mantenemos las librerias en el classpath.
$ java -cp "cividas.jar:cividasnotifications.java:CividasSara.jar:ontimizeEN.jar:ontimizeWeb.jar:util-java.jar:workflowEN.jar:." es.tecnocom.tsafirma.AFirmaImpl Factura-e_2013092520130925.xml
ANEXO II
El Anexo I en un script bash.
#!/bin/bash java -cp "bduac.jar:cividas.jar:cividasnotifications.jar:CividasSara.jar:commons-beanutils.jar:commons-collections.jar:commons-digester.jar:commons-fileupload.jar:commons-io.jar:commons-lang.jar:commons-logging.jar:jboss-el-2.0.0.GA.jar:jdom-2.0.1.jar:jsf-api-2.1.3-b02.jar:jsf-impl-2.1.3-b02.jar:jstl-1.2.jar:liferay-faces-bridge-api-3.1.1-ga2.jar:liferay-faces-bridge-impl-3.1.1-ga2.jar:liferay-faces-portal-3.1.1-ga2.jar:liferay-faces-util-3.1.1-ga2.jar:log4j.jar:Main.class:Main.java:ontimizeEN.jar:ontimizeWeb.jar:recaptcha4j-0.0.7.jar:util-bridges.jar:util-java.jar:util-taglib.jar:workflowEN.jar:portal-service-6.1.1.jar:tsafirma.jar:." es.tecnocom.tsafirma.AFirmaImpl $1 >> logPruebaSelladoTiempo.log && less -Ss logPruebaSelladoTiempo.log
tambien se puede poner al final en lugar de less: «tail -2», para mostrar solo el resultado
Hay que dar permisos, y ejecutar…
chmod 775 ejecuta.sh ./ejecuta.sh ficheroASellar.xml
List java classpath
public static void listURL(){ URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); for(URL url: loader.getURLs()){ System.out.println(url.toString()); } }
List springframework classpath
in applicationContext-XX.xml
<bean id="pathMatchingResourcePatternResolver" class="org.springframework.core.io.support.PathMatchingResourcePatternResolver" />
in your class:
@Autowired @Qualifier("pathMatchingResourcePatternResolver") private PathMatchingResourcePatternResolver path; public void method(...) throws Exception { URLClassLoader loader = (URLClassLoader) path.getClassLoader(); for(URL url: loader.getURLs()){ System.out.println(url.toString()); } // ...