[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[stp-commits] r3314 - org.eclipse.stp.sca/trunk/org.eclipse.stp.sca.common.java/src/org/eclipse/stp/sca/common/java/utils

Author: sdrapeau
Date: 2009-09-15 06:35:25 -0400 (Tue, 15 Sep 2009)
New Revision: 3314

Modified:
   org.eclipse.stp.sca/trunk/org.eclipse.stp.sca.common.java/src/org/eclipse/stp/sca/common/java/utils/JDTUtils.java
Log:
Added copyFileEnclosedInJar(JarEntryFile transfer,File tmpFile) method

Modified: org.eclipse.stp.sca/trunk/org.eclipse.stp.sca.common.java/src/org/eclipse/stp/sca/common/java/utils/JDTUtils.java
===================================================================
--- org.eclipse.stp.sca/trunk/org.eclipse.stp.sca.common.java/src/org/eclipse/stp/sca/common/java/utils/JDTUtils.java	2009-09-15 08:40:17 UTC (rev 3313)
+++ org.eclipse.stp.sca/trunk/org.eclipse.stp.sca.common.java/src/org/eclipse/stp/sca/common/java/utils/JDTUtils.java	2009-09-15 10:35:25 UTC (rev 3314)
@@ -11,6 +11,9 @@
 
 package org.eclipse.stp.sca.common.java.utils;
 
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -23,8 +26,10 @@
 import org.eclipse.core.resources.IResource;
 import org.eclipse.core.resources.ResourcesPlugin;
 import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
 import org.eclipse.core.runtime.IStatus;
 import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Path;
 import org.eclipse.emf.common.util.BasicDiagnostic;
 import org.eclipse.emf.common.util.Diagnostic;
 import org.eclipse.emf.ecore.EObject;
@@ -38,374 +43,454 @@
 import org.eclipse.jdt.core.JavaModelException;
 import org.eclipse.jdt.core.ToolFactory;
 import org.eclipse.jdt.core.util.IClassFileReader;
+import org.eclipse.jdt.internal.core.JarEntryFile;
 import org.eclipse.jdt.ui.JavaUI;
 
 /**
- * Utility methods related to the JDT and that could be used in several SCA (related) tools.
+ * Utility methods related to the JDT and that could be used in several SCA
+ * (related) tools.
+ * 
  * @see JavaCore
  * @see JavaUI
  * @see org.eclipse.jdt.internal.corext.util.* for other JDT utility methods.
  * 
  * @author Vincent Zurczak - EBM WebSourcing
+ * @contributor Stephane Drapeau - Obeo: Added
+ *              copyFileEnclosedInJar(JarEntryFile transfer, java.io.File
+ *              tmpFile) method
  */
 public class JDTUtils {
-	
+
 	/**
-	 * Return all the classes implementing or extending the given class in the given project.
+	 * Return all the classes implementing or extending the given class in the
+	 * given project.
 	 * 
-	 * @param superClassName the interface or the class name
-	 * @param javaProject the java project containing the class
+	 * @param superClassName
+	 *            the interface or the class name
+	 * @param javaProject
+	 *            the java project containing the class
 	 * @return the list of classes implementing the given class
-	 * @throws JavaModelException 
+	 * @throws JavaModelException
 	 */
-	public static List<String> getImplementors( 
-			String superClassName, IJavaProject javaProject ) 
-	throws JavaModelException {
-		
-		List<String> classes = new ArrayList<String> ();
-		IType parentType = javaProject.findType( superClassName );
-		ITypeHierarchy hierarchy = parentType.newTypeHierarchy( javaProject, new NullProgressMonitor ());
-		IType[] types = hierarchy.getAllSubtypes( parentType );
-		for( IType t : types )
-			classes.add( t.getFullyQualifiedName());
+	public static List<String> getImplementors(String superClassName,
+			IJavaProject javaProject) throws JavaModelException {
 
+		List<String> classes = new ArrayList<String>();
+		IType parentType = javaProject.findType(superClassName);
+		ITypeHierarchy hierarchy = parentType.newTypeHierarchy(javaProject,
+				new NullProgressMonitor());
+		IType[] types = hierarchy.getAllSubtypes(parentType);
+		for (IType t : types)
+			classes.add(t.getFullyQualifiedName());
+
 		return classes;
 	}
-	
-	
+
 	/**
 	 * @param resources
 	 * @return
 	 */
-	public static IResource[] removeResourceFromBinaryFolders( IResource[] _resources ) {
-		
+	public static IResource[] removeResourceFromBinaryFolders(
+			IResource[] _resources) {
+
 		Map<IProject, IJavaProject> projects = new HashMap<IProject, IJavaProject>();
-		List<IResource> toKeep = new ArrayList<IResource> ();
-		for( IResource res : _resources ) {
-			
+		List<IResource> toKeep = new ArrayList<IResource>();
+		for (IResource res : _resources) {
+
 			// Get project
 			IProject p = res.getProject();
 			try {
-				if( ! p.isOpen())
-					p.open( new NullProgressMonitor ());
-			} catch( CoreException e1 ) {
+				if (!p.isOpen())
+					p.open(new NullProgressMonitor());
+			} catch (CoreException e1) {
 				e1.printStackTrace();
 				continue;
 			}
-				
-			// Get Java project and make sure the resource is not in an output folder
+
+			// Get Java project and make sure the resource is not in an output
+			// folder
 			try {
-				if( p.hasNature( JavaCore.NATURE_ID )) {
-					IJavaProject jp = projects.get( p );
-					if( jp == null ) {
-						jp = JavaCore.create( p );
-						projects.put( p, jp );
+				if (p.hasNature(JavaCore.NATURE_ID)) {
+					IJavaProject jp = projects.get(p);
+					if (jp == null) {
+						jp = JavaCore.create(p);
+						projects.put(p, jp);
 					}
-					
-					if( ! jp.getOutputLocation().isPrefixOf( res.getFullPath()))
-						toKeep.add( res );
-				}
-				else
-					toKeep.add( res );
-				
-			} catch( CoreException e ) {
+
+					if (!jp.getOutputLocation().isPrefixOf(res.getFullPath()))
+						toKeep.add(res);
+				} else
+					toKeep.add(res);
+
+			} catch (CoreException e) {
 				e.printStackTrace();
 			}
 		}
-		
-		IResource[] result = new IResource[ toKeep.size() ]; 
-		return toKeep.toArray( result );
+
+		IResource[] result = new IResource[toKeep.size()];
+		return toKeep.toArray(result);
 	}
-	
-	
+
 	/**
 	 * Get the referenced projects from a Java project.
-	 * <p>The result includes the argument project.</p>
+	 * <p>
+	 * The result includes the argument project.
+	 * </p>
 	 * 
 	 * @param javaProject
 	 * @return
 	 */
-	public static List<IJavaProject> getJavaProjectDependencies( IJavaProject javaProject ) {
-		
-		if( javaProject == null )
+	public static List<IJavaProject> getJavaProjectDependencies(
+			IJavaProject javaProject) {
+
+		if (javaProject == null)
 			return Collections.emptyList();
-		
-		List<IJavaProject> result = new ArrayList<IJavaProject> ();
-		result.add( javaProject );
-		
+
+		List<IJavaProject> result = new ArrayList<IJavaProject>();
+		result.add(javaProject);
+
 		String[] projectNames;
 		try {
 			projectNames = javaProject.getRequiredProjectNames();
-		} catch( JavaModelException e1 ) {
+		} catch (JavaModelException e1) {
 			e1.printStackTrace();
-			projectNames = new String[ 0 ];
+			projectNames = new String[0];
 		}
-		
-		for( String projectName : projectNames ) {					
-			IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( projectName );
+
+		for (String projectName : projectNames) {
+			IProject project = ResourcesPlugin.getWorkspace().getRoot()
+					.getProject(projectName);
 			try {
-				if( !project.exists() 
-						|| !project.isOpen() 
-						|| !project.hasNature( JavaCore.NATURE_ID ))								
+				if (!project.exists() || !project.isOpen()
+						|| !project.hasNature(JavaCore.NATURE_ID))
 					continue;
-				
-			} catch( CoreException e ) {
+
+			} catch (CoreException e) {
 				e.printStackTrace();
 				continue;
 			}
-			
-			IJavaProject p = JavaCore.create( project );
-			result.add( p );
+
+			IJavaProject p = JavaCore.create(project);
+			result.add(p);
 		}
-		
+
 		return result;
 	}
-	
-	
+
 	/**
 	 * Get the referenced projects from a Java project.
-	 * <p>The result includes the argument project.</p>
-	 * <p>If the project is not a Java project, then the result only contains this project.</p>
+	 * <p>
+	 * The result includes the argument project.
+	 * </p>
+	 * <p>
+	 * If the project is not a Java project, then the result only contains this
+	 * project.
+	 * </p>
 	 * 
 	 * @param project
-	 * @return 
+	 * @return
 	 */
-	public static List<IProject> getJavaProjectDependencies( IProject project ) {
-		
-		IJavaProject jp = getJavaProject( project );
-		if( jp != null ) {
-			List<IJavaProject> jps = getJavaProjectDependencies( jp );
-			List<IProject> result = new ArrayList<IProject>( jps.size());
-			for( IJavaProject jp2 : jps )
-				result.add( jp2.getProject());
+	public static List<IProject> getJavaProjectDependencies(IProject project) {
+
+		IJavaProject jp = getJavaProject(project);
+		if (jp != null) {
+			List<IJavaProject> jps = getJavaProjectDependencies(jp);
+			List<IProject> result = new ArrayList<IProject>(jps.size());
+			for (IJavaProject jp2 : jps)
+				result.add(jp2.getProject());
 			return result;
 		}
-		
-		List<IProject> result = new ArrayList<IProject>( 1 );
-		result.add( project );
+
+		List<IProject> result = new ArrayList<IProject>(1);
+		result.add(project);
 		return result;
 	}
-	
-	
+
 	/**
-     * Get the class path from Java project.
-     * @param javaProject
-     * @return the class path as a list of string locations.
-     */
-    public static List<String> getClasspath( IJavaProject javaProject, boolean getReferencedProjectClasspath ) {
-    	
-    	List<String> paths = new ArrayList<String> ();
-    	try {
-			if( javaProject != null ) {
-			
+	 * Get the class path from Java project.
+	 * 
+	 * @param javaProject
+	 * @return the class path as a list of string locations.
+	 */
+	public static List<String> getClasspath(IJavaProject javaProject,
+			boolean getReferencedProjectClasspath) {
+
+		List<String> paths = new ArrayList<String>();
+		try {
+			if (javaProject != null) {
+
 				IClasspathEntry[] entries = javaProject.getRawClasspath();
-				for( IClasspathEntry entry : entries ) {
-					switch( entry.getEntryKind()) {
-					
+				for (IClasspathEntry entry : entries) {
+					switch (entry.getEntryKind()) {
+
 					case IClasspathEntry.CPE_PROJECT:
-						if( !getReferencedProjectClasspath )
+						if (!getReferencedProjectClasspath)
 							break;
-						
+
 						String projectName = entry.getPath().toString();
-						IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( projectName );
-						IJavaProject jProject = JavaCore.create( project );
-						
-						List<String> subPaths = getClasspath( jProject, true );
-						paths.addAll( subPaths );
+						IProject project = ResourcesPlugin.getWorkspace()
+								.getRoot().getProject(projectName);
+						IJavaProject jProject = JavaCore.create(project);
+
+						List<String> subPaths = getClasspath(jProject, true);
+						paths.addAll(subPaths);
 						break;
-						
+
 					case IClasspathEntry.CPE_LIBRARY:
 						String path = entry.getPath().toString();
-						paths.add( path );
+						paths.add(path);
 						break;
-						
+
 					case IClasspathEntry.CPE_VARIABLE:
-						entry = JavaCore.getResolvedClasspathEntry( entry );
-						if( entry != null ) {
+						entry = JavaCore.getResolvedClasspathEntry(entry);
+						if (entry != null) {
 							path = entry.getPath().toString();
-							paths.add( path );
+							paths.add(path);
 						}
 						break;
 					}
 				}
 			}
-			
-		} catch( JavaModelException e ) {
+
+		} catch (JavaModelException e) {
 			e.printStackTrace();
 		}
-    	
+
 		return paths;
-    }
-    
-    
-    /**
-     * @param project an IProject instance
-     * @return the corresponding IJavaProject if project is a Java project, false otherwise.
-     */
-    public static IJavaProject getJavaProject( IProject project ) {
-    	
-    	try {
-			if( project.hasNature( JavaCore.NATURE_ID ))
-				return JavaCore.create( project );
-		} catch( CoreException e ) {
+	}
+
+	/**
+	 * @param project
+	 *            an IProject instance
+	 * @return the corresponding IJavaProject if project is a Java project,
+	 *         false otherwise.
+	 */
+	public static IJavaProject getJavaProject(IProject project) {
+
+		try {
+			if (project.hasNature(JavaCore.NATURE_ID))
+				return JavaCore.create(project);
+		} catch (CoreException e) {
 			e.printStackTrace();
 		}
-    	
-    	return null;
-    }
-    
-    
-    /**
-     * @param qualifiedName the Java qualified name
-     * @return an array containing the package name (index=0) and the class simple name (index=1).
-     */
-    public static String[] getQualifiedNameElements( String qualifiedName ) {
-		int index = qualifiedName.lastIndexOf( '.' );
-		if( index < 0 )
+
+		return null;
+	}
+
+	/**
+	 * @param qualifiedName
+	 *            the Java qualified name
+	 * @return an array containing the package name (index=0) and the class
+	 *         simple name (index=1).
+	 */
+	public static String[] getQualifiedNameElements(String qualifiedName) {
+		int index = qualifiedName.lastIndexOf('.');
+		if (index < 0)
 			return new String[] { "", qualifiedName }; //$NON-NLS-1$
 		else
-			return new String[] { qualifiedName.substring( 0, index ), qualifiedName.substring( index+1 )};
+			return new String[] { qualifiedName.substring(0, index),
+					qualifiedName.substring(index + 1) };
 	}
-    
-    
-    /**
+
+	/**
 	 * @param name
 	 * @param eo
 	 * @return null if no error was found, a diagnostic otherwise
 	 * @see JavaConventions#validateJavaTypeName(String, String, String)
 	 */
-	public static Diagnostic validateJavaTypeName( String name, EObject eo ) {
-		
-		IStatus status = JavaConventions.validateJavaTypeName( 
-				name, 
-				JavaCore.getOption( JavaCore.COMPILER_SOURCE ),
-				JavaCore.getOption( JavaCore.COMPILER_COMPLIANCE ));
-		
-		if( status.getCode() == IStatus.WARNING )
-			return new BasicDiagnostic ( Diagnostic.WARNING, "", 0, status.getMessage(), new Object[] { eo } ); //$NON-NLS-1$
-		else if( status.getCode() == IStatus.ERROR )
-			return new BasicDiagnostic ( Diagnostic.ERROR, "", 0, status.getMessage(), new Object[] { eo } ); //$NON-NLS-1$
-		
+	public static Diagnostic validateJavaTypeName(String name, EObject eo) {
+
+		IStatus status = JavaConventions.validateJavaTypeName(name, JavaCore
+				.getOption(JavaCore.COMPILER_SOURCE), JavaCore
+				.getOption(JavaCore.COMPILER_COMPLIANCE));
+
+		if (status.getCode() == IStatus.WARNING)
+			return new BasicDiagnostic(Diagnostic.WARNING,
+					"", 0, status.getMessage(), new Object[] { eo }); //$NON-NLS-1$
+		else if (status.getCode() == IStatus.ERROR)
+			return new BasicDiagnostic(Diagnostic.ERROR,
+					"", 0, status.getMessage(), new Object[] { eo }); //$NON-NLS-1$
+
 		return null;
 	}
-	
-	
+
 	/**
 	 * Checks whether the given class implements all the super interfaces.
 	 * <p>
-	 * If the class is not in the class path, then all the possible super classes are returned.
+	 * If the class is not in the class path, then all the possible super
+	 * classes are returned.
 	 * </p>
 	 * 
-	 * @param javaProject the Java project
-	 * @param className the class name
-	 * @param superClassNames the possible super class names (null is not allowed)
+	 * @param javaProject
+	 *            the Java project
+	 * @param className
+	 *            the class name
+	 * @param superClassNames
+	 *            the possible super class names (null is not allowed)
 	 * @return the list of super classes that className does not implement
 	 * @see #implementsOrExtendsAll(IJavaProject, String, String...)
 	 */
-	public static List<String> implementsOrExtendsAll( IJavaProject javaProject, String className, List<String> superClassNames ) {
-		
-		String[] scn = superClassNames.toArray( new String[ superClassNames.size()]);
-		return implementsOrExtendsAll( javaProject, className, scn );
+	public static List<String> implementsOrExtendsAll(IJavaProject javaProject,
+			String className, List<String> superClassNames) {
+
+		String[] scn = superClassNames.toArray(new String[superClassNames
+				.size()]);
+		return implementsOrExtendsAll(javaProject, className, scn);
 	}
-	
-	
+
 	/**
 	 * Checks whether the given class implements all the super interfaces.
 	 * <p>
-	 * If the class is not in the class path, then all the possible super classes are returned.
+	 * If the class is not in the class path, then all the possible super
+	 * classes are returned.
 	 * </p>
 	 * <p>
 	 * 
 	 * </p>
 	 * 
-	 * @param javaProject the Java project
-	 * @param className the class name
-	 * @param superClassNames the possible super class names (null is not allowed)
+	 * @param javaProject
+	 *            the Java project
+	 * @param className
+	 *            the class name
+	 * @param superClassNames
+	 *            the possible super class names (null is not allowed)
 	 * @return the list of super classes that className does not implement
 	 * @see #implementsOrExtendsAll(IJavaProject, String, List)
 	 */
-	public static List<String> implementsOrExtendsAll( IJavaProject javaProject, String className, String... superClassNames  ) {
-		
+	public static List<String> implementsOrExtendsAll(IJavaProject javaProject,
+			String className, String... superClassNames) {
+
 		List<String> notImplemented = new ArrayList<String>();
 		try {
-			IType iType = javaProject.findType( className );
-			if( iType == null )
-				return Arrays.asList( superClassNames );
-			
-			List<String> superInterfaces = new ArrayList<String> ();
-			for( String t : iType.getSuperInterfaceNames()) {
-				String[][] types = iType.resolveType( t );
-				if( types == null )
+			IType iType = javaProject.findType(className);
+			if (iType == null)
+				return Arrays.asList(superClassNames);
+
+			List<String> superInterfaces = new ArrayList<String>();
+			for (String t : iType.getSuperInterfaceNames()) {
+				String[][] types = iType.resolveType(t);
+				if (types == null)
 					continue;
-				
+
 				// FIXME: handle ambiguous cases
-				String pckName = types[ 0 ][ 0 ];
+				String pckName = types[0][0];
 				pckName += pckName.length() > 0 ? "." : ""; //$NON-NLS-1$ //$NON-NLS-2$
-				superInterfaces.add( pckName + types[ 0 ][ 1 ] );
+				superInterfaces.add(pckName + types[0][1]);
 			}
-		
-			for( String superClassName : superClassNames ) {
-				if( ! superInterfaces.contains( superClassName ))
-					notImplemented.add( superClassName );
+
+			for (String superClassName : superClassNames) {
+				if (!superInterfaces.contains(superClassName))
+					notImplemented.add(superClassName);
 			}
-			
-		} catch( JavaModelException e ) {
+
+		} catch (JavaModelException e) {
 			// nothing
 		}
-		
+
 		return notImplemented;
 	}
-	
-	
+
 	/**
 	 * Computes the class name from the given parameter.
 	 * <p>
-	 * If the parameter is an IResource, then it must be in
-	 * a Java project, and the class name will be computed.
+	 * If the parameter is an IResource, then it must be in a Java project, and
+	 * the class name will be computed.
 	 * </p>
 	 * <p>
-	 * If the parameter is an IClassFile, then it is in a Java project
-	 * and the class name can be computed.
+	 * If the parameter is an IClassFile, then it is in a Java project and the
+	 * class name can be computed.
 	 * </p>
 	 * <p>
 	 * Other types are not covered and the returned name will be <i>null</i>.
 	 * </p>
 	 * 
-	 * @param transfer the object whose class name must be computed
+	 * @param transfer
+	 *            the object whose class name must be computed
 	 * @return the class name, or null if it could not be computed
 	 */
-	public static String getClassName( Object transfer ) {
-		
+	public static String getClassName(Object transfer) {
+
 		IClassFile classFile = null;
-		if( transfer instanceof IFile ) {
+		if (transfer instanceof IFile) {
 			IFile file = (IFile) transfer;
-			if( ! "class".equals( file.getFileExtension()))
+			if (!"class".equals(file.getFileExtension()))
 				return null;
-			
-			IJavaProject jp = JDTUtils.getJavaProject( file.getProject());
-			if( jp != null )
-				classFile = JavaCore.createClassFileFrom( file );
-		}
-		else if( transfer instanceof IClassFile )
+
+			IJavaProject jp = JDTUtils.getJavaProject(file.getProject());
+			if (jp != null)
+				classFile = JavaCore.createClassFileFrom(file);
+		} else if (transfer instanceof IClassFile)
 			classFile = (IClassFile) transfer;
-		
 
 		// Does not work on class files - package name is always empty
 		// return cf.getType().getFullyQualifiedName();
 
 		IClassFileReader cfr = null;
-		if( classFile != null )
-			cfr = ToolFactory.createDefaultClassFileReader( classFile, IClassFileReader.CLASSFILE_ATTRIBUTES );
-		else if( transfer instanceof IFile ) {
+		if (classFile != null)
+			cfr = ToolFactory.createDefaultClassFileReader(classFile,
+					IClassFileReader.CLASSFILE_ATTRIBUTES);
+		else if (transfer instanceof IFile) {
 			String location = ((IFile) transfer).getLocation().toOSString();
-			cfr = ToolFactory.createDefaultClassFileReader( location, IClassFileReader.CLASSFILE_ATTRIBUTES );
+			cfr = ToolFactory.createDefaultClassFileReader(location,
+					IClassFileReader.CLASSFILE_ATTRIBUTES);
 		}
 
-		if( cfr != null ) {
-			String result = new String( cfr.getClassName());
-			return result.replaceAll( "/", "." );
+		if (cfr != null) {
+			String result = new String(cfr.getClassName());
+			return result.replaceAll("/", ".");
 		}
 
 		return null;
 	}
+
+	public static IResource copyFileEnclosedInJar(JarEntryFile transfer,
+			java.io.File tmpFile) {
+		IResource result = null;
+		try {
+			if (copyFile(transfer.getContents(), tmpFile)) {
+				ResourcesPlugin.getWorkspace().getRoot().refreshLocal(10, null);
+				IPath location = new Path("file:" + tmpFile.getAbsolutePath());
+				result = ResourcesPlugin.getWorkspace().getRoot().getFile(
+						location);
+			}
+		} catch (CoreException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		return result;
+	}
+
+	private static boolean copyFile(InputStream in, java.io.File tmpFile) {
+		boolean result = false;
+		FileOutputStream out = null;
+		try {
+			out = new FileOutputStream(tmpFile);
+			byte[] buf = new byte[1024];
+			int len;
+			while ((len = in.read(buf)) > 0) {
+				out.write(buf, 0, len);
+			}
+			result = true;
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} finally {
+			if (in != null) {
+				try {
+					in.close();
+				} catch (IOException e) {
+					// Empty
+				}
+			}
+			if (out != null) {
+				try {
+					out.close();
+				} catch (IOException e) {
+					// Empty
+				}
+			}
+		}
+		return result;
+	}
+
 }