Utils.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
eclipseme.core.internal.utils |
![]() |
![]() |
EclipseME |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/**
* Copyright (c) 2003-2005 Craig Setera
* All Rights Reserved.
* Licensed under the Eclipse Public License - v 1.0
* For more information see http://www.eclipse.org/legal/epl-v10.html
*/
package eclipseme.core.internal.utils;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.IStreamListener;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.core.model.IStreamMonitor;
import org.eclipse.debug.core.model.IStreamsProxy;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.BinaryType;
import org.eclipse.jdt.internal.core.JavaModel;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.osgi.service.datalocation.Location;
import eclipseme.core.IEclipseMECoreConstants;
import eclipseme.core.internal.EclipseMECorePlugin;
/**
* Various utility functions.
* <p />
* Copyright (c) 2003-2005 Craig Setera<br>
* All Rights Reserved.<br>
* Licensed under the Eclipse Public License - v 1.0<p/>
* <br>
* $Revision: 1.25 $
* <br>
* $Date: 2006/11/26 21:41:57 $
* <br>
* @author Craig Setera
*/
public class Utils {
// TODO This should probably be handled better...
private static final String PRIVATE_CONFIGURATION =
"org.eclipse.debug.ui.private";
// Private default file filter
private static final FileFilter DEFAULT_FILTER = new FileFilter() {
public boolean accept(File pathname) {
// Default is to copy all files
return true;
}
};
// Copy buffer
private static final byte[] buffer = new byte[1024];
// Track whether the file system is case sensitive
private static boolean caseSensitivityChecked;
private static boolean caseSensitiveFileSystem;
/**
* Return a boolean indicating whether the specified paths
* point to the same file.
*
* @param path1
* @param path2
* @return
* @throws CoreException
*/
public static boolean arePathTargetsEqual(IPath path1, IPath path2)
throws CoreException
{
boolean equal = false;
File file1 = getPathTargetFile(path1);
File file2 = getPathTargetFile(path2);
if ((file1 != null) && (file2 != null)) {
equal = file1.equals(file2);
}
return equal;
}
/**
* Clear the specified container of all resources recursively.
*
* @param container
* @param monitor
* @throws CoreException
*/
public static void clearContainer(IContainer container, IProgressMonitor monitor)
throws CoreException
{
if (container.exists()) {
IResource[] resources = container.members();
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
if (resource instanceof IContainer) {
clearContainer((IContainer) resource, monitor);
resource.delete(true, monitor);
} else {
resource.delete(true, monitor);
}
}
}
}
/**
* Copy from the specified source to the specified destination,
* recursively as necessary.
*
* @param source
* @param destination
* @throws IOException
*/
public static void copy(File source, File destination)
throws IOException
{
copy(source, destination, null);
}
/**
* Copy from the specified source to the specified destination,
* recursively as necessary. The file filter will be used to
* determine what files will be copied along the way.
*
* @param source
* @param destination
* @param filter
* @throws IOException
*/
public static void copy(File source, File destination, FileFilter filter)
throws IOException
{
if (source.exists()) {
if (source.isDirectory()) {
copyDirectory(source, destination, filter);
} else {
copyFile(source, destination, filter);
}
}
}
/**
* Copy the specified directory and all of its contents recursively
* to the specified destination.
*
* @param source
* @param destination
* @param filter
* @throws IOException
*/
public static void copyDirectory(File source, File destination, FileFilter filter)
throws IOException
{
if (filter == null) filter = DEFAULT_FILTER;
if (source.exists() && source.isDirectory() && filter.accept(source)) {
destination.mkdirs();
File[] sources = source.listFiles();
for (int i = 0; i < sources.length; i++) {
File newSource = sources[i];
File newDestination = new File(destination, newSource.getName());
if (newSource.isDirectory()) {
copyDirectory(newSource, newDestination, filter);
} else {
copyFile(newSource, newDestination, filter);
}
}
}
}
/**
* Copy the specified source file into the specified target file.
*
* @param sourceFile
* @param targetFile
* @throws IOException
* @throws CoreException
*/
public static void copyFile(IFile sourceFile, IFile targetFile)
throws IOException, CoreException
{
copyFile(
sourceFile.getLocation().toFile(),
targetFile.getLocation().toFile(),
null);
}
/**
* Copy the specified source file into the specified target file.
*
* @param sourceFile
* @param targetFile
* @param filter
* @throws IOException
*/
public static void copyFile(File sourceFile, File targetFile, FileFilter filter)
throws IOException
{
if (filter == null) filter = DEFAULT_FILTER;
if (filter.accept(sourceFile)) {
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
copyInputToOutput(fis, fos);
fis.close();
fos.close();
}
}
/**
* Copy the contents of the input to the output stream.
*
* @param input
* @param output
* @throws IOException
*/
public static void copyInputToOutput(InputStream input, OutputStream output)
throws IOException
{
int bytesRead = 0;
do {
bytesRead = input.read(buffer, 0, buffer.length);
if (bytesRead > 0) {
output.write(buffer, 0, bytesRead);
}
} while (bytesRead != -1);
output.flush();
}
/**
* Create a new zip archive with the contents specified by the source folder.
*
* @param tgtArchiveFile
* @param srcFolder
* @throws IOException
*/
public static void createArchive(File tgtArchiveFile, File srcFolder)
throws IOException
{
if (srcFolder.exists() && srcFolder.isDirectory()) {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tgtArchiveFile));
try {
addFolderToArchive(zos, srcFolder.getAbsolutePath().length() + 1, srcFolder);
} finally {
if (zos != null) {
try { zos.close(); } catch (IOException e) {}
}
}
}
}
/**
* Delete the specified file, recursively as necessary.
*
* @param file
*/
public static void delete(File file) {
if (file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
delete(files[i]);
}
}
file.delete();
}
}
/**
* If the system property "eclipseme.dump.launch" is set to "true",
* dump the command line that was used to launch the emulator.
*/
public static void dumpCommandLine(ILaunch launch) {
// Search for the process command-line
IProcess[] processes = launch.getProcesses();
if ((processes != null) && (processes.length > 0)) {
IProcess process = processes[0];
if (process != null) {
String commandLine = process.getAttribute(IProcess.ATTR_CMDLINE);
dumpCommandLine(commandLine);
}
}
}
/**
* If the system property "eclipseme.dump.launch" is set to "true",
* dump the command line that was used to launch the emulator.
*
* @param commandLine
*/
public static void dumpCommandLine(String commandLine) {
// Pull the dump choice from system properties
String propValue =
System.getProperty(IEclipseMECoreConstants.PROP_DUMP_LAUNCH, "false");
boolean doDump = propValue.equalsIgnoreCase("TRUE");
// Only do this if requested
if (doDump) {
// Let the user know what happened via the log file
String text = (commandLine == null) ?
"Command line not found" :
"Command line: " + commandLine;
EclipseMECorePlugin.log(IStatus.INFO, text);
// if (commandLine != null) {
// EclipseMECorePlugin.log(IStatus.INFO, "" + commandLine.length());
// }
}
}
/**
* If the system property "eclipseme.dump.launch" is set to "true",
* dump the command line that was used to launch the emulator.
*
* @param commandLine
*/
public static void dumpCommandLine(String[] commandLine) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < commandLine.length; i++) {
String string = commandLine[i];
if (i != 0) sb.append(' ');
sb.append(string);
}
dumpCommandLine(sb.toString());
}
/**
* Exec a new process via the debug plugin.
*
* @param commandLine
* @param workingDirectory
* @param env The environment to be used or <code>null</code>
* to take the default.
* @return
* @throws CoreException
*/
public static Process exec(String[] commandLine, File workingDirectory, String[] env)
throws CoreException
{
return DebugPlugin.exec(commandLine, workingDirectory, env);
}
/**
* Test if the specified executable file exist. Add a ".exe"
* if necessary to handle Windows systems.
*
* @param executableFile
* @return
*/
public static boolean executableExists(File executableFile) {
File winExecutable = new File(
executableFile.getParentFile(),
executableFile.getName() + ".exe");
return
executableFile.exists() ||
winExecutable.exists();
}
/**
* Extract the archive specified by the file into the provided directory.
*
* @param jarFile
* @param tgtDirectory
* @throws IOException
*/
public static void extractArchive(File jarFile, File tgtDirectory)
throws IOException
{
ZipInputStream zis = new ZipInputStream(new FileInputStream(jarFile));
try {
ZipEntry entry = null;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
File directory = new File(tgtDirectory, entry.getName());
directory.mkdirs();
} else {
File file = new File(tgtDirectory, entry.getName());
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
try {
Utils.copyInputToOutput(zis, fos);
} finally {
if (fos != null) {
try { fos.close(); } catch (IOException e) {}
}
}
}
}
} finally {
try { zis.close(); } catch (IOException e) {}
}
}
/**
* Extract the class name from the specified
* IResource within the specified java project.
*
* @param javaProject the java project to provide the relative name
* @param resource the resource to extract a class name
* @return the class name or <code>null</code> if the resource
* name cannot be converted for some reason.
* @throws JavaModelException
*/
public static String extractClassName(
IJavaProject javaProject,
IResource resource)
throws JavaModelException
{
IPath classPath = extractsSourceFolderRelativePath(javaProject, resource);
return (classPath == null) ? null :
classPath.removeFileExtension().toString().replace('/', '.');
}
/**
* Extract the class path from the specified
* IResource within the specified java project.
*
* @param javaProject
* @param resource
* @return the extracted resource path
* @throws JavaModelException
*/
public static IPath extractsSourceFolderRelativePath(
IJavaProject javaProject,
IResource resource)
throws JavaModelException
{
IPath resultPath = null;
IPath projectOutputPath =
javaProject.getOutputLocation().makeAbsolute();
IPath resourcePath = resource.getFullPath();
IClasspathEntry[] classpath = javaProject.getRawClasspath();
for (int i = 0; i < classpath.length; i++) {
IClasspathEntry entry = classpath[i];
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath entryPath = entry.getOutputLocation();
entryPath = (entryPath == null) ?
projectOutputPath : entryPath.makeAbsolute();
if (entryPath.isPrefixOf(resourcePath)) {
resultPath =
resourcePath.removeFirstSegments(entryPath.segmentCount());
}
}
}
return resultPath;
}
/**
* Return the Javadoc classpath attribute or <code>null</code> if none
* is attached.
*
* @return
*/
public static IClasspathAttribute getJavadocAttribute(IClasspathEntry entry) {
int index = getJavadocAttributeIndex(entry);
return (index == -1) ? null : entry.getExtraAttributes()[index];
}
/**
* Return the Javadoc classpath attribute index or <code>-1</code> if none
* is attached.
*
* @return
*/
public static int getJavadocAttributeIndex(IClasspathEntry entry) {
int index = -1;
IClasspathAttribute[] attributes = entry.getExtraAttributes();
for (int i = 0; i < attributes.length; i++) {
IClasspathAttribute attribute = attributes[i];
if (attribute.getName().equals(IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME)) {
index = i;
break;
}
}
return index;
}
/**
* Get a new launch instance with the specified configuration
* name.
*
* @param configName
* @return
* @throws CoreException
*/
public static ILaunch getNewLaunch(String configName)
throws CoreException
{
return new Launch(
getNewLaunchConfiguration(configName),
ILaunchManager.RUN_MODE,
null);
}
/**
* Get the launch configuration to be used in building
* the ILaunch instance.
*/
public static ILaunchConfiguration getNewLaunchConfiguration(String name)
throws CoreException
{
ILaunchManager launchManager =
DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType configType =
launchManager.getLaunchConfigurationType(
IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
ILaunchConfigurationWorkingCopy config =
configType.newInstance(null, name);
config.setAttribute(PRIVATE_CONFIGURATION, true);
return config;
}
/**
* Return the resource that is resolved for the specified path.
* This will return one of three things:
* <ul>
* <li>An instance of org.eclipse.core.resources.IResource if the entry refers to a workspace resource.</li>
* <li>An instance of java.io.File if the entry refers to a non-workspace resource.</li>
* <li><code>null</code> if the entry points to a non-existent resource.</li>
* </ul>
*
* @param path the path to look for an object
* @return the resolved object
*/
public static Object getPathTarget(IPath path) {
Object target = null;
IWorkspaceRoot root = EclipseMECorePlugin.getWorkspace().getRoot();
target = root.findMember(path);
if (target == null) {
File externalFile = new File(path.toOSString());
if ((externalFile != null) && (externalFile.isFile())) {
target = externalFile;
} else {
target = null;
}
}
return target;
}
/**
* Return the java.io.File instance referenced by the specified path
* or <code>null</code> if no such file exists.
*
* @param entry
* @return
* @throws CoreException
*/
public static File getPathTargetFile(IPath path)
throws CoreException
{
File entryFile = null;
Object pathTarget = getPathTarget(path);
if (pathTarget instanceof IResource) {
entryFile = ((IResource) pathTarget).getLocation().toFile();
} else if (pathTarget instanceof File) {
entryFile = (File) pathTarget;
}
return entryFile;
}
/**
* Attempt to retrieve the fully-qualified class name.
*
* @param type
* @return
*/
public static String getQualifiedClassName(IType type) {
String classname = null;
if (type instanceof BinaryType) {
classname = getQualifiedClassName((BinaryType) type);
} else {
classname = type.getFullyQualifiedName();
}
return classname;
}
/**
* Return the resource that is resolved for the specified classpath
* entry. This will return one of three things:
* <ul>
* <li>An instance of org.eclipse.core.resources.IResource if the entry refers to a workspace resource.</li>
* <li>An instance of java.io.File if the entry refers to a non-workspace resource.</li>
* <li><code>null</code> if the entry points to a non-existent resource.</li>
* </ul>
*
* @param entry the entry to be resolved
* @return the resolved object
*/
public static Object getResolvedClasspathEntry(IClasspathEntry entry) {
IClasspathEntry resolved = JavaCore.getResolvedClasspathEntry(entry);
return getPathTarget(resolved.getPath());
}
/**
* Return the java.io.File instance referenced by the specified classpath
* entry or <code>null</code> if no such file exists.
*
* @param entry
* @return
* @throws CoreException
*/
public static final File getResolvedClasspathEntryFile(IClasspathEntry entry)
throws CoreException
{
IClasspathEntry resolved = JavaCore.getResolvedClasspathEntry(entry);
return getPathTargetFile(resolved.getPath());
}
/**
* Launch the specified command line and return the output from
* the standard output.
*
* @param name
* @param commandLine
* @return
* @throws CoreException
*/
public static String getStandardOutput(String name, String[] commandLine)
throws CoreException
{
return getStandardOutput(name, commandLine, null);
}
/**
* Launch the specified command line and return the output from
* the standard output.
*
* @param name
* @param commandLine
* @return
* @throws CoreException
*/
public static String getStandardOutput(String name, String[] commandLine, File workingDirectory)
throws CoreException
{
IProcess process =
Utils.launchApplication(commandLine, workingDirectory, null, name, name);
// Listen on the process output streams
IStreamsProxy proxy = process.getStreamsProxy();
// Wait until completion
while (!process.isTerminated()) {
try { Thread.sleep(1000); } catch (InterruptedException e) {};
}
return proxy.getOutputStreamMonitor().getContents();
}
/**
* This class is used as part of monitoring process output in the
* #getProcessOutput method. It monitors output from the process
* (either stdout or stderr) and appends the results to the
* specified <code>StringBuffer</code>. The listener approach
* prevents a process from stalling because output blocks.
*/
private static class StreamListener implements IStreamListener
{
private StringBuffer buf;
public StreamListener(StringBuffer buf)
{
this.buf = buf;
}
public void streamAppended(String text, IStreamMonitor monitor)
{
if (buf != null)
{
buf.append(text);
}
}
}
/**
* Execute a process and collect its stdout and stderr.
*
* @param name Name of the process for display purposes
* @param commandLine Array of <code>String</code>s that provides the command line.
* The first entry in the array is the executable.
* @param stdout <code>StringBuffer</code> to which the process' stdout will
* be appended. May be <code>null</code>.
* @param stderr <code>StringBuffer</code> to which the process' stderr will
* be appended. May be <code>null</code>.
* @return The exit value of the process.
* @throws CoreException
*/
public static int getProcessOutput(String name, String[] commandLine, StringBuffer stdout, StringBuffer stderr)
throws CoreException
{
IProcess process = Utils.launchApplication(commandLine, null, null, name, name);
// Listen on the process output streams
IStreamsProxy proxy = process.getStreamsProxy();
proxy.getOutputStreamMonitor().addListener(new StreamListener(stdout));
proxy.getErrorStreamMonitor().addListener(new StreamListener(stderr));
// Wait until completion
while (!process.isTerminated())
{
try
{
Thread.sleep(1000); // sleep for one second
}
catch (InterruptedException e)
{
}
}
return(process.getExitValue());
}
/**
* Return a boolean indicating whether the host file system
* appears to be case sensitive.
*
* @return case sensitivity of the host file system
*/
public static boolean isFileSystemCaseSensitive() {
if (!caseSensitivityChecked) {
caseSensitivityChecked = true;
Location location = Platform.getInstallLocation();
if (location != null) {
URL url = location.getURL();
if (url != null) {
String urlString = url.toString();
if (urlString.startsWith("file:/")) {
urlString = urlString.substring("file:/".length()).toUpperCase();
caseSensitiveFileSystem = !(new File(urlString)).exists();
}
}
}
}
return caseSensitiveFileSystem;
}
/**
* Return a boolean indicating whether the specified type is a Midlet
* subclass.
*
* @param type
* @return
*/
public static boolean isMidlet(IType type, IProgressMonitor monitor)
throws JavaModelException
{
boolean isMidlet = false;
if (type != null) {
IJavaProject javaProject = type.getJavaProject();
if (!type.exists() && type.isBinary()) {
// A binary type, which won't help much... Attempt to convert
// to a source type and use that to do the lookup
String classname = getQualifiedClassName(type);
if (classname != null) {
IType sourceType = javaProject.findType(classname);
isMidlet = isMidlet(sourceType, monitor);
}
} else {
ITypeHierarchy typeHierarchy = type.newSupertypeHierarchy(monitor);
IType midletType =
javaProject.findType(IEclipseMECoreConstants.MIDLET_SUPERCLASS);
isMidlet =
(midletType != null) &&
typeHierarchy.contains(midletType);
}
}
return isMidlet;
}
/**
* Launch a new application and return the IProcess
* representing the application.
*
* @param commandLine
* @param workingDirectory
* @param environment
* @param configName
* @param label
* @return
* @throws CoreException
*/
public static IProcess launchApplication(
String[] commandLine,
File workingDirectory,
String[] environment,
String configName,
String label)
throws CoreException
{
// Execute the process.
Process execProcess = exec(commandLine, workingDirectory, environment);
// Wrap it up in a JDT IProcess instance
Launch launch = new Launch(
getNewLaunchConfiguration(configName),
ILaunchManager.RUN_MODE,
null);
IProcess process = DebugPlugin.newProcess(launch, execProcess, label);
Utils.dumpCommandLine(commandLine);
return process;
}
/**
* Add the contents of the specified folder to the archive being
* created.
*
* @param zos
* @param prefixLength
* @param srcFolder
* @throws IOException
*/
private static void addFolderToArchive(ZipOutputStream zos, int prefixLength, File srcFolder)
throws IOException
{
File[] files = srcFolder.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
addFolderToArchive(zos, prefixLength, file);
} else {
addFileEntryToArchive(zos, prefixLength, file);
}
}
}
/**
* Add the specified file as an entry to the archive output stream.
*
* @param zos
* @param prefixLength
* @param file
* @throws IOException
*/
private static void addFileEntryToArchive(ZipOutputStream zos, int prefixLength, File file)
throws IOException
{
// Create a new zip entry
ZipEntry entry = getEntryForFile(file, prefixLength);
zos.putNextEntry(entry);
// Write the contents for the new zip entry
FileInputStream fis = new FileInputStream(file);
try {
copyInputToOutput(fis, zos);
} finally {
zos.closeEntry();
if (fis != null) {
try { fis.close(); } catch (IOException e) {}
}
}
}
/**
* @param file
* @param prefixLength
* @return
*/
private static ZipEntry getEntryForFile(File file, int prefixLength) {
String fileString = file.getAbsolutePath();
String entryName = fileString.substring(prefixLength).replace('\\', '/');
ZipEntry entry = new ZipEntry(entryName);
entry.setSize(file.length());
entry.setTime(file.lastModified());
return entry;
}
/**
* Private constructor
*/
private Utils() {
super();
}
/**
* Attempt to retrieve the fully-qualified class name.
*
* @param type
* @return
*/
private static String getQualifiedClassName(BinaryType type) {
IJavaElement javaElement = type.getPackageFragment();
StringBuffer name = new StringBuffer(type.getElementName());
while (javaElement.getElementType() != IJavaElement.JAVA_PROJECT) {
String elementName = javaElement.getElementName();
if ((elementName != null) && (elementName.length() > 0)) {
name.insert(0, '.').insert(0, elementName);
}
javaElement = javaElement.getParent();
}
return name.toString();
}
}
The table below shows all metrics for Utils.java.




