AntennaBuildExporter.java

Index Score
eclipseme.core.internal.tools
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.

MetricDescription
EXEC_COMMENTSComments in executable code
LINE_COMMENTNumber of line comments
EXITSProcedure exits
DECL_COMMENTSComments in declarations
RETURNSNumber of return points from functions
UNIQUE_OPERANDSNumber of unique operands
DOC_COMMENTNumber of javadoc comment lines
SIZESize of the file in bytes
INTERFACE_COMPLEXITYInterface complexity
PROGRAM_VOCABHalstead program vocabulary
COMMENTSComment lines
LOGICAL_LINESNumber of statements
OPERANDSNumber of operands
LINESNumber of lines in the source file
PROGRAM_LENGTHHalstead program length
ELOCEffective lines of code
JAVA0160JAVA0160 Method does not throw specified exception
LOCLines of code
OPERATORSNumber of operators
JAVA0130JAVA0130 Non-static method does not use instance fields
PARAMSNumber of formal parameter declarations
FUNCTIONSNumber of function declarations
JAVA0075JAVA0075 Method parameter hides field
CYCLOMATICCyclomatic complexity
LOOPSNumber of loops
JAVA0145JAVA0145 Tab character used in source file
BLOCKSNumber of blocks
JAVA0034JAVA0034 Missing braces in if statement
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0173JAVA0173 Unused method parameter
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0077JAVA0077 Private field not used in declaring class
JAVA0144JAVA0144 Line exceeds maximum M characters
JAVA0285JAVA0285 Dereference of potentially null variable
WHITESPACENumber of whitespace lines
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0096JAVA0096 Field in nested class hides outer field
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
COMPARISONSNumber of comparison operators
JAVA0117JAVA0117 Missing javadoc: method 'method'
UNIQUE_OPERATORSNumber of unique operators
JAVA0128JAVA0128 Public constructor in non-public class
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0254JAVA0254 Use enhanced for loop construct instead of Iterator
/** * 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.tools; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; 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.Preferences; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import eclipseme.core.IEclipseMECoreConstants; import eclipseme.core.internal.EclipseMECorePlugin; import eclipseme.core.internal.PreferenceAccessor; import eclipseme.core.internal.utils.FilteringClasspathEntryVisitor; import eclipseme.core.internal.utils.Utils; import eclipseme.core.internal.utils.XMLUtils; import eclipseme.core.model.ApplicationDescriptor; import eclipseme.core.model.IJADConstants; import eclipseme.core.model.IMidletSuiteProject; import eclipseme.core.model.device.IDevice; /** * Tool for exporting an Antenna build file. * <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: 2007/01/20 22:39:22 $ * <br> * @author Craig Setera */ public class AntennaBuildExporter { private static final String NO_EXPORT = "_no_export"; private static final String PATH_BUILD_CLASSES_NO_EXPORT = "${path.build.classes}/" + NO_EXPORT; private static final String PATH_BUILD_CLASSES = "${path.build.classes}"; // Holder for project-specific information built during the visitation of the classpath private class ProjectInfo { private String safeProjectName; private IJavaProject javaProject; private boolean exported; private Element classpathElement; private Map wtkBuildElements; private List packageFilesetElements; /** * Construct a new project information instance for the * specified java project. * * @param javaProject */ ProjectInfo(IJavaProject javaProject, boolean exported) { this.javaProject = javaProject; this.exported = exported; wtkBuildElements = new HashMap(); packageFilesetElements = new ArrayList(); // Calculate a "safe" project name safeProjectName = javaProject.getElementName(); safeProjectName = safeProjectName.replace(' ', '_'); } /** * Add a new fileset element to the list. * * @param element */ public void addPackageFilesetElement(Element element) { packageFilesetElements.add(element); } /** * Add a new wtkbuild element to the list. * * @param srcEntry * @param element */ public void addWtkBuildElement(IClasspathEntry srcEntry, Element element) { if (!wtkBuildElements.containsKey(srcEntry)) { wtkBuildElements.put(srcEntry, element); } } /** * Return the Ant property name to be used for this project. */ public String getAntProjectPropertyName() { return "project.root." + safeProjectName; } /** * Return the Ant project property value. * * @return */ public String getAntProjectPropertyValue() { String relativePath = null; // Figure out the property value relative to the base directory IPath projectPath = javaProject.getProject().getLocation(); relativePath = getRelativePath(basedirPath, projectPath); if (relativePath == null) { relativePath = projectPath.toString(); } return relativePath; } /** * Return the destination directory to be used for class build output. * * @return */ public String getBuildDestination() { return exported ? PATH_BUILD_CLASSES : PATH_BUILD_CLASSES_NO_EXPORT; } /** * Return the classpath element. * * @return */ public Element getClasspathElement() { if (classpathElement == null) { classpathElement = eclipseMeBuildXmlDocument.createElement("path"); classpathElement.setAttribute("id", getClasspathElementId()); Element pathElement = newChildElement(classpathElement, "path"); pathElement.setAttribute("location", PATH_BUILD_CLASSES); pathElement = newChildElement(classpathElement, "path"); pathElement.setAttribute("location", PATH_BUILD_CLASSES_NO_EXPORT); } return classpathElement; } /** * Return the identifier of the classpath path element. * * @return */ public String getClasspathElementId() { return "classpath." + safeProjectName; } /** * @return Returns the packageFilesetElements. */ public List getPackageFilesetElements() { return packageFilesetElements; } /** * @return Returns the wtkBuildElements. */ public Iterator getWtkBuildElements() { return wtkBuildElements.values().iterator(); } /** * @return Returns the exported flag indication */ public boolean isExported() { return exported; } } // Classpath entry visitor for helping build the build.xml file private class BuildClasspathEntryVisitor extends FilteringClasspathEntryVisitor { private Map projectInfoMap; /** * Construct a new visitor that will be responsible for * creating the necessary elements. */ public BuildClasspathEntryVisitor(IJavaProject rootProject) { projectInfoMap = new LinkedHashMap(); createProjectInfo(rootProject, true); } /** * Return the map of project information. * * @return */ public Map getProjectInfoMap() { return projectInfoMap; } /** * @see eclipseme.core.internal.utils.IClasspathEntryVisitor#visitLibraryEntry(org.eclipse.jdt.core.IClasspathEntry, org.eclipse.jdt.core.IJavaProject, org.eclipse.core.runtime.IProgressMonitor) */ public void visitLibraryEntry( IClasspathEntry entry, IJavaProject javaProject, IProgressMonitor monitor) throws CoreException { ProjectInfo projectInfo = getProjectInfo(javaProject); Element classpathElement = projectInfo.getClasspathElement(); IPath libLocation = getLibraryLocation(entry); if (libLocation != null) { File libFile = libLocation.toFile(); Element pathElement = newChildElement(classpathElement, "path"); String relativePath = getProjectRelativeValue(javaProject, projectInfo, libLocation); pathElement.setAttribute("location", relativePath); addIncludesAndExcludes(entry, pathElement); if (isLibraryExported(entry)) { if (libFile.isDirectory()) { // Create a new zip fileset for the packaging Element filesetElement = eclipseMeBuildXmlDocument.createElement("fileset"); projectInfo.addPackageFilesetElement(filesetElement); filesetElement.setAttribute("dir", relativePath); } else { // Create a new zip fileset for the packaging Element zipFilesetElement = eclipseMeBuildXmlDocument.createElement("zipfileset"); projectInfo.addPackageFilesetElement(zipFilesetElement); zipFilesetElement.setAttribute("src", relativePath); addIncludesAndExcludes(entry, zipFilesetElement); } } } } /** * @see eclipseme.core.internal.utils.IClasspathEntryVisitor#visitProject(IClasspathEntry, org.eclipse.jdt.core.IJavaProject, org.eclipse.jdt.core.IJavaProject, org.eclipse.core.runtime.IProgressMonitor) */ public boolean visitProject( IClasspathEntry entry, IJavaProject javaProject, IJavaProject classpathProject, IProgressMonitor monitor) throws CoreException { // Force the project info into the map so that it // is held in the correct order boolean exported = entry.isExported(); createProjectInfo(classpathProject, exported); return super.visitProject(entry, javaProject, classpathProject, monitor); } /** * @see eclipseme.core.internal.utils.IClasspathEntryVisitor#visitSourceEntry(org.eclipse.jdt.core.IClasspathEntry, org.eclipse.jdt.core.IJavaProject, org.eclipse.core.runtime.IProgressMonitor) */ public void visitSourceEntry( IClasspathEntry entry, IJavaProject javaProject, IProgressMonitor monitor) throws CoreException { IPath srcLocation = getSourceLocation(entry); if (srcLocation != null) { ProjectInfo projectInfo = getProjectInfo(javaProject); // Create the wtkbuild task call String buildTask = projectInfo.isExported() ? "wtkbuild" : "javac"; Element buildElement = eclipseMeBuildXmlDocument.createElement(buildTask); projectInfo.addWtkBuildElement(entry, buildElement); buildElement.setAttribute("destdir", projectInfo.getBuildDestination()); buildElement.setAttribute("sourcepath", ""); buildElement.setAttribute("encoding", "${src.encoding}"); buildElement.setAttribute("source", "1.3"); // Calculate the src directory relative to the specified // project. String relativePath = getProjectRelativeValue(javaProject, projectInfo, srcLocation); buildElement.setAttribute("srcdir", relativePath); // Add the inclusion and exclusion patterns as necessary addIncludesAndExcludes(entry, buildElement); // Add the classpath reference Element classpathElement = newChildElement(buildElement, "classpath"); classpathElement.setAttribute("refid", projectInfo.getClasspathElementId()); // Make sure to copy the non-Java resources into the package Element srcPackageElement = eclipseMeBuildXmlDocument.createElement("fileset"); srcPackageElement.setAttribute("dir", relativePath); Element javaExclude = newChildElement(srcPackageElement, "exclude"); javaExclude.setAttribute("name", "**/*.java"); Element buildExclude = newChildElement(srcPackageElement, "exclude"); buildExclude.setAttribute("name", "build/"); addIncludesAndExcludes(entry, srcPackageElement); projectInfo.addPackageFilesetElement(srcPackageElement); } else { EclipseMECorePlugin.log( IStatus.WARNING, "Skipping unresolvable classpath entry " + entry); } } /** * Add the inclusion and exclusion elements as necessary. * * @param entry * @param element */ private void addIncludesAndExcludes(IClasspathEntry entry, Element element) { for (int i = 0; i < entry.getExclusionPatterns().length; i++) { IPath pattern = entry.getExclusionPatterns()[i]; Element exclusionElement = newChildElement(element, "exclude"); exclusionElement.setAttribute("name", pattern.toString()); } for (int i = 0; i < entry.getInclusionPatterns().length; i++) { IPath pattern = entry.getInclusionPatterns()[i]; Element inclusionElement = newChildElement(element, "include"); inclusionElement.setAttribute("name", pattern.toString()); } } /** * Create a new project information structure. * * @param javaProject * @param exported */ private void createProjectInfo(IJavaProject javaProject, boolean exported) { ProjectInfo info = new ProjectInfo(javaProject, exported); projectInfoMap.put(javaProject, info); } /** * Get the holder of information for the specified project. * * @param javaProject * @return */ private ProjectInfo getProjectInfo(IJavaProject javaProject) { return (ProjectInfo) projectInfoMap.get(javaProject); } /** * Get the file system location for the specified classpath entry. * * @param entry * @return * @throws CoreException */ private IPath getLibraryLocation(IClasspathEntry entry) throws CoreException { IPath libLocation = null; Object resolved = Utils.getResolvedClasspathEntry(entry); if (resolved instanceof IResource) { IResource libResource = (IResource) resolved; libLocation = libResource.getLocation(); } else if (resolved instanceof File) { libLocation = entry.getPath(); } return libLocation; } /** * Return the project relative path. * * @param javaProject * @param projectInfo * @param location * @return * @throws CoreException */ private String getProjectRelativeValue( IJavaProject javaProject, ProjectInfo projectInfo, IPath location) throws CoreException { StringBuffer sb = new StringBuffer(); IPath projectPath = javaProject.getProject().getLocation(); String relativePath = getRelativePath(projectPath, location); if (relativePath == null) { // Can't get relation to projectPath, use location as it is sb.append(location.toString()); } else { sb .append("${") .append(projectInfo.getAntProjectPropertyName()) .append("}") .append(relativePath); } return sb.toString(); } /** * Get the file system location for the specified classpath entry. * * @param entry * @return * @throws CoreException */ private IPath getSourceLocation(IClasspathEntry entry) throws CoreException { IPath sourceLocation = null; Object resolved = Utils.getResolvedClasspathEntry(entry); if (resolved instanceof IResource) { IResource srcResource = (IResource) resolved; sourceLocation = srcResource.getLocation(); } return sourceLocation; } } private static final Pattern SUBSTITUTION_PATTERN = Pattern.compile("\\@\\{(.+?)\\}"); private IMidletSuiteProject midletSuite; private IJavaProject javaProject; private IPath basedirPath; private String projectName; private Properties buildProperties; private Document eclipseMeBuildXmlDocument; /** * Construct a new exporter for the specified midlet suite project. * * @param midletSuite */ public AntennaBuildExporter(IMidletSuiteProject midletSuite) { super(); this.midletSuite = midletSuite; this.javaProject = midletSuite.getJavaProject(); basedirPath = javaProject.getProject().getLocation(); projectName = midletSuite.getProject().getName(); } /** * Do the export for the midlet suite. * * @throws CoreException */ public void doExport(IProgressMonitor monitor) throws CoreException, AntennaExportException { // Validate the environment is ok. validateEnvironment(monitor); try { // Read in the templates buildProperties = createInitialProperties(); eclipseMeBuildXmlDocument = readEclipseMeBuildTemplate(); // Traverse the classpath and update the results along the way BuildClasspathEntryVisitor visitor = traverseClasspath(monitor); updateEclipseMeBuildXml(visitor.getProjectInfoMap()); // Write out the results exportBuildXml(monitor); writeBuildProperties(monitor); writeEclipseMeBuildXml(monitor); // Refresh so these files show in the workbench. javaProject.getProject().refreshLocal(IResource.DEPTH_ONE, monitor); } catch (Exception e) { if (e instanceof CoreException) { throw (CoreException) e; } else { EclipseMECorePlugin.throwCoreException(IStatus.ERROR, -999, e); } } } /** * Create the initial properties object. * * @return */ private Properties createInitialProperties() { Properties props = new Properties(); // The basics props.setProperty("midlet.name", javaProject.getProject().getName()); props.setProperty("path.build", "${basedir}/build"); props.setProperty("path.build.classes", "${basedir}/build/classes"); props.setProperty("path.build.output", "${basedir}/deployed"); // Antenna stuff Preferences prefs = EclipseMECorePlugin.getDefault().getPluginPreferences(); props.setProperty( "wtk.home", prefs.getString(IEclipseMECoreConstants.PREF_WTK_ROOT)); props.setProperty( "path.antenna.jar", prefs.getString(IEclipseMECoreConstants.PREF_ANTENNA_JAR)); boolean autoVersion = PreferenceAccessor.instance.getAutoversionPackage(midletSuite.getProject()); props.setProperty( "flag.autoversion", Boolean.toString(autoVersion)); props.setProperty("flag.preverify", "true"); // Set default encoding to UTF-8 props.setProperty("src.encoding", "UTF-8"); // Set the classpath to match the device IDevice device = midletSuite.getDevice(); if (device != null) { props.setProperty("wtk.midpapi", device.getClasspath().toString()); } // Properties necessary for running in the emulator props.setProperty("run.device.name", "DefaultColorPhone"); props.setProperty("run.trace.options", ""); // Add some default properties based on various things addObfuscationProperties(props); addVersionProperties(props); return props; } /** * Add the obfuscation-related properties. * * @param props */ private void addObfuscationProperties(Properties props) { File proguardFile = EclipseMECorePlugin.getProguardJarFile(); boolean obfuscate = ((proguardFile != null) && proguardFile.exists()); // props.setProperty("flag.obfuscate", Boolean.toString(obfuscate)); if (obfuscate) { File proguardHome = proguardFile.getParentFile().getParentFile(); props.setProperty("wtk.proguard.home", proguardHome.toString()); } } /** * Add the appropriate J2ME version properties to match the JAD versions. * * @param props */ private void addVersionProperties(Properties props) { ApplicationDescriptor descriptor = midletSuite.getApplicationDescriptor(); Properties manifestProperties = descriptor.getManifestProperties(); String versionString = manifestProperties.getProperty(IJADConstants.JAD_MICROEDITION_CONFIG); if (versionString != null) { int index = versionString.indexOf('-'); versionString = (index == -1) ? versionString : versionString.substring(index + 1); props.setProperty("wtk.cldc.version", versionString); } versionString = manifestProperties.getProperty(IJADConstants.JAD_MICROEDITION_PROFILE); if (versionString != null) { int index = versionString.indexOf('-'); versionString = (index == -1) ? versionString : versionString.substring(index + 1); props.setProperty("wtk.midp.version", versionString); } } /** * Add a new argument to the WTK obfuscate element. * * @param wktobfuscateElement * @param argument */ private void addWtkObfuscateArgument(Element wktobfuscateElement, String argument) { Element argumentElement = newChildElement(wktobfuscateElement, "argument"); argumentElement.setAttribute("value", argument); } /** * Read the build.xml template file. * * @param is * @return * @throws UnsupportedEncodingException * @throws IOException */ private StringBuffer readBuildXmlTemplate(InputStream is) throws UnsupportedEncodingException, IOException { // Read in the template int charsRead; char[] buffer = new char[1024]; Reader reader = new InputStreamReader(is, "UTF-8"); StringBuffer sb = new StringBuffer(); while ((charsRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, charsRead); } is.close(); return sb; } /** * Read the template EclipseME build file. * @return * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ private Document readEclipseMeBuildTemplate() throws ParserConfigurationException, SAXException, IOException { Document document = null; InputStream is = getClass().getResourceAsStream("eclipseme-build.xml"); if (is == null) { throw new IOException("build.xml template not found"); } else { // Read the document document = XMLUtils.readDocument(is); // Alter the "project" element's name attribute Element projectElement = document.getDocumentElement(); projectElement.setAttribute("name", "eclipseme-" + projectName); // Add some warning comments StringBuffer comment = new StringBuffer(); comment .append("\n\tAutomatically generated by EclipseME on ") .append(new Date()) .append("\n\tDO NOT ALTER THIS FILE. IT WILL BE OVERWRITTEN\n\n") .append("\tChanges may be made to build.xml and user-build.properties\n"); insertCommentBefore(projectElement, comment.toString()); } return document; } /** * Replace the build xml template values. * * @param sb * @param props */ private void replaceTemplateValues(StringBuffer sb, Properties props) { // Replace template values int offset = 0; Matcher matcher = SUBSTITUTION_PATTERN.matcher(sb); while (matcher.find(offset)) { String referencedValue = matcher.group(1); String resolvedValue = props.getProperty(referencedValue, referencedValue); sb.replace(matcher.start(), matcher.end(), resolvedValue); // Figure out the new offset, based on the replaced // string length offset = matcher.start() + resolvedValue.length(); } } /** * Export the build.xml file. * * @param monitor * @throws SAXException * @throws ParserConfigurationException * @throws IOException * @throws TransformerException * @throws CoreException */ private void exportBuildXml(IProgressMonitor monitor) throws ParserConfigurationException, SAXException, TransformerException, IOException, CoreException { // Check to make sure that we don't overwrite a user's build.xml file // with our template file. // TODO What do we do, if anything, when the build.xml file already exists? File buildXmlFile = getMidletSuiteFile("build.xml", monitor); if (!buildXmlFile.exists()) { // Template values Properties props = new Properties(); props.setProperty("eclipseme.version", EclipseMECorePlugin.getPluginVersion()); props.setProperty("date", (new Date()).toString()); props.setProperty("project.name", projectName); InputStream is = getClass().getResourceAsStream("buildtemplate.xml"); if (is != null) { // Read the template and do the replacements StringBuffer sb = readBuildXmlTemplate(is); replaceTemplateValues(sb, props); // Write the results FileOutputStream fos = new FileOutputStream(buildXmlFile); OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); writer.write(sb.toString()); writer.close(); } } } /** * Return the specified element within the specified parent. If more * elements exist with that name, the first will be returned. If not * found, <code>null</code> will be returned. * * @param parentElement * @param elementName * @return */ private Element findElement(Element parentElement, String elementName) { Element element = null; NodeList elements = parentElement.getElementsByTagName(elementName); if (elements.getLength() > 0) { element = (Element) elements.item(0); } return element; } /** * Return a File reference to a file with the specified name * in the midlet suite project. * * @param filename * @param monitor * @return * @throws CoreException */ private File getMidletSuiteFile(String filename, IProgressMonitor monitor) throws CoreException { IFile file = midletSuite.getProject().getFile(filename); return file.getLocation().toFile(); } /** * Get the options to be specified when calling Proguard for * obfuscation. * * @return */ private String getProguardOptions() { IProject project = midletSuite.getProject(); PreferenceAccessor obfuscationPrefs = PreferenceAccessor.instance; String specifiedOptions = obfuscationPrefs.getSpecifiedProguardOptions(project); boolean useSpecified = obfuscationPrefs.isUseSpecifiedProguardOptions(project); return useSpecified ? specifiedOptions : obfuscationPrefs.getDefaultProguardOptions(); } /** * Return the relative path. * * @param basePath the path that acts as the base for comparison * @param tgtPath the path being compared to the base path * @return relative path, or null if relation not possible */ private String getRelativePath(IPath basePath, IPath tgtPath) { String path = null; // Find the common path prefix int matchingSegments = tgtPath.matchingFirstSegments(basePath); String baseDevice = basePath.getDevice(); String tgtDevice = tgtPath.getDevice(); boolean bothNull = ((baseDevice == null) && (tgtDevice == null)); if (bothNull || baseDevice.equals(tgtDevice)) { // Step up the directory tree StringBuffer relativePath = new StringBuffer(); int upSteps = basedirPath.segmentCount() - matchingSegments; for (int i = 0; i < upSteps; i++) { relativePath.append("/.."); } // Tack on the src folder segments tgtPath = tgtPath.removeFirstSegments(matchingSegments); String[] segments = tgtPath.segments(); for (int i = 0; i < segments.length; i++) { relativePath.append("/").append(segments[i]); } path = relativePath.toString(); } return path; } /** * Return the root of the first located Sun wireless toolkit for use * in setting the appropriate Antenna property or <code>null</code> * if one cannot be found. * * @return */ private File getWTKRoot() { Preferences prefs = EclipseMECorePlugin.getDefault().getPluginPreferences(); return new File(prefs.getString(IEclipseMECoreConstants.PREF_WTK_ROOT)); } /** * Insert the comment text before the specified element. * * @param element * @param commentString */ private void insertCommentBefore(Element element, String commentString) { Document document = element.getOwnerDocument(); Comment comment = document.createComment(commentString); document.insertBefore(comment, element); } /** * Create and return a new child element under the specified parent * element. * * @param parentElement * @param name * @return */ private Element newChildElement(Element parentElement, String name) { Element element = parentElement.getOwnerDocument().createElement(name); parentElement.appendChild(element); return element; } /** * Traverse the classpath and update the build information * along the way. * @throws CoreException */ private BuildClasspathEntryVisitor traverseClasspath(IProgressMonitor monitor) throws CoreException { // Use a classpath visitor to build up the build information BuildClasspathEntryVisitor visitor = new BuildClasspathEntryVisitor(javaProject); visitor.getRunner(true).run(javaProject, visitor, monitor); return visitor; } /** * Update the EclipseME build file based on the classpath information * collected during traversal. * * @param projectInfoMap */ private void updateEclipseMeBuildXml(Map projectInfoMap) { // Collect the elements Document doc = eclipseMeBuildXmlDocument; Element documentElement = doc.getDocumentElement(); Element pathElement = findElement(documentElement, "path"); Element wtkBuildElement = findElement(documentElement, "wtkbuild"); Element wtkPackageElement = findElement(documentElement, "wtkpackage"); Element previousBuildElement = wtkBuildElement; // Walk through the project info making the necessary updates Iterator iterator = projectInfoMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); ProjectInfo info = (ProjectInfo) entry.getValue(); // Set the property for the root of the project String propertyValue = info.getAntProjectPropertyValue(); propertyValue = (propertyValue.length() == 0) ? "${basedir}" : "${basedir}" + propertyValue; buildProperties.setProperty( info.getAntProjectPropertyName(), propertyValue); // Insert this project's classpath path definition pathElement.getParentNode().insertBefore(info.getClasspathElement(), pathElement); // Insert the project's wtkbuild calls Iterator elements = info.getWtkBuildElements(); while (elements.hasNext()) { Element element = (Element) elements.next(); // Add these to the build file such that the prereq projects // get built before the dependent projects wtkBuildElement.getParentNode().insertBefore(element, previousBuildElement); previousBuildElement = element; } // Insert the fileset definitions for packaging from this project if (info.isExported()) { // Add the classpath reference Element classpathElement = newChildElement(wtkPackageElement, "classpath"); classpathElement.setAttribute("refid", info.getClasspathElementId()); elements = info.getPackageFilesetElements().iterator(); while (elements.hasNext()) { Element element = (Element) elements.next(); wtkPackageElement.appendChild(element); } } } // Remove the marker elements pathElement.getParentNode().removeChild(pathElement); wtkBuildElement.getParentNode().removeChild(wtkBuildElement); // Update the wtkobfuscate parameters Element wktobfuscateElement = findElement(documentElement, "wtkobfuscate"); updateWtkObfuscateElement(wktobfuscateElement); } /** * Update the WTK obfuscate element to include the parameters. * * @param wktobfuscateElement */ private void updateWtkObfuscateElement(Element wktobfuscateElement) { String[] keepExpressions = PreferenceAccessor.instance.getProguardKeepExpressions(midletSuite.getProject()); for (int i = 0; i < keepExpressions.length; i++) { StringBuffer sb = new StringBuffer("'-keep "); sb.append(keepExpressions[i]).append("'"); addWtkObfuscateArgument(wktobfuscateElement, sb.toString()); } addWtkObfuscateArgument(wktobfuscateElement, getProguardOptions()); } /** * Validate that the antenna property is valid. * * @param monitor * @throws AntennaExportException */ private void validateAntenna(IProgressMonitor monitor) throws AntennaExportException { boolean valid = false; Preferences prefs = EclipseMECorePlugin.getDefault().getPluginPreferences(); String antennaPref = prefs.getString(IEclipseMECoreConstants.PREF_ANTENNA_JAR); File antennaFile = new File(antennaPref); if (antennaFile.exists()) { try { ZipFile zipFile = new ZipFile(antennaFile); ZipEntry entry = zipFile.getEntry("antenna.properties"); valid = (entry != null); zipFile.close(); } catch (IOException e) { // Assume these cases mean the file is invalid EclipseMECorePlugin.log(IStatus.WARNING, "Error testing Antenna settings", e); } } if (!valid) { throw new AntennaExportException("Antenna library not found or not valid.\nCheck the preference settings."); } } /** * Validate the environment prior to the export. Throw * an exception if the environment is not valid. * * @param monitor * @throws AntennaExportException if the environment is not valid */ private void validateEnvironment(IProgressMonitor monitor) throws AntennaExportException { validateAntenna(monitor); validateWTK(monitor); } /** * Validate that a Sun WTK can be found. * * @param monitor * @throws AntennaExportException */ private void validateWTK(IProgressMonitor monitor) throws AntennaExportException { File wtkRoot = getWTKRoot(); if ((wtkRoot == null) || !wtkRoot.exists()) { throw new AntennaExportException("Sun WTK not found.\nCheck the platform definition settings."); } } /** * Write out the build properties file. * * @param monitor * @throws IOException * @throws CoreException */ private void writeBuildProperties(IProgressMonitor monitor) throws IOException, CoreException { File buildPropsFile = getMidletSuiteFile("eclipseme-build.properties", monitor); FileOutputStream fos = new FileOutputStream(buildPropsFile); buildProperties.store(fos, " EclipseME Build Properties - DO NOT ALTER THIS FILE - Make changes in user-build.properties"); fos.close(); } /** * Write the EclipseME build.xml file. * * @throws TransformerException * @throws IOException * @throws CoreException */ private void writeEclipseMeBuildXml(IProgressMonitor monitor) throws TransformerException, IOException, CoreException { // Write the output File buildXmlFile = getMidletSuiteFile("eclipseme-build.xml", monitor); XMLUtils.writeDocument(buildXmlFile, eclipseMeBuildXmlDocument); } }

The table below shows all metrics for AntennaBuildExporter.java.

MetricValueDescription
BLOCKS91.00Number of blocks
BLOCK_COMMENT 0.00Number of block comment lines
COMMENTS347.00Comment lines
COMMENT_DENSITY 0.72Comment density
COMPARISONS45.00Number of comparison operators
CYCLOMATIC94.00Cyclomatic complexity
DECL_COMMENTS51.00Comments in declarations
DOC_COMMENT290.00Number of javadoc comment lines
ELOC483.00Effective lines of code
EXEC_COMMENTS49.00Comments in executable code
EXITS144.00Procedure exits
FUNCTIONS47.00Number of function declarations
HALSTEAD_DIFFICULTY74.72Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY161.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 1.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA0034 0.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 1.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 6.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 2.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 1.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 5.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 3.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 4.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 0.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 1.00JAVA0128 Public constructor in non-public class
JAVA0130 8.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 3.00JAVA0144 Line exceeds maximum M characters
JAVA01452162.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 7.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 1.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 3.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 1.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 1.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 1.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 1.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 2.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 2.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES1071.00Number of lines in the source file
LINE_COMMENT57.00Number of line comments
LOC590.00Lines of code
LOGICAL_LINES343.00Number of statements
LOOPS10.00Number of loops
NEST_DEPTH 4.00Maximum nesting depth
OPERANDS1575.00Number of operands
OPERATORS2437.00Number of operators
PARAMS54.00Number of formal parameter declarations
PROGRAM_LENGTH4012.00Halstead program length
PROGRAM_VOCAB577.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS107.00Number of return points from functions
SIZE33911.00Size of the file in bytes
UNIQUE_OPERANDS527.00Number of unique operands
UNIQUE_OPERATORS50.00Number of unique operators
WHITESPACE134.00Number of whitespace lines