diff options
Diffstat (limited to 'bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util')
19 files changed, 0 insertions, 4657 deletions
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/CodeFormatterUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/CodeFormatterUtil.java deleted file mode 100644 index 39c48470..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/CodeFormatterUtil.java +++ /dev/null @@ -1,383 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.util.Map; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.BadPositionCategoryException; -import org.eclipse.jface.text.DefaultPositionUpdater; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.Position; -import org.eclipse.text.edits.DeleteEdit; -import org.eclipse.text.edits.InsertEdit; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.wst.jsdt.core.IJavaScriptProject; -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.eclipse.wst.jsdt.core.ToolFactory; -import org.eclipse.wst.jsdt.core.dom.ASTNode; -import org.eclipse.wst.jsdt.core.dom.BodyDeclaration; -import org.eclipse.wst.jsdt.core.dom.Expression; -import org.eclipse.wst.jsdt.core.dom.Statement; -import org.eclipse.wst.jsdt.core.formatter.CodeFormatter; -import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants; -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; - -public class CodeFormatterUtil { - - /** - * Creates a string that represents the given number of indentation units. - * The returned string can contain tabs and/or spaces depending on the core - * formatter preferences. - * - * @param indentationUnits the number of indentation units to generate - * @param project the project from which to get the formatter settings, - * <code>null</code> if the workspace default should be used - * @return the indent string - */ - public static String createIndentString(int indentationUnits, IJavaScriptProject project) { - Map options= project != null ? project.getOptions(true) : JavaScriptCore.getOptions(); - return ToolFactory.createCodeFormatter(options).createIndentationString(indentationUnits); - } - - /** - * Gets the current tab width. - * - * @param project The project where the source is used, used for project - * specific options or <code>null</code> if the project is unknown - * and the workspace default should be used - * @return The tab width - */ - public static int getTabWidth(IJavaScriptProject project) { - /* - * If the tab-char is SPACE, FORMATTER_INDENTATION_SIZE is not used - * by the core formatter. - * We piggy back the visual tab length setting in that preference in - * that case. - */ - String key; - if (JavaScriptCore.SPACE.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) - key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE; - else - key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE; - - return getCoreOption(project, key, 4); - } - - /** - * Returns the current indent width. - * - * @param project the project where the source is used or <code>null</code> - * if the project is unknown and the workspace default should be used - * @return the indent width - * - */ - public static int getIndentWidth(IJavaScriptProject project) { - String key; - if (DefaultCodeFormatterConstants.MIXED.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) - key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE; - else - key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE; - - return getCoreOption(project, key, 4); - } - - /** - * Returns the possibly <code>project</code>-specific core preference - * defined under <code>key</code>. - * - * @param project the project to get the preference from, or - * <code>null</code> to get the global preference - * @param key the key of the preference - * @return the value of the preference - * - */ - private static String getCoreOption(IJavaScriptProject project, String key) { - if (project == null) - return JavaScriptCore.getOption(key); - return project.getOption(key, true); - } - - /** - * Returns the possibly <code>project</code>-specific core preference - * defined under <code>key</code>, or <code>def</code> if the value is - * not a integer. - * - * @param project the project to get the preference from, or - * <code>null</code> to get the global preference - * @param key the key of the preference - * @param def the default value - * @return the value of the preference - * - */ - private static int getCoreOption(IJavaScriptProject project, String key, int def) { - try { - return Integer.parseInt(getCoreOption(project, key)); - } catch (NumberFormatException e) { - return def; - } - } - - // transition code - - /** - * Old API. Consider to use format2 (TextEdit) - */ - public static String format(int kind, String string, int indentationLevel, int[] positions, String lineSeparator, Map options) { - return format(kind, string, 0, string.length(), indentationLevel, positions, lineSeparator, options); - } - - public static String format(int kind, String string, int indentationLevel, int[] positions, String lineSeparator, IJavaScriptProject project) { - Map options= project != null ? project.getOptions(true) : null; - return format(kind, string, 0, string.length(), indentationLevel, positions, lineSeparator, options); - } - - - /** - * Old API. Consider to use format2 (TextEdit) - */ - public static String format(int kind, String string, int offset, int length, int indentationLevel, int[] positions, String lineSeparator, Map options) { - TextEdit edit= format2(kind, string, offset, length, indentationLevel, lineSeparator, options); - if (edit == null) { - //JavaScriptPlugin.logErrorMessage("formatter failed to format (no edit returned). Will use unformatted text instead. kind: " + kind + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$ - return string.substring(offset, offset + length); - } - String formatted= getOldAPICompatibleResult(string, edit, indentationLevel, positions, lineSeparator, options); - return formatted.substring(offset, formatted.length() - (string.length() - (offset + length))); - } - - /** - * Old API. Consider to use format2 (TextEdit) - */ - public static String format(ASTNode node, String string, int indentationLevel, int[] positions, String lineSeparator, Map options) { - - TextEdit edit= format2(node, string, indentationLevel, lineSeparator, options); - if (edit == null) { - //JavaScriptPlugin.logErrorMessage("formatter failed to format (no edit returned). Will use unformatted text instead. node: " + node.getNodeType() + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$ - return string; - } - return getOldAPICompatibleResult(string, edit, indentationLevel, positions, lineSeparator, options); - } - - private static String getOldAPICompatibleResult(String string, TextEdit edit, int indentationLevel, int[] positions, String lineSeparator, Map options) { - Position[] p= null; - - if (positions != null) { - p= new Position[positions.length]; - for (int i= 0; i < positions.length; i++) { - p[i]= new Position(positions[i], 0); - } - } - String res= evaluateFormatterEdit(string, edit, p); - - if (positions != null) { - for (int i= 0; i < positions.length; i++) { - Position curr= p[i]; - positions[i]= curr.getOffset(); - } - } - return res; - } - - /** - * Evaluates the edit on the given string. - * @throws IllegalArgumentException If the positions are not inside the string, a - * IllegalArgumentException is thrown. - */ - public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) { - try { - Document doc= createDocument(string, positions); - edit.apply(doc, 0); - if (positions != null) { - for (int i= 0; i < positions.length; i++) { - Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$ - } - } - return doc.get(); - } catch (BadLocationException e) { - JavaScriptPlugin.log(e); // bug in the formatter - Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ - } - return null; - } - - /** - * Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind. - * @throws IllegalArgumentException If the offset and length are not inside the string, a - * IllegalArgumentException is thrown. - */ - public static TextEdit format2(int kind, String string, int offset, int length, int indentationLevel, String lineSeparator, Map options) { - if (offset < 0 || length < 0 || offset + length > string.length()) { - throw new IllegalArgumentException("offset or length outside of string. offset: " + offset + ", length: " + length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - } - return ToolFactory.createCodeFormatter(options).format(kind, string, offset, length, indentationLevel, lineSeparator); - } - - public static TextEdit format2(int kind, String string, int indentationLevel, String lineSeparator, Map options) { - return format2(kind, string, 0, string.length(), indentationLevel, lineSeparator, options); - } - - public static TextEdit reformat(int kind, String string, int offset, int length, int indentationLevel, String lineSeparator, Map options) { - if (offset < 0 || length < 0 || offset + length > string.length()) { - throw new IllegalArgumentException("offset or length outside of string. offset: " + offset + ", length: " + length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - } - return ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_EXISTING).format(kind, string, offset, length, indentationLevel, lineSeparator); - } - - public static TextEdit reformat(int kind, String string, int indentationLevel, String lineSeparator, Map options) { - return reformat(kind, string, 0, string.length(), indentationLevel, lineSeparator, options); - } - - /** - * Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind. - * @throws IllegalArgumentException If the offset and length are not inside the string, a - * IllegalArgumentException is thrown. - */ - public static TextEdit format2(ASTNode node, String str, int indentationLevel, String lineSeparator, Map options) { - int code; - String prefix= ""; //$NON-NLS-1$ - String suffix= ""; //$NON-NLS-1$ - if (node instanceof Statement) { - code= CodeFormatter.K_STATEMENTS; - if (node.getNodeType() == ASTNode.SWITCH_CASE) { - prefix= "switch(1) {"; //$NON-NLS-1$ - suffix= "}"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - } - } else if (node instanceof Expression && node.getNodeType() != ASTNode.VARIABLE_DECLARATION_EXPRESSION) { - code= CodeFormatter.K_EXPRESSION; - } else if (node instanceof BodyDeclaration) { - code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; - } else { - switch (node.getNodeType()) { - case ASTNode.ARRAY_TYPE: - case ASTNode.PRIMITIVE_TYPE: - case ASTNode.QUALIFIED_TYPE: - case ASTNode.SIMPLE_TYPE: - suffix= " x;"; //$NON-NLS-1$ - code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; - break; - case ASTNode.JAVASCRIPT_UNIT: - code= CodeFormatter.K_JAVASCRIPT_UNIT; - break; - case ASTNode.VARIABLE_DECLARATION_EXPRESSION: - case ASTNode.SINGLE_VARIABLE_DECLARATION: - suffix= ";"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - break; - case ASTNode.VARIABLE_DECLARATION_FRAGMENT: - prefix= "A "; //$NON-NLS-1$ - suffix= ";"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - break; - case ASTNode.PACKAGE_DECLARATION: - case ASTNode.IMPORT_DECLARATION: - suffix= "\nclass A {}"; //$NON-NLS-1$ - code= CodeFormatter.K_JAVASCRIPT_UNIT; - break; - case ASTNode.JSDOC: - suffix= "void foo();"; //$NON-NLS-1$ - code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; - break; - case ASTNode.CATCH_CLAUSE: - prefix= "try {}"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - break; - case ASTNode.ANONYMOUS_CLASS_DECLARATION: - prefix= "new A()"; //$NON-NLS-1$ - suffix= ";"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - break; - case ASTNode.MODIFIER: - suffix= " class x {}"; //$NON-NLS-1$ - code= CodeFormatter.K_JAVASCRIPT_UNIT; - break; - case ASTNode.MEMBER_REF: - case ASTNode.FUNCTION_REF: - case ASTNode.FUNCTION_REF_PARAMETER: - case ASTNode.TAG_ELEMENT: - case ASTNode.TEXT_ELEMENT: - // Javadoc formatting not yet supported: - return null; - default: - //Assert.isTrue(false, "Node type not covered: " + node.getClass().getName()); //$NON-NLS-1$ - return null; - } - } - - String concatStr= prefix + str + suffix; - TextEdit edit= ToolFactory.createCodeFormatter(options).format(code, concatStr, prefix.length(), str.length(), indentationLevel, lineSeparator); - if (prefix.length() > 0) { - edit= shifEdit(edit, prefix.length()); - } - return edit; - } - - private static TextEdit shifEdit(TextEdit oldEdit, int diff) { - TextEdit newEdit; - if (oldEdit instanceof ReplaceEdit) { - ReplaceEdit edit= (ReplaceEdit) oldEdit; - newEdit= new ReplaceEdit(edit.getOffset() - diff, edit.getLength(), edit.getText()); - } else if (oldEdit instanceof InsertEdit) { - InsertEdit edit= (InsertEdit) oldEdit; - newEdit= new InsertEdit(edit.getOffset() - diff, edit.getText()); - } else if (oldEdit instanceof DeleteEdit) { - DeleteEdit edit= (DeleteEdit) oldEdit; - newEdit= new DeleteEdit(edit.getOffset() - diff, edit.getLength()); - } else if (oldEdit instanceof MultiTextEdit) { - newEdit= new MultiTextEdit(); - } else { - return null; // not supported - } - TextEdit[] children= oldEdit.getChildren(); - for (int i= 0; i < children.length; i++) { - TextEdit shifted= shifEdit(children[i], diff); - if (shifted != null) { - newEdit.addChild(shifted); - } - } - return newEdit; - } - - private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException { - Document doc= new Document(string); - try { - if (positions != null) { - final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ - - doc.addPositionCategory(POS_CATEGORY); - doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { - protected boolean notDeleted() { - if (fOffset < fPosition.offset && (fPosition.offset + fPosition.length < fOffset + fLength)) { - fPosition.offset= fOffset + fLength; // deleted positions: set to end of remove - return false; - } - return true; - } - }); - for (int i= 0; i < positions.length; i++) { - try { - doc.addPosition(POS_CATEGORY, positions[i]); - } catch (BadLocationException e) { - throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - } - } - } - } catch (BadPositionCategoryException cannotHappen) { - // can not happen: category is correctly set up - } - return doc; - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/History.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/History.java deleted file mode 100644 index a8b7781c..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/History.java +++ /dev/null @@ -1,311 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.util.Collection; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.wst.jsdt.internal.corext.CorextMessages; -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.eclipse.wst.jsdt.internal.ui.JavaUIException; -import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * History stores a list of key, object pairs. The list is bounded at size - * MAX_HISTORY_SIZE. If the list exceeds this size the eldest element is removed - * from the list. An element can be added/renewed with a call to <code>accessed(Object)</code>. - * - * The history can be stored to/loaded from an xml file. - */ -public abstract class History { - - private static final String DEFAULT_ROOT_NODE_NAME= "histroyRootNode"; //$NON-NLS-1$ - private static final String DEFAULT_INFO_NODE_NAME= "infoNode"; //$NON-NLS-1$ - private static final int MAX_HISTORY_SIZE= 60; - - private static JavaUIException createException(Throwable t, String message) { - return new JavaUIException(JavaUIStatus.createError(IStatus.ERROR, message, t)); - } - - private final Map fHistory; - private final Hashtable fPositions; - private final String fFileName; - private final String fRootNodeName; - private final String fInfoNodeName; - - public History(String fileName, String rootNodeName, String infoNodeName) { - fHistory= new LinkedHashMap(80, 0.75f, true) { - private static final long serialVersionUID= 1L; - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > MAX_HISTORY_SIZE; - } - }; - fFileName= fileName; - fRootNodeName= rootNodeName; - fInfoNodeName= infoNodeName; - fPositions= new Hashtable(MAX_HISTORY_SIZE); - } - - public History(String fileName) { - this(fileName, DEFAULT_ROOT_NODE_NAME, DEFAULT_INFO_NODE_NAME); - } - - public synchronized void accessed(Object object) { - fHistory.put(getKey(object), object); - rebuildPositions(); - } - - public synchronized boolean contains(Object object) { - return fHistory.containsKey(getKey(object)); - } - - public synchronized boolean containsKey(Object key) { - return fHistory.containsKey(key); - } - - public synchronized boolean isEmpty() { - return fHistory.isEmpty(); - } - - public synchronized Object remove(Object object) { - Object removed= fHistory.remove(getKey(object)); - rebuildPositions(); - return removed; - } - - public synchronized Object removeKey(Object key) { - Object removed= fHistory.remove(key); - rebuildPositions(); - return removed; - } - - /** - * Normalized position in history of object denoted by key. - * The position is a value between zero and one where zero - * means not contained in history and one means newest element - * in history. The lower the value the older the element. - * - * @param key The key of the object to inspect - * @return value in [0.0, 1.0] the lower the older the element - */ - public synchronized float getNormalizedPosition(Object key) { - if (!containsKey(key)) - return 0.0f; - - int pos= ((Integer)fPositions.get(key)).intValue() + 1; - - //containsKey(key) implies fHistory.size()>0 - return (float)pos / (float)fHistory.size(); - } - - /** - * Absolute position of object denoted by key in the - * history or -1 if !containsKey(key). The higher the - * newer. - * - * @param key The key of the object to inspect - * @return value between 0 and MAX_HISTORY_SIZE - 1, or -1 - */ - public synchronized int getPosition(Object key) { - if (!containsKey(key)) - return -1; - - return ((Integer)fPositions.get(key)).intValue(); - } - - public synchronized void load() { - IPath stateLocation= JavaScriptPlugin.getDefault().getStateLocation().append(fFileName); - File file= new File(stateLocation.toOSString()); - if (file.exists()) { - InputStreamReader reader= null; - try { - reader = new InputStreamReader(new FileInputStream(file), "utf-8");//$NON-NLS-1$ - load(new InputSource(reader)); - } catch (IOException e) { - JavaScriptPlugin.log(e); - } catch (CoreException e) { - JavaScriptPlugin.log(e); - } finally { - try { - if (reader != null) - reader.close(); - } catch (IOException e) { - JavaScriptPlugin.log(e); - } - } - } - } - - public synchronized void save() { - IPath stateLocation= JavaScriptPlugin.getDefault().getStateLocation().append(fFileName); - File file= new File(stateLocation.toOSString()); - OutputStream out= null; - try { - out= new FileOutputStream(file); - save(out); - } catch (IOException e) { - JavaScriptPlugin.log(e); - } catch (CoreException e) { - JavaScriptPlugin.log(e); - } catch (TransformerFactoryConfigurationError e) { - // The XML library can be misconficgured (e.g. via - // -Djava.endorsed.dirs=C:\notExisting\xerces-2_7_1) - JavaScriptPlugin.log(e); - } finally { - try { - if (out != null) { - out.close(); - } - } catch (IOException e) { - JavaScriptPlugin.log(e); - } - } - } - - protected Set getKeys() { - return fHistory.keySet(); - } - - protected Collection getValues() { - return fHistory.values(); - } - - /** - * Store <code>Object</code> in <code>Element</code> - * - * @param object The object to store - * @param element The Element to store to - */ - protected abstract void setAttributes(Object object, Element element); - - /** - * Return a new instance of an Object given <code>element</code> - * - * @param element The element containing required information to create the Object - */ - protected abstract Object createFromElement(Element element); - - /** - * Get key for object - * - * @param object The object to calculate a key for, not null - * @return The key for object, not null - */ - protected abstract Object getKey(Object object); - - private void rebuildPositions() { - fPositions.clear(); - Collection values= fHistory.values(); - int pos=0; - for (Iterator iter= values.iterator(); iter.hasNext();) { - Object element= iter.next(); - fPositions.put(getKey(element), new Integer(pos)); - pos++; - } - } - - private void load(InputSource inputSource) throws CoreException { - Element root; - try { - DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - root = parser.parse(inputSource).getDocumentElement(); - } catch (SAXException e) { - throw createException(e, Messages.format(CorextMessages.History_error_read, fFileName)); - } catch (ParserConfigurationException e) { - throw createException(e, Messages.format(CorextMessages.History_error_read, fFileName)); - } catch (IOException e) { - throw createException(e, Messages.format(CorextMessages.History_error_read, fFileName)); - } - - if (root == null) return; - if (!root.getNodeName().equalsIgnoreCase(fRootNodeName)) { - return; - } - NodeList list= root.getChildNodes(); - int length= list.getLength(); - for (int i= 0; i < length; ++i) { - Node node= list.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element type= (Element) node; - if (type.getNodeName().equalsIgnoreCase(fInfoNodeName)) { - Object object= createFromElement(type); - if (object != null) { - fHistory.put(getKey(object), object); - } - } - } - } - rebuildPositions(); - } - - private void save(OutputStream stream) throws CoreException { - try { - DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); - DocumentBuilder builder= factory.newDocumentBuilder(); - Document document= builder.newDocument(); - - Element rootElement = document.createElement(fRootNodeName); - document.appendChild(rootElement); - - Iterator values= getValues().iterator(); - while (values.hasNext()) { - Object object= values.next(); - Element element= document.createElement(fInfoNodeName); - setAttributes(object, element); - rootElement.appendChild(element); - } - - Transformer transformer=TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$ - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ - DOMSource source = new DOMSource(document); - StreamResult result = new StreamResult(stream); - - transformer.transform(source, result); - } catch (TransformerException e) { - throw createException(e, Messages.format(CorextMessages.History_error_serialize, fFileName)); - } catch (ParserConfigurationException e) { - throw createException(e, Messages.format(CorextMessages.History_error_serialize, fFileName)); - } - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/IOCloser.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/IOCloser.java deleted file mode 100644 index 1d42717f..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/IOCloser.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; - -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; - -public class IOCloser { - public static void perform(Reader reader, InputStream stream) { - try { - rethrows(reader, stream); - } catch (IOException e) { - JavaScriptPlugin.log(e); - } - } - - public static void rethrows(Reader reader, InputStream stream) throws IOException { - if (reader != null) { - reader.close(); - return; - } - if (stream != null) { - stream.close(); - return; - } - } -} - diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaElementResourceMapping.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaElementResourceMapping.java deleted file mode 100644 index 77118a0d..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaElementResourceMapping.java +++ /dev/null @@ -1,398 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceVisitor; -import org.eclipse.core.resources.mapping.RemoteResourceMappingContext; -import org.eclipse.core.resources.mapping.ResourceMapping; -import org.eclipse.core.resources.mapping.ResourceMappingContext; -import org.eclipse.core.resources.mapping.ResourceTraversal; -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.wst.jsdt.core.IClassFile; -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; -import org.eclipse.wst.jsdt.core.IJavaScriptModel; -import org.eclipse.wst.jsdt.core.IJavaScriptProject; -import org.eclipse.wst.jsdt.core.IPackageFragment; -import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage; -import org.eclipse.wst.jsdt.internal.ui.model.JavaModelProvider; - -/** - * An abstract super class to describe mappings from a Java element to a - * set of resources. The class also provides factory methods to create - * resource mappings. - * - * - */ -public abstract class JavaElementResourceMapping extends ResourceMapping { - - protected JavaElementResourceMapping() { - } - - public IJavaScriptElement getJavaElement() { - Object o= getModelObject(); - if (o instanceof IJavaScriptElement) - return (IJavaScriptElement)o; - return null; - } - - public boolean equals(Object obj) { - if (!(obj instanceof JavaElementResourceMapping)) - return false; - return getJavaElement().equals(((JavaElementResourceMapping)obj).getJavaElement()); - } - - public int hashCode() { - IJavaScriptElement javaElement= getJavaElement(); - if (javaElement == null) - return super.hashCode(); - - return javaElement.hashCode(); - } - - public String getModelProviderId() { - return JavaModelProvider.JAVA_MODEL_PROVIDER_ID; - } - - public boolean contains(ResourceMapping mapping) { - if (mapping instanceof JavaElementResourceMapping) { - JavaElementResourceMapping javaMapping = (JavaElementResourceMapping) mapping; - IJavaScriptElement element = getJavaElement(); - IJavaScriptElement other = javaMapping.getJavaElement(); - if (other != null && element != null) - return element.getPath().isPrefixOf(other.getPath()); - } - return false; - } - - //---- the factory code --------------------------------------------------------------- - - private static final class JavaModelResourceMapping extends JavaElementResourceMapping { - private final IJavaScriptModel fJavaModel; - private JavaModelResourceMapping(IJavaScriptModel model) { - Assert.isNotNull(model); - fJavaModel= model; - } - public Object getModelObject() { - return fJavaModel; - } - public IProject[] getProjects() { - IJavaScriptProject[] projects= null; - try { - projects= fJavaModel.getJavaScriptProjects(); - } catch (JavaScriptModelException e) { - JavaScriptPlugin.log(e); - return new IProject[0]; - } - IProject[] result= new IProject[projects.length]; - for (int i= 0; i < projects.length; i++) { - result[i]= projects[i].getProject(); - } - return result; - } - public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - IJavaScriptProject[] projects= fJavaModel.getJavaScriptProjects(); - ResourceTraversal[] result= new ResourceTraversal[projects.length]; - for (int i= 0; i < projects.length; i++) { - result[i]= new ResourceTraversal(new IResource[] {projects[i].getProject()}, IResource.DEPTH_INFINITE, 0); - } - return result; - } - } - - private static final class JavaProjectResourceMapping extends JavaElementResourceMapping { - private final IJavaScriptProject fProject; - private JavaProjectResourceMapping(IJavaScriptProject project) { - Assert.isNotNull(project); - fProject= project; - } - public Object getModelObject() { - return fProject; - } - public IProject[] getProjects() { - return new IProject[] {fProject.getProject() }; - } - public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - return new ResourceTraversal[] { - new ResourceTraversal(new IResource[] {fProject.getProject()}, IResource.DEPTH_INFINITE, 0) - }; - } - } - - private static final class PackageFragementRootResourceMapping extends JavaElementResourceMapping { - private final IPackageFragmentRoot fRoot; - private PackageFragementRootResourceMapping(IPackageFragmentRoot root) { - Assert.isNotNull(root); - fRoot= root; - } - public Object getModelObject() { - return fRoot; - } - public IProject[] getProjects() { - return new IProject[] {fRoot.getJavaScriptProject().getProject() }; - } - public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - return new ResourceTraversal[] { - new ResourceTraversal(new IResource[] {fRoot.getResource()}, IResource.DEPTH_INFINITE, 0) - }; - } - } - - private static final class LocalPackageFragementTraversal extends ResourceTraversal { - private final IPackageFragment fPack; - public LocalPackageFragementTraversal(IPackageFragment pack) throws CoreException { - super(new IResource[] {pack.getResource()}, IResource.DEPTH_ONE, 0); - fPack= pack; - } - public void accept(IResourceVisitor visitor) throws CoreException { - IFile[] files= getPackageContent(fPack); - final IResource resource= fPack.getResource(); - if (resource != null) - visitor.visit(resource); - for (int i= 0; i < files.length; i++) { - visitor.visit(files[i]); - } - } - } - - private static final class PackageFragmentResourceMapping extends JavaElementResourceMapping { - private final IPackageFragment fPack; - private PackageFragmentResourceMapping(IPackageFragment pack) { - Assert.isNotNull(pack); - fPack= pack; - } - public Object getModelObject() { - return fPack; - } - public IProject[] getProjects() { - return new IProject[] { fPack.getJavaScriptProject().getProject() }; - } - public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - if (context instanceof RemoteResourceMappingContext) { - return new ResourceTraversal[] { - new ResourceTraversal(new IResource[] {fPack.getResource()}, IResource.DEPTH_ONE, 0) - }; - } else { - return new ResourceTraversal[] { new LocalPackageFragementTraversal(fPack) }; - } - } - public void accept(ResourceMappingContext context, IResourceVisitor visitor, IProgressMonitor monitor) throws CoreException { - if (context instanceof RemoteResourceMappingContext) { - super.accept(context, visitor, monitor); - } else { - // We assume a local context. - IFile[] files= getPackageContent(fPack); - if (monitor == null) - monitor= new NullProgressMonitor(); - monitor.beginTask("", files.length + 1); //$NON-NLS-1$ - final IResource resource= fPack.getResource(); - if (resource != null) - visitor.visit(resource); - monitor.worked(1); - for (int i= 0; i < files.length; i++) { - visitor.visit(files[i]); - monitor.worked(1); - } - } - } - } - - private static IFile[] getPackageContent(IPackageFragment pack) throws CoreException { - List result= new ArrayList(); - IContainer container= (IContainer)pack.getResource(); - if (container != null) { - IResource[] members= container.members(); - for (int m= 0; m < members.length; m++) { - IResource member= members[m]; - if (member instanceof IFile) { - IFile file= (IFile)member; - if ("class".equals(file.getFileExtension()) && file.isDerived()) //$NON-NLS-1$ - continue; - result.add(member); - } - } - } - return (IFile[])result.toArray(new IFile[result.size()]); - } - - - private static final class CompilationUnitResourceMapping extends JavaElementResourceMapping { - private final IJavaScriptUnit fUnit; - private CompilationUnitResourceMapping(IJavaScriptUnit unit) { - Assert.isNotNull(unit); - fUnit= unit; - } - public Object getModelObject() { - return fUnit; - } - public IProject[] getProjects() { - return new IProject[] {fUnit.getJavaScriptProject().getProject() }; - } - public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - return new ResourceTraversal[] { - new ResourceTraversal(new IResource[] {fUnit.getResource()}, IResource.DEPTH_ONE, 0) - }; - } - } - - private static final class ClassFileResourceMapping extends JavaElementResourceMapping { - private final IClassFile fClassFile; - private ClassFileResourceMapping(IClassFile classFile) { - fClassFile= classFile; - } - public Object getModelObject() { - return fClassFile; - } - public IProject[] getProjects() { - return new IProject[] { fClassFile.getJavaScriptProject().getProject() }; - } - public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - return new ResourceTraversal[] { - new ResourceTraversal(new IResource[] {fClassFile.getResource()}, IResource.DEPTH_ONE, 0) - }; - } - } - - private static final class LogicalPackageResourceMapping extends ResourceMapping { - private final IPackageFragment[] fFragments; - private LogicalPackageResourceMapping(IPackageFragment[] fragments) { - fFragments= fragments; - } - public Object getModelObject() { - return fFragments; - } - public IProject[] getProjects() { - Set result= new HashSet(); - for (int i= 0; i < fFragments.length; i++) { - result.add(fFragments[i].getJavaScriptProject().getProject()); - } - return (IProject[])result.toArray(new IProject[result.size()]); - } - public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - List result= new ArrayList(); - if (context instanceof RemoteResourceMappingContext) { - for (int i= 0; i < fFragments.length; i++) { - result.add(new ResourceTraversal( - new IResource[] {fFragments[i].getResource()}, IResource.DEPTH_ONE, 0)); - } - } else { - for (int i= 0; i < fFragments.length; i++) { - result.add(new LocalPackageFragementTraversal(fFragments[i])); - } - } - return (ResourceTraversal[])result.toArray(new ResourceTraversal[result.size()]); - } - - public String getModelProviderId() { - return JavaModelProvider.JAVA_MODEL_PROVIDER_ID; - } - } - - public static ResourceMapping create(IJavaScriptElement element) { - switch (element.getElementType()) { - case IJavaScriptElement.TYPE: - return create((IType)element); - case IJavaScriptElement.JAVASCRIPT_UNIT: - return create((IJavaScriptUnit)element); - case IJavaScriptElement.CLASS_FILE: - return create((IClassFile)element); - case IJavaScriptElement.PACKAGE_FRAGMENT: - return create((IPackageFragment)element); - case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT: - return create((IPackageFragmentRoot)element); - case IJavaScriptElement.JAVASCRIPT_PROJECT: - return create((IJavaScriptProject)element); - case IJavaScriptElement.JAVASCRIPT_MODEL: - return create((IJavaScriptModel)element); - default: - return null; - } - - } - - public static ResourceMapping create(final IJavaScriptModel model) { - return new JavaModelResourceMapping(model); - } - - public static ResourceMapping create(final IJavaScriptProject project) { - return new JavaProjectResourceMapping(project); - } - - public static ResourceMapping create(final IPackageFragmentRoot root) { - if (root.isExternal()) - return null; - return new PackageFragementRootResourceMapping(root); - } - - public static ResourceMapping create(final IPackageFragment pack) { - // test if in an archive - IPackageFragmentRoot root= (IPackageFragmentRoot)pack.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT); - if (!root.isArchive()) { - return new PackageFragmentResourceMapping(pack); - } - return null; - } - - public static ResourceMapping create(IJavaScriptUnit unit) { - if (unit == null) - return null; - return new CompilationUnitResourceMapping(unit.getPrimary()); - } - - public static ResourceMapping create(IClassFile classFile) { - // test if in a archive - IPackageFragmentRoot root= (IPackageFragmentRoot)classFile.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT); - if (!root.isArchive()) { - return new ClassFileResourceMapping(classFile); - } - return null; - } - - public static ResourceMapping create(IType type) { - // top level types behave like the CU - IJavaScriptElement parent= type.getParent(); - if (parent instanceof IJavaScriptUnit) { - return create((IJavaScriptUnit)parent); - } - return null; - } - - public static ResourceMapping create(LogicalPackage logicalPackage) { - IPackageFragment[] fragments= logicalPackage.getFragments(); - List toProcess= new ArrayList(fragments.length); - for (int i= 0; i < fragments.length; i++) { - // only add if not part of an archive - IPackageFragmentRoot root= (IPackageFragmentRoot)fragments[i].getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT); - if (!root.isArchive()) { - toProcess.add(fragments[i]); - } - } - if (toProcess.size() == 0) - return null; - return new LogicalPackageResourceMapping((IPackageFragment[])toProcess.toArray(new IPackageFragment[toProcess.size()])); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaModelUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaModelUtil.java deleted file mode 100644 index 0ad639fc..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaModelUtil.java +++ /dev/null @@ -1,947 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.filebuffers.ITextFileBufferManager; -import org.eclipse.core.filebuffers.LocationKind; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IStorage; -import org.eclipse.core.runtime.Assert; -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.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.RewriteSessionEditProcessor; -import org.eclipse.text.edits.MalformedTreeException; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer; -import org.eclipse.wst.jsdt.core.Flags; -import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer; -import org.eclipse.wst.jsdt.core.IIncludePathEntry; -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; -import org.eclipse.wst.jsdt.core.IField; -import org.eclipse.wst.jsdt.core.IJarEntryResource; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; -import org.eclipse.wst.jsdt.core.IJavaScriptProject; -import org.eclipse.wst.jsdt.core.ILocalVariable; -import org.eclipse.wst.jsdt.core.IMember; -import org.eclipse.wst.jsdt.core.IFunction; -import org.eclipse.wst.jsdt.core.IPackageFragment; -import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.ITypeHierarchy; -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.Signature; -import org.eclipse.wst.jsdt.core.WorkingCopyOwner; -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.internal.core.util.Util; -import org.eclipse.wst.jsdt.internal.corext.CorextMessages; -import org.eclipse.wst.jsdt.internal.corext.ValidateEditException; -import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil; -import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus; -import org.eclipse.wst.jsdt.launching.IVMInstall; -import org.eclipse.wst.jsdt.launching.IVMInstall2; -import org.eclipse.wst.jsdt.launching.JavaRuntime; - -/** - * Utility methods for the Java Model. - */ -public final class JavaModelUtil { - - /** - * Only use this suffix for creating new .java files. - * In general, use one of the three *JavaLike*(..) methods in JavaScriptCore or create - * a name from an existing compilation unit with {@link #getRenamedCUName(IJavaScriptUnit, String)} - * <p> - * Note: Unlike {@link JavaScriptCore#getJavaScriptLikeExtensions()}, this suffix includes a leading ".". - * </p> - * - * @see JavaScriptCore#getJavaScriptLikeExtensions() - * @see JavaScriptCore#isJavaScriptLikeFileName(String) - * @see JavaScriptCore#removeJavaScriptLikeExtension(String) - * @see #getRenamedCUName(IJavaScriptUnit, String) - */ - public static final String DEFAULT_CU_SUFFIX= ".js"; //$NON-NLS-1$ - - /** - * Finds a type by its qualified type name (dot separated). - * @param jproject The java project to search in - * @param fullyQualifiedName The fully qualified name (type name with enclosing type names and package (all separated by dots)) - * @return The type found, or null if not existing - */ - public static IType findType(IJavaScriptProject jproject, String fullyQualifiedName) throws JavaScriptModelException { - //workaround for bug 22883 - IType type= jproject.findType(fullyQualifiedName); - if (type != null) - return type; - IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); - for (int i= 0; i < roots.length; i++) { - IPackageFragmentRoot root= roots[i]; - type= findType(root, fullyQualifiedName); - if (type != null && type.exists()) - return type; - } - return null; - } - - /** - * Finds a type by its qualified type name (dot separated). - * @param jproject The java project to search in - * @param fullyQualifiedName The fully qualified name (type name with enclosing type names and package (all separated by dots)) - * @param owner the working copy owner - * @return The type found, or null if not existing - */ - public static IType findType(IJavaScriptProject jproject, String fullyQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException { - //workaround for bug 22883 - IType type= jproject.findType(fullyQualifiedName, owner); - if (type != null) - return type; - IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); - for (int i= 0; i < roots.length; i++) { - IPackageFragmentRoot root= roots[i]; - type= findType(root, fullyQualifiedName); - if (type != null && type.exists()) - return type; - } - return null; - } - - - - private static IType findType(IPackageFragmentRoot root, String fullyQualifiedName) throws JavaScriptModelException{ - IJavaScriptElement[] children= root.getChildren(); - for (int i= 0; i < children.length; i++) { - IJavaScriptElement element= children[i]; - if (element.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT){ - IPackageFragment pack= (IPackageFragment)element; - if (! fullyQualifiedName.startsWith(pack.getElementName())) - continue; - IType type= findType(pack, fullyQualifiedName); - if (type != null && type.exists()) - return type; - } - } - return null; - } - - private static IType findType(IPackageFragment pack, String fullyQualifiedName) throws JavaScriptModelException{ - IJavaScriptUnit[] cus= pack.getJavaScriptUnits(); - for (int i= 0; i < cus.length; i++) { - IJavaScriptUnit unit= cus[i]; - IType type= findType(unit, fullyQualifiedName); - if (type != null && type.exists()) - return type; - } - return null; - } - - private static IType findType(IJavaScriptUnit cu, String fullyQualifiedName) throws JavaScriptModelException{ - IType[] types= cu.getAllTypes(); - for (int i= 0; i < types.length; i++) { - IType type= types[i]; - if (getFullyQualifiedName(type).equals(fullyQualifiedName)) - return type; - } - return null; - } - - /** - * Finds a type container by container name. - * The returned element will be of type <code>IType</code> or a <code>IPackageFragment</code>. - * <code>null</code> is returned if the type container could not be found. - * @param jproject The Java project defining the context to search - * @param typeContainerName A dot separated name of the type container - * @see #getTypeContainerName(IType) - */ - public static IJavaScriptElement findTypeContainer(IJavaScriptProject jproject, String typeContainerName) throws JavaScriptModelException { - // try to find it as type - IJavaScriptElement result= jproject.findType(typeContainerName); - if (result == null) { - // find it as package - IPath path= new Path(typeContainerName.replace('.', '/')); - result= jproject.findElement(path); - if (!(result instanceof IPackageFragment)) { - result= null; - } - - } - return result; - } - - /** - * Finds a type in a compilation unit. Typical usage is to find the corresponding - * type in a working copy. - * @param cu the compilation unit to search in - * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots)) - * @return the type found, or null if not existing - */ - public static IType findTypeInCompilationUnit(IJavaScriptUnit cu, String typeQualifiedName) throws JavaScriptModelException { - IType[] types= cu.getAllTypes(); - for (int i= 0; i < types.length; i++) { - String currName= getTypeQualifiedName(types[i]); - if (typeQualifiedName.equals(currName)) { - return types[i]; - } - } - return null; - } - - /** - * Returns the element of the given compilation unit which is "equal" to the - * given element. Note that the given element usually has a parent different - * from the given compilation unit. - * - * @param cu the cu to search in - * @param element the element to look for - * @return an element of the given cu "equal" to the given element - */ - public static IJavaScriptElement findInCompilationUnit(IJavaScriptUnit cu, IJavaScriptElement element) { - IJavaScriptElement[] elements= cu.findElements(element); - if (elements != null && elements.length > 0) { - return elements[0]; - } - return null; - } - - /** - * Returns the qualified type name of the given type using '.' as separators. - * This is a replace for IType.getTypeQualifiedName() - * which uses '$' as separators. As '$' is also a valid character in an id - * this is ambiguous. JavaScriptCore PR: 1GCFUNT - */ - public static String getTypeQualifiedName(IType type) { - try { - if (type.isBinary() && !type.isAnonymous()) { - IType declaringType= type.getDeclaringType(); - if (declaringType != null) { - return getTypeQualifiedName(declaringType) + '.' + type.getElementName(); - } - } - } catch (JavaScriptModelException e) { - // ignore - } - return type.getTypeQualifiedName('.'); - } - - /** - * Returns the fully qualified name of the given type using '.' as separators. - * This is a replace for IType.getFullyQualifiedTypeName - * which uses '$' as separators. As '$' is also a valid character in an id - * this is ambiguous. JavaScriptCore PR: 1GCFUNT - */ - public static String getFullyQualifiedName(IType type) { - try { - if (type.isBinary() && !type.isAnonymous()) { - IType declaringType= type.getDeclaringType(); - if (declaringType != null) { - return getFullyQualifiedName(declaringType) + '.' + type.getElementName(); - } - } - } catch (JavaScriptModelException e) { - // ignore - } - return type.getFullyQualifiedName('.'); - } - - /** - * Returns the fully qualified name of a type's container. (package name or enclosing type name) - */ - public static String getTypeContainerName(IType type) { - IType outerType= type.getDeclaringType(); - if (outerType != null) { - return getFullyQualifiedName(outerType); - } else { - return type.getPackageFragment().getElementName(); - } - } - - - /** - * Concatenates two names. Uses a dot for separation. - * Both strings can be empty or <code>null</code>. - */ - public static String concatenateName(String name1, String name2) { - StringBuffer buf= new StringBuffer(); - if (name1 != null && name1.length() > 0) { - buf.append(name1); - } - if (name2 != null && name2.length() > 0) { - if (buf.length() > 0) { - buf.append('.'); - } - buf.append(name2); - } - return buf.toString(); - } - - /** - * Concatenates two names. Uses a dot for separation. - * Both strings can be empty or <code>null</code>. - */ - public static String concatenateName(char[] name1, char[] name2) { - StringBuffer buf= new StringBuffer(); - if (name1 != null && name1.length > 0) { - buf.append(name1); - } - if (name2 != null && name2.length > 0) { - if (buf.length() > 0) { - buf.append('.'); - } - buf.append(name2); - } - return buf.toString(); - } - - /** - * Evaluates if a member (possible from another package) is visible from - * elements in a package. - * @param member The member to test the visibility for - * @param pack The package in focus - */ - public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaScriptModelException { - - int type= member.getElementType(); - if (type == IJavaScriptElement.INITIALIZER || (type == IJavaScriptElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$ - return false; - } - - int otherflags= member.getFlags(); - if (Flags.isPublic(otherflags)) { - return true; - } else if (Flags.isPrivate(otherflags)) { - return false; - } - - IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT); - return (pack != null && otherpack != null && isSamePackage(pack, otherpack)); - } - - /** - * Evaluates if a member in the focus' element hierarchy is visible from - * elements in a package. - * @param member The member to test the visibility for - * @param pack The package of the focus element focus - */ - public static boolean isVisibleInHierarchy(IMember member, IPackageFragment pack) throws JavaScriptModelException { - int type= member.getElementType(); - if (type == IJavaScriptElement.INITIALIZER || (type == IJavaScriptElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$ - return false; - } - return true; - -// int otherflags= member.getFlags(); -// -// if (Flags.isPublic(otherflags)) { -// return true; -// } else if (Flags.isPrivate(otherflags)) { -// return false; -// } -// -// IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT); -// return (pack != null && pack.equals(otherpack)); - } - - - /** - * Returns the package fragment root of <code>IJavaScriptElement</code>. If the given - * element is already a package fragment root, the element itself is returned. - */ - public static IPackageFragmentRoot getPackageFragmentRoot(IJavaScriptElement element) { - return (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT); - } - - /** - * Finds a method in a type. - * This searches for a method with the same name and signature. Parameter types are only - * compared by the simple name, no resolving for the fully qualified type name is done. - * Constructors are only compared by parameters, not the name. - * @param name The name of the method to find - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor If the method is a constructor - * @return The first found method or <code>null</code>, if nothing found - */ - public static IFunction findMethod(String name, String[] paramTypes, boolean isConstructor, IType type) throws JavaScriptModelException { - IFunction[] methods= type.getFunctions(); - for (int i= 0; i < methods.length; i++) { - if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i])) { - return methods[i]; - } - } - return null; - } - - /** - * Finds a method in a type and all its super types. The super class hierarchy is searched first, then the super interfaces. - * This searches for a method with the same name and signature. Parameter types are only - * compared by the simple name, no resolving for the fully qualified type name is done. - * Constructors are only compared by parameters, not the name. - * NOTE: For finding overridden methods or for finding the declaring method, use {@link MethodOverrideTester} - * @param hierarchy The hierarchy containing the type - * @param type The type to start the search from - * @param name The name of the method to find - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor If the method is a constructor - * @return The first found method or <code>null</code>, if nothing found - */ - public static IFunction findMethodInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaScriptModelException { - IFunction method= findMethod(name, paramTypes, isConstructor, type); - if (method != null) { - return method; - } - IType superClass= hierarchy.getSuperclass(type); - if (superClass != null) { - IFunction res= findMethodInHierarchy(hierarchy, superClass, name, paramTypes, isConstructor); - if (res != null) { - return res; - } - } - return method; - } - - - /** - * Tests if a method equals to the given signature. - * Parameter types are only compared by the simple name, no resolving for - * the fully qualified type name is done. Constructors are only compared by - * parameters, not the name. - * @param name Name of the method - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor Specifies if the method is a constructor - * @return Returns <code>true</code> if the method has the given name and parameter types and constructor state. - */ - public static boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IFunction curr) throws JavaScriptModelException { - if (isConstructor || name.equals(curr.getElementName())) { - if (isConstructor == curr.isConstructor()) { - String[] currParamTypes= curr.getParameterTypes(); - if (paramTypes.length == currParamTypes.length) { - for (int i= 0; i < paramTypes.length; i++) { - String t1= Signature.getSimpleName(Signature.toString(paramTypes[i])); - String t2= Signature.getSimpleName(Signature.toString(currParamTypes[i])); - if (!t1.equals(t2)) { - return false; - } - } - return true; - } - } - } - return false; - } - - /** - * Tests if two <code>IPackageFragment</code>s represent the same logical java package. - * @return <code>true</code> if the package fragments' names are equal. - */ - public static boolean isSamePackage(IPackageFragment pack1, IPackageFragment pack2) { - return pack1.getElementName().equals(pack2.getElementName()); - } - - /** - * Checks if the field is boolean. - */ - public static boolean isBoolean(IField field) throws JavaScriptModelException{ - return field.getTypeSignature().equals(SignatureUtil.BOOLEAN_SIGNATURE); - } - - /** - * Resolves a type name in the context of the declaring type. - * - * @param refTypeSig the type name in signature notation (for example 'QVector') this can also be an array type, but dimensions will be ignored. - * @param declaringType the context for resolving (type where the reference was made in) - * @return returns the fully qualified type name or build-in-type name. if a unresolved type couldn't be resolved null is returned - */ - public static String getResolvedTypeName(String refTypeSig, IType declaringType) throws JavaScriptModelException { - int arrayCount= Signature.getArrayCount(refTypeSig); - char type= refTypeSig.charAt(arrayCount); - if (type == Signature.C_UNRESOLVED) { - String name= ""; //$NON-NLS-1$ - int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1); - if (semi == -1) { - throw new IllegalArgumentException(); - } - name= refTypeSig.substring(arrayCount + 1, semi); - - String[][] resolvedNames= declaringType.resolveType(name); - if (resolvedNames != null && resolvedNames.length > 0) { - return JavaModelUtil.concatenateName(resolvedNames[0][0], resolvedNames[0][1]); - } - return null; - } else { - return Signature.toString(refTypeSig.substring(arrayCount)); - } - } - - /** - * Returns if a CU can be edited. - */ - public static boolean isEditable(IJavaScriptUnit cu) { - Assert.isNotNull(cu); - IResource resource= cu.getPrimary().getResource(); - return (resource.exists() && !resource.getResourceAttributes().isReadOnly()); - } - - /** - * Returns true if a cu is a primary cu (original or shared working copy) - */ - public static boolean isPrimary(IJavaScriptUnit cu) { - return cu.getOwner() == null; - } - - /* - * http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253 - * - * Reconciling happens in a separate thread. This can cause a situation where the - * Java element gets disposed after an exists test has been done. So we should not - * log not present exceptions when they happen in working copies. - */ - public static boolean isExceptionToBeLogged(CoreException exception) { - if (!(exception instanceof JavaScriptModelException)) - return true; - JavaScriptModelException je= (JavaScriptModelException)exception; - if (!je.isDoesNotExist()) - return true; - IJavaScriptElement[] elements= je.getJavaScriptModelStatus().getElements(); - for (int i= 0; i < elements.length; i++) { - IJavaScriptElement element= elements[i]; - // if the element is already a compilation unit don't log - // does not exist exceptions. See bug - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=75894 - // for more details - if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) - continue; - IJavaScriptUnit unit= (IJavaScriptUnit)element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT); - if (unit == null) - return true; - if (!unit.isWorkingCopy()) - return true; - } - return false; - } - - public static IType[] getAllSuperTypes(IType type, IProgressMonitor pm) throws JavaScriptModelException { - // workaround for 23656 - IType[] superTypes= SuperTypeHierarchyCache.getTypeHierarchy(type).getAllSuperclasses(type); - return superTypes; - } - - public static boolean isSuperType(ITypeHierarchy hierarchy, IType possibleSuperType, IType type) { - // filed bug 112635 to add this method to ITypeHierarchy - IType superClass= hierarchy.getSuperclass(type); - if (superClass != null && (possibleSuperType.equals(superClass) || isSuperType(hierarchy, possibleSuperType, superClass))) { - return true; - } - return false; - } - - public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) { - char[] path = resourcePath.toString().toCharArray(); - for (int i = 0, length = exclusionPatterns.length; i < length; i++) { - char[] pattern= exclusionPatterns[i].toString().toCharArray(); - if (CharOperation.pathMatch(pattern, path, true, '/')) { - return true; - } - } - return false; - } - - - /* - * Returns whether the given resource path matches one of the exclusion - * patterns. - * - * @see IIncludePathEntry#getExclusionPatterns - */ - public final static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) { - if (exclusionPatterns == null) return false; - char[] path = resourcePath.toString().toCharArray(); - for (int i = 0, length = exclusionPatterns.length; i < length; i++) - if (CharOperation.pathMatch(exclusionPatterns[i], path, true, '/')) - return true; - return false; - } - - - /** - * Force a reconcile of a compilation unit. - * @param unit - */ - public static void reconcile(IJavaScriptUnit unit) throws JavaScriptModelException { - unit.reconcile( - IJavaScriptUnit.NO_AST, - false /* don't force problem detection */, - null /* use primary owner */, - null /* no progress monitor */); - } - - /** - * Helper method that tests if an classpath entry can be found in a - * container. <code>null</code> is returned if the entry can not be found - * or if the container does not allows the configuration of source - * attachments - * @param jproject The container's parent project - * @param containerPath The path of the container - * @param libPath The path of the library to be found - * @return IIncludePathEntry A classpath entry from the container of - * <code>null</code> if the container can not be modified. - * @throws JavaScriptModelException thrown if accessing the container failed - */ - public static IIncludePathEntry getClasspathEntryToEdit(IJavaScriptProject jproject, IPath containerPath, IPath libPath) throws JavaScriptModelException { - IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, jproject); - JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0)); - if (container != null && initializer != null && initializer.canUpdateJsGlobalScopeContainer(containerPath, jproject)) { - return findEntryInContainer(container, libPath); - } - return null; // attachment not possible - } - - /** - * Finds an entry in a container. <code>null</code> is returned if the entry can not be found - * @param container The container - * @param libPath The path of the library to be found - * @return IIncludePathEntry A classpath entry from the container of - * <code>null</code> if the container can not be modified. - */ - public static IIncludePathEntry findEntryInContainer(IJsGlobalScopeContainer container, IPath libPath) { - IIncludePathEntry[] entries= container.getIncludepathEntries(); - for (int i= 0; i < entries.length; i++) { - IIncludePathEntry curr= entries[i]; - IIncludePathEntry resolved= JavaScriptCore.getResolvedIncludepathEntry(curr); - if (resolved != null && libPath.equals(resolved.getPath())) { - return curr; // return the real entry - } - } - return null; // attachment not possible - } - - /** - * Get all compilation units of a selection. - * @param javaElements the selected java elements - * @return all compilation units containing and contained in elements from javaElements - * @throws JavaScriptModelException - */ - public static IJavaScriptUnit[] getAllCompilationUnits(IJavaScriptElement[] javaElements) throws JavaScriptModelException { - HashSet result= new HashSet(); - for (int i= 0; i < javaElements.length; i++) { - addAllCus(result, javaElements[i]); - } - return (IJavaScriptUnit[]) result.toArray(new IJavaScriptUnit[result.size()]); - } - - private static void addAllCus(HashSet/*<IJavaScriptUnit>*/ collector, IJavaScriptElement javaElement) throws JavaScriptModelException { - switch (javaElement.getElementType()) { - case IJavaScriptElement.JAVASCRIPT_PROJECT: - IJavaScriptProject javaProject= (IJavaScriptProject) javaElement; - IPackageFragmentRoot[] packageFragmentRoots= javaProject.getPackageFragmentRoots(); - for (int i= 0; i < packageFragmentRoots.length; i++) - addAllCus(collector, packageFragmentRoots[i]); - return; - - case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT: - IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot) javaElement; - if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE) - return; - IJavaScriptElement[] packageFragments= packageFragmentRoot.getChildren(); - for (int j= 0; j < packageFragments.length; j++) - addAllCus(collector, packageFragments[j]); - return; - - case IJavaScriptElement.PACKAGE_FRAGMENT: - IPackageFragment packageFragment= (IPackageFragment) javaElement; - collector.addAll(Arrays.asList(packageFragment.getJavaScriptUnits())); - return; - - case IJavaScriptElement.JAVASCRIPT_UNIT: - collector.add(javaElement); - return; - - default: - IJavaScriptElement cu= javaElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT); - if (cu != null) - collector.add(cu); - } - } - - - /** - * Sets all compliance settings in the given map to 5.0 - */ - public static void set50CompilanceOptions(Map map) { - setCompilanceOptions(map, JavaScriptCore.VERSION_1_5); - } - - public static void setCompilanceOptions(Map map, String compliance) { - if (JavaScriptCore.VERSION_1_6.equals(compliance)) { - map.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_6); - map.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_6); - map.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_6); - map.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR); - } else if (JavaScriptCore.VERSION_1_5.equals(compliance)) { - map.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_5); - map.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_5); - map.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_5); - map.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR); - } else if (JavaScriptCore.VERSION_1_4.equals(compliance)) { - map.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_4); - map.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_3); - map.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_2); - map.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.WARNING); - } else if (JavaScriptCore.VERSION_1_3.equals(compliance)) { - map.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_3); - map.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_3); - map.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_1); - map.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.IGNORE); - } else { - throw new IllegalArgumentException("Unsupported compliance: " + compliance); //$NON-NLS-1$ - } - } - - public static void setDefaultClassfileOptions(Map map, String compliance) { - map.put(JavaScriptCore.COMPILER_CODEGEN_INLINE_JSR_BYTECODE, is50OrHigher(compliance) ? JavaScriptCore.ENABLED : JavaScriptCore.DISABLED); - map.put(JavaScriptCore.COMPILER_LOCAL_VARIABLE_ATTR, JavaScriptCore.GENERATE); - map.put(JavaScriptCore.COMPILER_LINE_NUMBER_ATTR, JavaScriptCore.GENERATE); - map.put(JavaScriptCore.COMPILER_SOURCE_FILE_ATTR, JavaScriptCore.GENERATE); - map.put(JavaScriptCore.COMPILER_CODEGEN_UNUSED_LOCAL, JavaScriptCore.PRESERVE); - } - - /** - * @return returns if version 1 is less than version 2. - */ - public static boolean isVersionLessThan(String version1, String version2) { - return version1.compareTo(version2) < 0; - } - - public static boolean is50OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaScriptCore.VERSION_1_5); - } - - public static boolean is50OrHigher(IJavaScriptProject project) { - return is50OrHigher(project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true)); - } - - public static boolean is50OrHigherJRE(IJavaScriptProject project) throws CoreException { - IVMInstall vmInstall= JavaRuntime.getVMInstall(project); - if (!(vmInstall instanceof IVMInstall2)) - return true; // assume 5.0. - - String compliance= getCompilerCompliance((IVMInstall2) vmInstall, null); - if (compliance == null) - return true; // assume 5.0 - return compliance.startsWith(JavaScriptCore.VERSION_1_5) || compliance.startsWith(JavaScriptCore.VERSION_1_6); - } - - public static String getCompilerCompliance(IVMInstall2 vMInstall, String defaultCompliance) { - String version= vMInstall.getJavaVersion(); - if (version == null) { - return defaultCompliance; - } else if (version.startsWith(JavaScriptCore.VERSION_1_6)) { - return JavaScriptCore.VERSION_1_6; - } else if (version.startsWith(JavaScriptCore.VERSION_1_5)) { - return JavaScriptCore.VERSION_1_5; - } else if (version.startsWith(JavaScriptCore.VERSION_1_4)) { - return JavaScriptCore.VERSION_1_4; - } else if (version.startsWith(JavaScriptCore.VERSION_1_3)) { - return JavaScriptCore.VERSION_1_3; - } else if (version.startsWith(JavaScriptCore.VERSION_1_2)) { - return JavaScriptCore.VERSION_1_3; - } else if (version.startsWith(JavaScriptCore.VERSION_1_1)) { - return JavaScriptCore.VERSION_1_3; - } - return defaultCompliance; - } - -// public static String getExecutionEnvironmentCompliance(IExecutionEnvironment executionEnvironment) { -// String desc= executionEnvironment.getId(); -// if (desc.indexOf("1.6") != -1) { //$NON-NLS-1$ -// return JavaScriptCore.VERSION_1_6; -// } else if (desc.indexOf("1.5") != -1) { //$NON-NLS-1$ -// return JavaScriptCore.VERSION_1_5; -// } else if (desc.indexOf("1.4") != -1) { //$NON-NLS-1$ -// return JavaScriptCore.VERSION_1_4; -// } -// return JavaScriptCore.VERSION_1_3; -// } - - /** - * Compute a new name for a compilation unit, given the name of the new main type. - * This query tries to maintain the existing extension (e.g. ".java"). - * - * @param cu a compilation unit - * @param newMainName the new name of the cu's main type (without extension) - * @return the new name for the compilation unit - */ - public static String getRenamedCUName(IJavaScriptUnit cu, String newMainName) { - String oldName = cu.getElementName(); - int i = oldName.lastIndexOf('.'); - if (i != -1) { - return newMainName + oldName.substring(i); - } else { - return newMainName; - } - } - - /** - * Applies an text edit to a compilation unit. Filed bug 117694 against jdt.core. - * @param cu the compilation unit to apply the edit to - * @param edit the edit to apply - * @param save is set, save the CU after the edit has been applied - * @param monitor the progress monitor to use - * @throws CoreException Thrown when the access to the CU failed - * @throws ValidateEditException if validate edit fails - */ - public static void applyEdit(IJavaScriptUnit cu, TextEdit edit, boolean save, IProgressMonitor monitor) throws CoreException, ValidateEditException { - if (monitor == null) { - monitor= new NullProgressMonitor(); - } - monitor.beginTask(CorextMessages.JavaModelUtil_applyedit_operation, 3); - - try { - IDocument document= null; - try { - document= aquireDocument(cu, new SubProgressMonitor(monitor, 1)); - if (save) { - commitDocument(cu, document, edit, new SubProgressMonitor(monitor, 1)); - } else { - new RewriteSessionEditProcessor(document, edit, TextEdit.UPDATE_REGIONS).performEdits(); - } - } catch (BadLocationException e) { - throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e)); - } finally { - releaseDocument(cu, document, new SubProgressMonitor(monitor, 1)); - } - } finally { - monitor.done(); - } - } - - private static IDocument aquireDocument(IJavaScriptUnit cu, IProgressMonitor monitor) throws CoreException { - if (JavaModelUtil.isPrimary(cu)) { - IFile file= (IFile) cu.getResource(); - if (file.exists()) { - ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager(); - IPath path= cu.getPath(); - bufferManager.connect(path, LocationKind.IFILE, monitor); - return bufferManager.getTextFileBuffer(path, LocationKind.IFILE).getDocument(); - } - } - monitor.done(); - return new Document(cu.getSource()); - } - - private static void commitDocument(IJavaScriptUnit cu, IDocument document, TextEdit edit, IProgressMonitor monitor) throws CoreException, MalformedTreeException, BadLocationException { - if (JavaModelUtil.isPrimary(cu)) { - IFile file= (IFile) cu.getResource(); - if (file.exists()) { - IStatus status= Resources.makeCommittable(file, null); - if (!status.isOK()) { - throw new ValidateEditException(status); - } - new RewriteSessionEditProcessor(document, edit, TextEdit.UPDATE_REGIONS).performEdits(); // apply after file is commitable - - ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager(); - bufferManager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE).commit(monitor, true); - return; - } - } - // no commit possible, make sure changes are in - new RewriteSessionEditProcessor(document, edit, TextEdit.UPDATE_REGIONS).performEdits(); - } - - - private static void releaseDocument(IJavaScriptUnit cu, IDocument document, IProgressMonitor monitor) throws CoreException { - if (JavaModelUtil.isPrimary(cu)) { - IFile file= (IFile) cu.getResource(); - if (file.exists()) { - ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager(); - bufferManager.disconnect(file.getFullPath(), LocationKind.IFILE, monitor); - return; - } - } - cu.getBuffer().setContents(document.get()); - monitor.done(); - } - - public static boolean isImplicitImport(String qualifier, IJavaScriptUnit cu) { - if ("java.lang".equals(qualifier)) { //$NON-NLS-1$ - return true; - } - String packageName= cu.getParent().getElementName(); - if (qualifier.equals(packageName)) { - return true; - } - String typeName= JavaScriptCore.removeJavaScriptLikeExtension(cu.getElementName()); - String mainTypeName= JavaModelUtil.concatenateName(packageName, typeName); - return qualifier.equals(mainTypeName); - } - - public static boolean isOpenableStorage(Object storage) { - if (storage instanceof IJarEntryResource) { - return ((IJarEntryResource) storage).isFile(); - } else { - return storage instanceof IStorage; - } - } - - /** - * Returns true iff the given local variable is a parameter of its - * declaring method. - * - * TODO replace this method with new API when available: - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=48420 - * @param currentLocal the local variable to test - * - * @return returns true if the variable is a parameter - * @throws JavaScriptModelException - */ - public static boolean isParameter(ILocalVariable currentLocal) throws JavaScriptModelException { - - final IJavaScriptElement parent= currentLocal.getParent(); - if (parent instanceof IFunction) { - final String[] params= ((IFunction) parent).getParameterNames(); - for (int i= 0; i < params.length; i++) { - if (params[i].equals(currentLocal.getElementName())) - return true; - } - } - return false; - } - - - public static String getFilePackage(IJavaScriptElement javaElement) - { - IJavaScriptElement fileAncestor = javaElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT); - if (fileAncestor==null) - fileAncestor=javaElement.getAncestor(IJavaScriptElement.CLASS_FILE); - IPath filePath= fileAncestor.getResource().getFullPath(); - IJavaScriptElement rootElement=fileAncestor.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT); - IPath rootPath = rootElement.getResource().getFullPath(); - String relativePath = filePath.removeFirstSegments(rootPath.segmentCount()).toPortableString(); - int index=Util.indexOfJavaLikeExtension(relativePath); - if (index>=0) - relativePath=relativePath.substring(0,index); - relativePath=relativePath.replace('/', '.'); - return relativePath; - - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JdtFlags.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JdtFlags.java deleted file mode 100644 index f57932ca..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JdtFlags.java +++ /dev/null @@ -1,228 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.wst.jsdt.core.Flags; -import org.eclipse.wst.jsdt.core.IFunction; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; -import org.eclipse.wst.jsdt.core.IMember; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.dom.BodyDeclaration; -import org.eclipse.wst.jsdt.core.dom.IBinding; -import org.eclipse.wst.jsdt.core.dom.IFunctionBinding; -import org.eclipse.wst.jsdt.core.dom.IVariableBinding; -import org.eclipse.wst.jsdt.core.dom.Modifier; - - -public class JdtFlags { - private JdtFlags(){ - } - - public static final String VISIBILITY_STRING_PRIVATE= "private"; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PACKAGE= ""; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PROTECTED= "protected"; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PUBLIC= "public"; //$NON-NLS-1$ - - - public static final int VISIBILITY_CODE_INVALID= -1; - - public static boolean isAbstract(IMember member) throws JavaScriptModelException{ - return Flags.isAbstract(member.getFlags()); - } - - public static boolean isAbstract(IFunctionBinding member) { - return Modifier.isAbstract(member.getModifiers()); - } - - public static boolean isDeprecated(IMember member) throws JavaScriptModelException{ - return Flags.isDeprecated(member.getFlags()); - } - - public static boolean isFinal(IMember member) throws JavaScriptModelException{ - if (isAnonymousType(member)) - return true; - return false; - } - - public static boolean isPackageVisible(IMember member) throws JavaScriptModelException{ - return (! isPrivate(member) && ! isPublic(member)); - } - - public static boolean isPackageVisible(BodyDeclaration bodyDeclaration) { - return (! isPrivate(bodyDeclaration) && ! isProtected(bodyDeclaration) && ! isPublic(bodyDeclaration)); - } - - public static boolean isPackageVisible(IBinding binding) { - return (! isPrivate(binding) && ! isProtected(binding) && ! isPublic(binding)); - } - - public static boolean isPrivate(IMember member) throws JavaScriptModelException{ - return Flags.isPrivate(member.getFlags()); - } - - public static boolean isPrivate(BodyDeclaration bodyDeclaration) { - return Modifier.isPrivate(bodyDeclaration.getModifiers()); - } - - public static boolean isPrivate(IBinding binding) { - return Modifier.isPrivate(binding.getModifiers()); - } - - public static boolean isProtected(BodyDeclaration bodyDeclaration) { - return Modifier.isProtected(bodyDeclaration.getModifiers()); - } - - public static boolean isProtected(IBinding binding) { - return Modifier.isProtected(binding.getModifiers()); - } - - public static boolean isPublic(IMember member) throws JavaScriptModelException{ - return Flags.isPublic(member.getFlags()); - } - - public static boolean isPublic(IBinding binding) { - return Modifier.isPublic(binding.getModifiers()); - } - - - public static boolean isPublic(BodyDeclaration bodyDeclaration) { - return Modifier.isPublic(bodyDeclaration.getModifiers()); - } - - public static boolean isStatic(IMember member) throws JavaScriptModelException{ - return Flags.isStatic(member.getFlags()); - } - - public static boolean isStatic(IFunctionBinding methodBinding){ - return Modifier.isStatic(methodBinding.getModifiers()); - } - - public static boolean isStatic(IVariableBinding variableBinding){ - return Modifier.isStatic(variableBinding.getModifiers()); - } - - public static boolean isVarargs(IFunction method) throws JavaScriptModelException{ - return Flags.isVarargs(method.getFlags()); - } - - private static boolean isAnonymousType(IMember member) throws JavaScriptModelException { - return member.getElementType() == IJavaScriptElement.TYPE && - ((IType)member).isAnonymous(); - } - - public static int getVisibilityCode(IMember member) throws JavaScriptModelException { - if (isPublic(member)) - return Modifier.PUBLIC; - else if (isPackageVisible(member)) - return Modifier.NONE; - else if (isPrivate(member)) - return Modifier.PRIVATE; - Assert.isTrue(false); - return VISIBILITY_CODE_INVALID; - } - - public static int getVisibilityCode(BodyDeclaration bodyDeclaration) { - if (isPublic(bodyDeclaration)) - return Modifier.PUBLIC; - else if (isProtected(bodyDeclaration)) - return Modifier.PROTECTED; - else if (isPackageVisible(bodyDeclaration)) - return Modifier.NONE; - else if (isPrivate(bodyDeclaration)) - return Modifier.PRIVATE; - Assert.isTrue(false); - return VISIBILITY_CODE_INVALID; - } - - public static int getVisibilityCode(IBinding binding) { - if (isPublic(binding)) - return Modifier.PUBLIC; - else if (isProtected(binding)) - return Modifier.PROTECTED; - else if (isPackageVisible(binding)) - return Modifier.NONE; - else if (isPrivate(binding)) - return Modifier.PRIVATE; - Assert.isTrue(false); - return VISIBILITY_CODE_INVALID; - } - - - public static String getVisibilityString(int visibilityCode){ - if (Modifier.isPublic(visibilityCode)) - return VISIBILITY_STRING_PUBLIC; - if (Modifier.isProtected(visibilityCode)) - return VISIBILITY_STRING_PROTECTED; - if (Modifier.isPrivate(visibilityCode)) - return VISIBILITY_STRING_PRIVATE; - return VISIBILITY_STRING_PACKAGE; - } - - public static int getVisibilityCode(String visibilityString) { - Assert.isNotNull(visibilityString); - if (VISIBILITY_STRING_PACKAGE.equals(visibilityString)) - return 0; - else if (VISIBILITY_STRING_PRIVATE.equals(visibilityString)) - return Modifier.PRIVATE; - else if (VISIBILITY_STRING_PROTECTED.equals(visibilityString)) - return Modifier.PROTECTED; - else if (VISIBILITY_STRING_PUBLIC.equals(visibilityString)) - return Modifier.PUBLIC; - return VISIBILITY_CODE_INVALID; - } - - public static void assertVisibility(int visibility){ - Assert.isTrue( visibility == Modifier.PUBLIC || - visibility == Modifier.PROTECTED || - visibility == Modifier.NONE || - visibility == Modifier.PRIVATE); - } - - public static boolean isHigherVisibility(int newVisibility, int oldVisibility){ - assertVisibility(oldVisibility); - assertVisibility(newVisibility); - switch (oldVisibility) { - case Modifier.PRIVATE : - return newVisibility == Modifier.NONE - || newVisibility == Modifier.PUBLIC - || newVisibility == Modifier.PROTECTED; - case Modifier.NONE : - return newVisibility == Modifier.PUBLIC - || newVisibility == Modifier.PROTECTED; - - case Modifier.PROTECTED : - return newVisibility == Modifier.PUBLIC; - - case Modifier.PUBLIC : - return false; - default: - Assert.isTrue(false); - return false; - } - } - - public static int getLowerVisibility(int visibility1, int visibility2) { - if (isHigherVisibility(visibility1, visibility2)) - return visibility2; - else - return visibility1; - } - - public static int clearAccessModifiers(int flags) { - return clearFlag(Modifier.PROTECTED | Modifier.PUBLIC | Modifier.PRIVATE, flags); - } - - public static int clearFlag(int flag, int flags){ - return flags & ~ flag; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/LRUMap.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/LRUMap.java deleted file mode 100644 index ebafde9f..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/LRUMap.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.util.LinkedHashMap; - -/** - * - */ -public class LRUMap extends LinkedHashMap { - - private static final long serialVersionUID= 1L; - private final int fMaxSize; - - public LRUMap(int maxSize) { - super(maxSize, 0.75f, true); - fMaxSize= maxSize; - } - - protected boolean removeEldestEntry(java.util.Map.Entry eldest) { - return size() > fMaxSize; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java deleted file mode 100644 index 951eea68..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import com.ibm.icu.text.MessageFormat; - -/** - * Helper class to format message strings. - * - * - */ -public class Messages { - - public static String format(String message, Object object) { - return MessageFormat.format(message, new Object[] { object}); - } - - public static String format(String message, Object[] objects) { - return MessageFormat.format(message, objects); - } - - private Messages() { - // Not for instantiation - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/MethodOverrideTester.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/MethodOverrideTester.java deleted file mode 100644 index d05a9958..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/MethodOverrideTester.java +++ /dev/null @@ -1,373 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.wst.jsdt.core.Flags; -import org.eclipse.wst.jsdt.core.IFunction; -import org.eclipse.wst.jsdt.core.IMember; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.ITypeHierarchy; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.Signature; - - -public class MethodOverrideTester { - private static class Substitutions { - - public static final Substitutions EMPTY_SUBST= new Substitutions(); - - private HashMap fMap; - - public Substitutions() { - fMap= null; - } - - private String[] getSubstArray(String typeVariable) { - if (fMap != null) { - return (String[]) fMap.get(typeVariable); - } - return null; - } - - public String getSubstitution(String typeVariable) { - String[] subst= getSubstArray(typeVariable); - if (subst != null) { - return subst[0]; - } - return null; - } - - public String getErasure(String typeVariable) { - String[] subst= getSubstArray(typeVariable); - if (subst != null) { - return subst[1]; - } - return null; - } - } - - private final IType fFocusType; - private final ITypeHierarchy fHierarchy; - - private Map /* <IFunction, Substitutions> */ fMethodSubstitutions; - private Map /* <IType, Substitutions> */ fTypeVariableSubstitutions; - - public MethodOverrideTester(IType focusType, ITypeHierarchy hierarchy) { - if (focusType == null || hierarchy == null) { - throw new IllegalArgumentException(); - } - fFocusType= focusType; - fHierarchy= hierarchy; - fTypeVariableSubstitutions= null; - fMethodSubstitutions= null; - } - - public IType getFocusType() { - return fFocusType; - } - - public ITypeHierarchy getTypeHierarchy() { - return fHierarchy; - } - - /** - * Finds the method that declares the given method. A declaring method is the 'original' method declaration that does - * not override nor implement a method. <code>null</code> is returned it the given method does not override - * a method. When searching, super class are examined before implemented interfaces. - * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible. - * @throws JavaScriptModelException - */ - public IFunction findDeclaringMethod(IFunction overriding, boolean testVisibility) throws JavaScriptModelException { - IFunction result= null; - IFunction overridden= findOverriddenMethod(overriding, testVisibility); - while (overridden != null) { - result= overridden; - overridden= findOverriddenMethod(result, testVisibility); - } - return result; - } - - /** - * Finds the method that is overridden by the given method. - * First the super class is examined and then the implemented interfaces. - * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible. - * @throws JavaScriptModelException - */ - public IFunction findOverriddenMethod(IFunction overriding, boolean testVisibility) throws JavaScriptModelException { - int flags= overriding.getFlags(); - if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor()) { - return null; - } - - IType type= overriding.getDeclaringType(); - if (type==null) - return null; - IType superClass= fHierarchy.getSuperclass(type); - if (superClass != null) { - IFunction res= findOverriddenMethodInHierarchy(superClass, overriding); - if (res != null && !Flags.isPrivate(res.getFlags())) { - if (!testVisibility || JavaModelUtil.isVisibleInHierarchy(res, type.getPackageFragment())) { - return res; - } - } - } - return null; - } - - /** - * Finds the directly overridden method in a type and its super types. First the super class is examined and then the implemented interfaces. - * With generics it is possible that 2 methods in the same type are overidden at the same time. In that case, the first overridden method found is returned. - * @param type The type to find methods in - * @param overriding The overriding method - * @return The first overridden method or <code>null</code> if no method is overridden - * @throws JavaScriptModelException - */ - public IFunction findOverriddenMethodInHierarchy(IType type, IFunction overriding) throws JavaScriptModelException { - IFunction method= findOverriddenMethodInType(type, overriding); - if (method != null) { - return method; - } - IType superClass= fHierarchy.getSuperclass(type); - if (superClass != null) { - IFunction res= findOverriddenMethodInHierarchy(superClass, overriding); - if (res != null) { - return res; - } - } - return method; - } - - /** - * Finds an overridden method in a type. WWith generics it is possible that 2 methods in the same type are overidden at the same time. - * In that case the first overridden method found is returned. - * @param overriddenType The type to find methods in - * @param overriding The overriding method - * @return The first overridden method or <code>null</code> if no method is overridden - * @throws JavaScriptModelException - */ - public IFunction findOverriddenMethodInType(IType overriddenType, IFunction overriding) throws JavaScriptModelException { - IFunction[] overriddenMethods= overriddenType.getFunctions(); - for (int i= 0; i < overriddenMethods.length; i++) { - if (isSubsignature(overriding, overriddenMethods[i])) { - return overriddenMethods[i]; - } - } - return null; - } - - /** - * Finds an overriding method in a type. - * @param overridingType The type to find methods in - * @param overridden The overridden method - * @return The overriding method or <code>null</code> if no method is overriding. - * @throws JavaScriptModelException - */ - public IFunction findOverridingMethodInType(IType overridingType, IFunction overridden) throws JavaScriptModelException { - IFunction[] overridingMethods= overridingType.getFunctions(); - for (int i= 0; i < overridingMethods.length; i++) { - if (isSubsignature(overridingMethods[i], overridden)) { - return overridingMethods[i]; - } - } - return null; - } - - /** - * Tests if a method is a subsignature of another method. - * @param overriding overriding method (m1) - * @param overridden overridden method (m2) - * @return <code>true</code> iff the method <code>m1</code> is a subsignature of the method <code>m2</code>. - * This is one of the requirements for m1 to override m2. - * Accessibility and return types are not taken into account. - * Note that subsignature is <em>not</em> symmetric! - * @throws JavaScriptModelException - */ - public boolean isSubsignature(IFunction overriding, IFunction overridden) throws JavaScriptModelException { - if (!overridden.getElementName().equals(overriding.getElementName())) { - return false; - } - int nParameters= overridden.getNumberOfParameters(); - if (nParameters != overriding.getNumberOfParameters()) { - return false; - } - - return nParameters == 0 || hasCompatibleParameterTypes(overriding, overridden); - } - - private boolean hasCompatibleParameterTypes(IFunction overriding, IFunction overridden) throws JavaScriptModelException { - String[] overriddenParamTypes= overridden.getParameterTypes(); - String[] overridingParamTypes= overriding.getParameterTypes(); - - String[] substitutedOverriding= new String[overridingParamTypes.length]; - boolean testErasure= false; - - for (int i= 0; i < overridingParamTypes.length; i++) { - String overriddenParamSig= overriddenParamTypes[i]; - String overriddenParamName= getSubstitutedTypeName(overriddenParamSig, overridden); - String overridingParamName= getSubstitutedTypeName(overridingParamTypes[i], overriding); - substitutedOverriding[i]= overridingParamName; - if (!overriddenParamName.equals(overridingParamName)) { - testErasure= true; - break; - } - } - if (testErasure) { - for (int i= 0; i < overridingParamTypes.length; i++) { - String overriddenParamSig= overriddenParamTypes[i]; - String overriddenParamName= getErasedTypeName(overriddenParamSig, overridden); - String overridingParamName= substitutedOverriding[i]; - if (overridingParamName == null) - overridingParamName= getSubstitutedTypeName(overridingParamTypes[i], overriding); - if (!overriddenParamName.equals(overridingParamName)) { - return false; - } - } - } - return true; - } - - private String getVariableSubstitution(IMember context, String variableName) throws JavaScriptModelException { - IType type; - if (context instanceof IFunction) { - String subst= getMethodSubstitions((IFunction) context).getSubstitution(variableName); - if (subst != null) { - return subst; - } - type= context.getDeclaringType(); - } else { - type= (IType) context; - } - String subst= getTypeSubstitions(type).getSubstitution(variableName); - if (subst != null) { - return subst; - } - return variableName; // not a type variable - } - - private String getVariableErasure(IMember context, String variableName) throws JavaScriptModelException { - IType type; - if (context instanceof IFunction) { - String subst= getMethodSubstitions((IFunction) context).getErasure(variableName); - if (subst != null) { - return subst; - } - type= context.getDeclaringType(); - } else { - type= (IType) context; - } - String subst= getTypeSubstitions(type).getErasure(variableName); - if (subst != null) { - return subst; - } - return variableName; // not a type variable - } - - /* - * Returns the substitutions for a method's type parameters - */ - private Substitutions getMethodSubstitions(IFunction method) throws JavaScriptModelException { - if (fMethodSubstitutions == null) { - fMethodSubstitutions= new LRUMap(3); - } - - Substitutions s= (Substitutions) fMethodSubstitutions.get(method); - if (s == null) { - s= Substitutions.EMPTY_SUBST; - fMethodSubstitutions.put(method, s); - } - return s; - } - - /* - * Returns the substitutions for a type's type parameters - */ - private Substitutions getTypeSubstitions(IType type) throws JavaScriptModelException { - if (fTypeVariableSubstitutions == null) { - fTypeVariableSubstitutions= new HashMap(); - computeSubstitutions(fFocusType, null, null); - } - Substitutions subst= (Substitutions) fTypeVariableSubstitutions.get(type); - if (subst == null) { - return Substitutions.EMPTY_SUBST; - } - return subst; - } - - private void computeSubstitutions(IType instantiatedType, IType instantiatingType, String[] typeArguments) throws JavaScriptModelException { - Substitutions s= new Substitutions(); - fTypeVariableSubstitutions.put(instantiatedType, s); - - String superclassTypeSignature= instantiatedType.getSuperclassTypeSignature(); - if (superclassTypeSignature != null) { - IType superclass= fHierarchy.getSuperclass(instantiatedType); - if (superclass != null && !fTypeVariableSubstitutions.containsKey(superclass)) { - computeSubstitutions(superclass, instantiatedType, new String[0]); - } - } - } - - /** - * Translates the type signature to a 'normalized' type name where all variables are substituted for the given type or method context. - * The returned name contains only simple names and can be used to compare against other substituted type names - * @param typeSig The type signature to translate - * @param context The context for the substitution - * @return a type name - * @throws JavaScriptModelException - */ - private String getSubstitutedTypeName(String typeSig, IMember context) throws JavaScriptModelException { - return internalGetSubstitutedTypeName(typeSig, context, false, new StringBuffer()).toString(); - } - - private String getErasedTypeName(String typeSig, IMember context) throws JavaScriptModelException { - return internalGetSubstitutedTypeName(typeSig, context, true, new StringBuffer()).toString(); - } - - private StringBuffer internalGetSubstitutedTypeName(String typeSig, IMember context, boolean erasure, StringBuffer buf) throws JavaScriptModelException { - int sigKind= Signature.getTypeSignatureKind(typeSig); - switch (sigKind) { - case Signature.BASE_TYPE_SIGNATURE: - return buf.append(Signature.toString(typeSig)); - case Signature.ARRAY_TYPE_SIGNATURE: - internalGetSubstitutedTypeName(Signature.getElementType(typeSig), context, erasure, buf); - for (int i= Signature.getArrayCount(typeSig); i > 0; i--) { - buf.append('[').append(']'); - } - return buf; - case Signature.CLASS_TYPE_SIGNATURE: { - String erasureSig= typeSig; - String erasureName= Signature.getSimpleName(Signature.toString(erasureSig)); - - char ch= erasureSig.charAt(0); - if (ch == Signature.C_RESOLVED) { - buf.append(erasureName); - } else if (ch == Signature.C_UNRESOLVED) { // could be a type variable - if (erasure) { - buf.append(getVariableErasure(context, erasureName)); - } else { - buf.append(getVariableSubstitution(context, erasureName)); - } - } else { - Assert.isTrue(false, "Unknown class type signature"); //$NON-NLS-1$ - } - return buf; - } - default: - Assert.isTrue(false, "Unhandled type signature kind"); //$NON-NLS-1$ - return buf; - } - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/OpenTypeHistory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/OpenTypeHistory.java deleted file mode 100644 index 1a921e04..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/OpenTypeHistory.java +++ /dev/null @@ -1,419 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - package org.eclipse.wst.jsdt.internal.corext.util; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.filebuffers.ITextFileBuffer; -import org.eclipse.core.filebuffers.ITextFileBufferManager; -import org.eclipse.core.filebuffers.LocationKind; -import org.eclipse.core.filesystem.EFS; -import org.eclipse.core.filesystem.IFileInfo; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.wst.jsdt.core.ElementChangedEvent; -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; -import org.eclipse.wst.jsdt.core.IElementChangedListener; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; -import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta; -import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.search.SearchEngine; -import org.eclipse.wst.jsdt.core.search.TypeNameMatch; -import org.eclipse.wst.jsdt.internal.corext.CorextMessages; -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.w3c.dom.Element; - -/** - * History for the open type dialog. Object and keys are both {@link TypeNameMatch}s. - */ -public class OpenTypeHistory extends History { - - private static class TypeHistoryDeltaListener implements IElementChangedListener { - public void elementChanged(ElementChangedEvent event) { - if (processDelta(event.getDelta())) { - OpenTypeHistory.getInstance().markAsInconsistent(); - } - } - - /** - * Computes whether the history needs a consistency check or not. - * - * @param delta the Java element delta - * - * @return <code>true</code> if consistency must be checked - * <code>false</code> otherwise. - */ - private boolean processDelta(IJavaScriptElementDelta delta) { - IJavaScriptElement elem= delta.getElement(); - - boolean isChanged= delta.getKind() == IJavaScriptElementDelta.CHANGED; - boolean isRemoved= delta.getKind() == IJavaScriptElementDelta.REMOVED; - - switch (elem.getElementType()) { - case IJavaScriptElement.JAVASCRIPT_PROJECT: - if (isRemoved || (isChanged && - (delta.getFlags() & IJavaScriptElementDelta.F_CLOSED) != 0)) { - return true; - } - return processChildrenDelta(delta); - case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT: - if (isRemoved || (isChanged && ( - (delta.getFlags() & IJavaScriptElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0 || - (delta.getFlags() & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) != 0))) { - return true; - } - return processChildrenDelta(delta); - case IJavaScriptElement.TYPE: - if (isChanged && (delta.getFlags() & IJavaScriptElementDelta.F_MODIFIERS) != 0) { - return true; - } - // type children can be inner classes: fall through - //$FALL-THROUGH$ - case IJavaScriptElement.JAVASCRIPT_MODEL: - case IJavaScriptElement.PACKAGE_FRAGMENT: - case IJavaScriptElement.CLASS_FILE: - if (isRemoved) { - return true; - } - return processChildrenDelta(delta); - case IJavaScriptElement.JAVASCRIPT_UNIT: - // Not the primary compilation unit. Ignore it - if (!JavaModelUtil.isPrimary((IJavaScriptUnit) elem)) { - return false; - } - - if (isRemoved || (isChanged && isUnknownStructuralChange(delta.getFlags()))) { - return true; - } - return processChildrenDelta(delta); - default: - // fields, methods, imports ect - return false; - } - } - - private boolean isUnknownStructuralChange(int flags) { - if ((flags & IJavaScriptElementDelta.F_CONTENT) == 0) - return false; - return (flags & IJavaScriptElementDelta.F_FINE_GRAINED) == 0; - } - - /* - private boolean isPossibleStructuralChange(int flags) { - return (flags & (IJavaScriptElementDelta.F_CONTENT | IJavaScriptElementDelta.F_FINE_GRAINED)) == IJavaScriptElementDelta.F_CONTENT; - } - */ - - private boolean processChildrenDelta(IJavaScriptElementDelta delta) { - IJavaScriptElementDelta[] children= delta.getAffectedChildren(); - for (int i= 0; i < children.length; i++) { - if (processDelta(children[i])) { - return true; - } - } - return false; - } - } - - private static class UpdateJob extends Job { - public static final String FAMILY= UpdateJob.class.getName(); - public UpdateJob() { - super(CorextMessages.TypeInfoHistory_consistency_check); - } - protected IStatus run(IProgressMonitor monitor) { - OpenTypeHistory history= OpenTypeHistory.getInstance(); - history.internalCheckConsistency(monitor); - return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ - } - public boolean belongsTo(Object family) { - return FAMILY.equals(family); - } - } - - // Needs to be volatile since accesses aren't synchronized. - private volatile boolean fNeedsConsistencyCheck; - // Map of cached time stamps - private Map fTimestampMapping; - - private final IElementChangedListener fDeltaListener; - private final UpdateJob fUpdateJob; - - private static final String FILENAME= "OpenTypeHistory.xml"; //$NON-NLS-1$ - private static final String NODE_ROOT= "typeInfoHistroy"; //$NON-NLS-1$ - private static final String NODE_TYPE_INFO= "typeInfo"; //$NON-NLS-1$ - private static final String NODE_HANDLE= "handle"; //$NON-NLS-1$ - private static final String NODE_MODIFIERS= "modifiers"; //$NON-NLS-1$ - private static final String NODE_TIMESTAMP= "timestamp"; //$NON-NLS-1$ - - private static OpenTypeHistory fgInstance; - - public static synchronized OpenTypeHistory getInstance() { - if (fgInstance == null) - fgInstance= new OpenTypeHistory(); - return fgInstance; - } - - public static synchronized void shutdown() { - if (fgInstance == null) - return; - fgInstance.doShutdown(); - } - - private OpenTypeHistory() { - super(FILENAME, NODE_ROOT, NODE_TYPE_INFO); - fTimestampMapping= new HashMap(); - fNeedsConsistencyCheck= true; - load(); - fDeltaListener= new TypeHistoryDeltaListener(); - JavaScriptCore.addElementChangedListener(fDeltaListener); - fUpdateJob= new UpdateJob(); - // It is not necessary anymore that the update job has a rule since - // markAsInconsistent isn't synchronized anymore. See bugs - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=128399 and - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=135278 - // for details. - fUpdateJob.setPriority(Job.SHORT); - } - - public void markAsInconsistent() { - fNeedsConsistencyCheck= true; - // cancel the old job. If no job is running this is a NOOP. - fUpdateJob.cancel(); - fUpdateJob.schedule(); - } - - public boolean needConsistencyCheck() { - return fNeedsConsistencyCheck; - } - - public void checkConsistency(IProgressMonitor monitor) throws OperationCanceledException { - if (!fNeedsConsistencyCheck) - return; - if (fUpdateJob.getState() == Job.RUNNING) { - try { - Job.getJobManager().join(UpdateJob.FAMILY, monitor); - } catch (OperationCanceledException e) { - // Ignore and do the consistency check without - // waiting for the update job. - } catch (InterruptedException e) { - // Ignore and do the consistency check without - // waiting for the update job. - } - } - if (!fNeedsConsistencyCheck) - return; - internalCheckConsistency(monitor); - } - - public synchronized boolean contains(TypeNameMatch type) { - return super.contains(type); - } - - public synchronized void accessed(TypeNameMatch info) { - // Fetching the timestamp might not be cheap (remote file system - // external Jars. So check if we alreay have one. - if (!fTimestampMapping.containsKey(info)) { - fTimestampMapping.put(info, new Long(getContainerTimestamp(info))); - } - super.accessed(info); - } - - public synchronized TypeNameMatch remove(TypeNameMatch info) { - fTimestampMapping.remove(info); - return (TypeNameMatch)super.remove(info); - } - - public synchronized void replace(TypeNameMatch old, TypeNameMatch newMatch) { - fTimestampMapping.remove(old); - fTimestampMapping.put(newMatch, new Long(getContainerTimestamp(newMatch))); - super.remove(old); - super.accessed(newMatch); - } - - public synchronized TypeNameMatch[] getTypeInfos() { - Collection values= getValues(); - int size= values.size(); - TypeNameMatch[] result= new TypeNameMatch[size]; - int i= size - 1; - for (Iterator iter= values.iterator(); iter.hasNext();) { - result[i]= (TypeNameMatch)iter.next(); - i--; - } - return result; - } - - public synchronized TypeNameMatch[] getFilteredTypeInfos(TypeInfoFilter filter) { - Collection values= getValues(); - List result= new ArrayList(); - for (Iterator iter= values.iterator(); iter.hasNext();) { - TypeNameMatch type= (TypeNameMatch)iter.next(); - if ((filter == null || filter.matchesHistoryElement(type)) && !TypeFilter.isFiltered(type.getFullyQualifiedName())) - result.add(type); - } - Collections.reverse(result); - return (TypeNameMatch[])result.toArray(new TypeNameMatch[result.size()]); - - } - - protected Object getKey(Object object) { - return object; - } - - private synchronized void internalCheckConsistency(IProgressMonitor monitor) throws OperationCanceledException { - // Setting fNeedsConsistencyCheck is necessary here since - // markAsInconsistent isn't synchronized. - fNeedsConsistencyCheck= true; - List typesToCheck= new ArrayList(getKeys()); - monitor.beginTask(CorextMessages.TypeInfoHistory_consistency_check, typesToCheck.size()); - monitor.setTaskName(CorextMessages.TypeInfoHistory_consistency_check); - for (Iterator iter= typesToCheck.iterator(); iter.hasNext();) { - TypeNameMatch type= (TypeNameMatch)iter.next(); - long currentTimestamp= getContainerTimestamp(type); - Long lastTested= (Long)fTimestampMapping.get(type); - if (lastTested != null && currentTimestamp != IResource.NULL_STAMP && currentTimestamp == lastTested.longValue() && !isContainerDirty(type)) - continue; - try { - IType jType= type.getType(); - if (jType == null || !jType.exists()) { - remove(type); - } else { - // copy over the modifiers since they may have changed - int modifiers= jType.getFlags(); - if (modifiers != type.getModifiers()) { - replace(type, SearchEngine.createTypeNameMatch(jType, modifiers)); - } else { - fTimestampMapping.put(type, new Long(currentTimestamp)); - } - } - } catch (JavaScriptModelException e) { - remove(type); - } - if (monitor.isCanceled()) - throw new OperationCanceledException(); - monitor.worked(1); - } - monitor.done(); - fNeedsConsistencyCheck= false; - } - - private long getContainerTimestamp(TypeNameMatch match) { - try { - IType type= match.getType(); - IResource resource= type.getResource(); - if (resource != null) { - URI location= resource.getLocationURI(); - if (location != null) { - IFileInfo info= EFS.getStore(location).fetchInfo(); - if (info.exists()) { - // The element could be removed from the build path. So check - // if the Java element still exists. - IJavaScriptElement element= JavaScriptCore.create(resource); - if (element != null && element.exists()) - return info.getLastModified(); - } - } - } else { // external JAR - IPackageFragmentRoot root= match.getPackageFragmentRoot(); - if (root.exists()) { - IFileInfo info= EFS.getLocalFileSystem().getStore(root.getPath()).fetchInfo(); - if (info.exists()) { - return info.getLastModified(); - } - } - } - } catch (CoreException e) { - // Fall through - } - return IResource.NULL_STAMP; - } - - - public boolean isContainerDirty(TypeNameMatch match) { - IJavaScriptUnit cu= match.getType().getJavaScriptUnit(); - if (cu == null) { - return false; - } - IResource resource= cu.getResource(); - ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); - ITextFileBuffer textFileBuffer= manager.getTextFileBuffer(resource.getFullPath(), LocationKind.IFILE); - if (textFileBuffer != null) { - return textFileBuffer.isDirty(); - } - return false; - } - - - private void doShutdown() { - JavaScriptCore.removeElementChangedListener(fDeltaListener); - save(); - } - - protected Object createFromElement(Element type) { - String handle= type.getAttribute(NODE_HANDLE); - if (handle == null ) - return null; - - IJavaScriptElement element= JavaScriptCore.create(handle); - if (!(element instanceof IType)) - return null; - - int modifiers= 0; - try { - modifiers= Integer.parseInt(type.getAttribute(NODE_MODIFIERS)); - } catch (NumberFormatException e) { - // take zero - } - TypeNameMatch info= SearchEngine.createTypeNameMatch((IType) element, modifiers); - long timestamp= IResource.NULL_STAMP; - String timestampValue= type.getAttribute(NODE_TIMESTAMP); - if (timestampValue != null && timestampValue.length() > 0) { - try { - timestamp= Long.parseLong(timestampValue); - } catch (NumberFormatException e) { - // take null stamp - } - } - if (timestamp != IResource.NULL_STAMP) { - fTimestampMapping.put(info, new Long(timestamp)); - } - return info; - } - - protected void setAttributes(Object object, Element typeElement) { - TypeNameMatch type= (TypeNameMatch) object; - String handleId= type.getType().getHandleIdentifier(); - typeElement.setAttribute(NODE_HANDLE, handleId); - typeElement.setAttribute(NODE_MODIFIERS, Integer.toString(type.getModifiers())); - Long timestamp= (Long) fTimestampMapping.get(type); - if (timestamp == null) { - typeElement.setAttribute(NODE_TIMESTAMP, Long.toString(IResource.NULL_STAMP)); - } else { - typeElement.setAttribute(NODE_TIMESTAMP, timestamp.toString()); - } - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/QualifiedTypeNameHistory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/QualifiedTypeNameHistory.java deleted file mode 100644 index 36a2b1c0..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/QualifiedTypeNameHistory.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import org.w3c.dom.Element; - -public class QualifiedTypeNameHistory extends History { - - private static final String NODE_ROOT= "qualifiedTypeNameHistroy"; //$NON-NLS-1$ - private static final String NODE_TYPE_INFO= "fullyQualifiedTypeName"; //$NON-NLS-1$ - private static final String NODE_NAME= "name"; //$NON-NLS-1$ - - private static QualifiedTypeNameHistory fgInstance; - - - public static QualifiedTypeNameHistory getDefault() { - if (fgInstance == null) - fgInstance= new QualifiedTypeNameHistory("QualifiedTypeNameHistory.xml"); //$NON-NLS-1$ - - return fgInstance; - } - - public QualifiedTypeNameHistory(String fileName) { - super(fileName, NODE_ROOT, NODE_TYPE_INFO); - load(); - } - - /** - * {@inheritDoc} - */ - protected void setAttributes(Object object, Element element) { - element.setAttribute(NODE_NAME, (String)object); - } - - /** - * {@inheritDoc} - */ - protected Object createFromElement(Element element) { - return element.getAttribute(NODE_NAME); - } - - /** - * {@inheritDoc} - */ - protected Object getKey(Object object) { - return object; - } - - public static int getBoost(String fullyQualifiedTypeName, int min, int max) { - float position= getDefault().getNormalizedPosition(fullyQualifiedTypeName); - int dist= max - min; - return Math.round(position * dist) + min; - } - - public static void remember(String fullyQualifiedTypeName) { - getDefault().accessed(fullyQualifiedTypeName); - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Resources.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Resources.java deleted file mode 100644 index 49a58b8d..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Resources.java +++ /dev/null @@ -1,238 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.io.File; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.filesystem.EFS; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceStatus; -import org.eclipse.core.resources.ResourceAttributes; -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.MultiStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.wst.jsdt.internal.corext.CorextMessages; -import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants; -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus; - -public class Resources { - - private Resources() { - } - - /** - * Checks if the given resource is in sync with the underlying file system. - * - * @param resource the resource to be checked - * @return IStatus status describing the check's result. If <code>status. - * isOK()</code> returns <code>true</code> then the resource is in sync - */ - public static IStatus checkInSync(IResource resource) { - return checkInSync(new IResource[] {resource}); - } - - /** - * Checks if the given resources are in sync with the underlying file - * system. - * - * @param resources the resources to be checked - * @return IStatus status describing the check's result. If <code>status. - * isOK() </code> returns <code>true</code> then the resources are in sync - */ - public static IStatus checkInSync(IResource[] resources) { - IStatus result= null; - for (int i= 0; i < resources.length; i++) { - IResource resource= resources[i]; - if (!resource.isSynchronized(IResource.DEPTH_INFINITE)) { - result= addOutOfSync(result, resource); - } - } - if (result != null) - return result; - return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ - } - - /** - * Makes the given resource committable. Committable means that it is - * writeable and that its content hasn't changed by calling - * <code>validateEdit</code> for the given resource on <tt>IWorkspace</tt>. - * - * @param resource the resource to be checked - * @param context the context passed to <code>validateEdit</code> - * @return status describing the method's result. If <code>status.isOK()</code> returns <code>true</code> then the resources are committable. - * - * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object) - */ - public static IStatus makeCommittable(IResource resource, Object context) { - return makeCommittable(new IResource[] { resource }, context); - } - - /** - * Makes the given resources committable. Committable means that all - * resources are writeable and that the content of the resources hasn't - * changed by calling <code>validateEdit</code> for a given file on - * <tt>IWorkspace</tt>. - * - * @param resources the resources to be checked - * @param context the context passed to <code>validateEdit</code> - * @return IStatus status describing the method's result. If <code>status. - * isOK()</code> returns <code>true</code> then the add resources are - * committable - * - * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object) - */ - public static IStatus makeCommittable(IResource[] resources, Object context) { - List readOnlyFiles= new ArrayList(); - for (int i= 0; i < resources.length; i++) { - IResource resource= resources[i]; - if (resource.getType() == IResource.FILE && isReadOnly(resource)) - readOnlyFiles.add(resource); - } - if (readOnlyFiles.size() == 0) - return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ - - Map oldTimeStamps= createModificationStampMap(readOnlyFiles); - IStatus status= ResourcesPlugin.getWorkspace().validateEdit( - (IFile[]) readOnlyFiles.toArray(new IFile[readOnlyFiles.size()]), context); - if (!status.isOK()) - return status; - - IStatus modified= null; - Map newTimeStamps= createModificationStampMap(readOnlyFiles); - for (Iterator iter= oldTimeStamps.keySet().iterator(); iter.hasNext();) { - IFile file= (IFile) iter.next(); - if (!oldTimeStamps.get(file).equals(newTimeStamps.get(file))) - modified= addModified(modified, file); - } - if (modified != null) - return modified; - return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ - } - - private static Map createModificationStampMap(List files){ - Map map= new HashMap(); - for (Iterator iter= files.iterator(); iter.hasNext(); ) { - IFile file= (IFile)iter.next(); - map.put(file, new Long(file.getModificationStamp())); - } - return map; - } - - private static IStatus addModified(IStatus status, IFile file) { - IStatus entry= JavaUIStatus.createError( - IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT, - Messages.format(CorextMessages.Resources_fileModified, file.getFullPath().toString()), - null); - if (status == null) { - return entry; - } else if (status.isMultiStatus()) { - ((MultiStatus)status).add(entry); - return status; - } else { - MultiStatus result= new MultiStatus(JavaScriptPlugin.getPluginId(), - IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT, - CorextMessages.Resources_modifiedResources, null); - result.add(status); - result.add(entry); - return result; - } - } - - private static IStatus addOutOfSync(IStatus status, IResource resource) { - IStatus entry= new Status( - IStatus.ERROR, - ResourcesPlugin.PI_RESOURCES, - IResourceStatus.OUT_OF_SYNC_LOCAL, - Messages.format(CorextMessages.Resources_outOfSync, resource.getFullPath().toString()), - null); - if (status == null) { - return entry; - } else if (status.isMultiStatus()) { - ((MultiStatus)status).add(entry); - return status; - } else { - MultiStatus result= new MultiStatus( - ResourcesPlugin.PI_RESOURCES, - IResourceStatus.OUT_OF_SYNC_LOCAL, - CorextMessages.Resources_outOfSyncResources, null); - result.add(status); - result.add(entry); - return result; - } - } - - /** - * This method is used to generate a list of local locations to - * be used in DnD for file transfers. - * - * @param resources the array of resources to get the local - * locations for - * @return the local locations - */ - public static String[] getLocationOSStrings(IResource[] resources) { - List result= new ArrayList(resources.length); - for (int i= 0; i < resources.length; i++) { - IPath location= resources[i].getLocation(); - if (location != null) - result.add(location.toOSString()); - } - return (String[]) result.toArray(new String[result.size()]); - } - - /** - * Returns the location of the given resource. For local - * resources this is the OS path in the local file system. For - * remote resource this is the URI. - * - * @param resource the resource - * @return the location string or <code>null</code> if the - * location URI of the resource is <code>null</code> - */ - public static String getLocationString(IResource resource) { - URI uri= resource.getLocationURI(); - if (uri == null) - return null; - return EFS.SCHEME_FILE.equalsIgnoreCase(uri.getScheme()) - ? new File(uri).getAbsolutePath() - : uri.toString(); - } - - public static boolean isReadOnly(IResource resource) { - ResourceAttributes resourceAttributes = resource.getResourceAttributes(); - if (resourceAttributes == null) // not supported on this platform for this resource - return false; - return resourceAttributes.isReadOnly(); - } - - static void setReadOnly(IResource resource, boolean readOnly) { - ResourceAttributes resourceAttributes = resource.getResourceAttributes(); - if (resourceAttributes == null) // not supported on this platform for this resource - return; - - resourceAttributes.setReadOnly(readOnly); - try { - resource.setResourceAttributes(resourceAttributes); - } catch (CoreException e) { - JavaScriptPlugin.log(e); - } - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java deleted file mode 100644 index 916d4cc9..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.eclipse.wst.jsdt.core.search.SearchEngine; -import org.eclipse.wst.jsdt.core.search.SearchMatch; -import org.eclipse.wst.jsdt.core.search.SearchParticipant; -import org.eclipse.wst.jsdt.core.search.SearchPattern; - -public class SearchUtils { - - /** - * @param match - * @return the enclosing {@link IJavaScriptElement}, or null iff none - */ - public static IJavaScriptElement getEnclosingJavaElement(SearchMatch match) { - Object element = match.getElement(); - if (element instanceof IJavaScriptElement) - return (IJavaScriptElement) element; - else - return null; - } - - /** - * @param match - * @return the enclosing {@link IJavaScriptUnit} of the given match, or null iff none - */ - public static IJavaScriptUnit getCompilationUnit(SearchMatch match) { - IJavaScriptElement enclosingElement = getEnclosingJavaElement(match); - if (enclosingElement != null){ - if (enclosingElement instanceof IJavaScriptUnit) - return (IJavaScriptUnit) enclosingElement; - IJavaScriptUnit cu= (IJavaScriptUnit) enclosingElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT); - if (cu != null) - return cu; - } - - IJavaScriptElement jElement= JavaScriptCore.create(match.getResource()); - if (jElement != null && jElement.exists() && jElement.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) - return (IJavaScriptUnit) jElement; - return null; - } - - public static SearchParticipant[] getDefaultSearchParticipants() { - return new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; - } - - /** - * Constant for use as matchRule in {@link SearchPattern#createPattern(IJavaScriptElement, int, int)} - * to get search behavior as of 3.1M3 (all generic instantiations are found). - */ - public final static int GENERICS_AGNOSTIC_MATCH_RULE= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_ERASURE_MATCH; - - /** - * Returns whether the given pattern is a camel case pattern or not. - * - * @param pattern the pattern to inspect - * @return whether it is a camel case pattern or not - */ - public static boolean isCamelCasePattern(String pattern) { - return SearchPattern.validateMatchRule( - pattern, - SearchPattern.R_CAMELCASE_MATCH) == SearchPattern.R_CAMELCASE_MATCH; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Strings.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Strings.java deleted file mode 100644 index 37833aae..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Strings.java +++ /dev/null @@ -1,433 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.action.LegacyActionTools; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultLineTracker; -import org.eclipse.jface.text.ILineTracker; -import org.eclipse.jface.text.IRegion; -import org.eclipse.wst.jsdt.core.IJavaScriptProject; -import org.eclipse.wst.jsdt.core.formatter.IndentManipulation; - - -/** - * Helper class to provide String manipulation functions not available in standard JDK. - */ -public class Strings { - - private Strings(){} - - /** - * tests if a char is lower case. Fix for 26529 - */ - public static boolean isLowerCase(char ch) { - return Character.toLowerCase(ch) == ch; - } - - public static boolean startsWithIgnoreCase(String text, String prefix) { - int textLength= text.length(); - int prefixLength= prefix.length(); - if (textLength < prefixLength) - return false; - for (int i= prefixLength - 1; i >= 0; i--) { - if (Character.toLowerCase(prefix.charAt(i)) != Character.toLowerCase(text.charAt(i))) - return false; - } - return true; - } - - public static String removeNewLine(String message) { - StringBuffer result= new StringBuffer(); - int current= 0; - int index= message.indexOf('\n', 0); - while (index != -1) { - result.append(message.substring(current, index)); - if (current < index && index != 0) - result.append(' '); - current= index + 1; - index= message.indexOf('\n', current); - } - result.append(message.substring(current)); - return result.toString(); - } - - /** - * Converts the given string into an array of lines. The lines - * don't contain any line delimiter characters. - * - * @return the string converted into an array of strings. Returns <code> - * null</code> if the input string can't be converted in an array of lines. - */ - public static String[] convertIntoLines(String input) { - try { - ILineTracker tracker= new DefaultLineTracker(); - tracker.set(input); - int size= tracker.getNumberOfLines(); - String result[]= new String[size]; - for (int i= 0; i < size; i++) { - IRegion region= tracker.getLineInformation(i); - int offset= region.getOffset(); - result[i]= input.substring(offset, offset + region.getLength()); - } - return result; - } catch (BadLocationException e) { - return null; - } - } - - /** - * Returns <code>true</code> if the given string only consists of - * white spaces according to Java. If the string is empty, <code>true - * </code> is returned. - * - * @return <code>true</code> if the string only consists of white - * spaces; otherwise <code>false</code> is returned - * - * @see java.lang.Character#isWhitespace(char) - */ - public static boolean containsOnlyWhitespaces(String s) { - int size= s.length(); - for (int i= 0; i < size; i++) { - if (!Character.isWhitespace(s.charAt(i))) - return false; - } - return true; - } - - /** - * Removes leading tabs and spaces from the given string. If the string - * doesn't contain any leading tabs or spaces then the string itself is - * returned. - */ - public static String trimLeadingTabsAndSpaces(String line) { - int size= line.length(); - int start= size; - for (int i= 0; i < size; i++) { - char c= line.charAt(i); - if (!IndentManipulation.isIndentChar(c)) { - start= i; - break; - } - } - if (start == 0) - return line; - else if (start == size) - return ""; //$NON-NLS-1$ - else - return line.substring(start); - } - - public static String trimTrailingTabsAndSpaces(String line) { - int size= line.length(); - int end= size; - for (int i= size - 1; i >= 0; i--) { - char c= line.charAt(i); - if (IndentManipulation.isIndentChar(c)) { - end= i; - } else { - break; - } - } - if (end == size) - return line; - else if (end == 0) - return ""; //$NON-NLS-1$ - else - return line.substring(0, end); - } - - /** - * Returns the indent of the given string in indentation units. Odd spaces - * are not counted. - * - * @param line the text line - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * - */ - public static int computeIndentUnits(String line, IJavaScriptProject project) { - return IndentManipulation.measureIndentUnits(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project)); - } - - /** - * Returns the indent of the given string in indentation units. Odd spaces - * are not counted. - * - * @param line the text line - * @param tabWidth the width of the '\t' character in space equivalents - * @param indentWidth the width of one indentation unit in space equivalents - * - */ - public static int computeIndentUnits(String line, int tabWidth, int indentWidth) { - return IndentManipulation.measureIndentUnits(line, tabWidth, indentWidth); - } - - /** - * Computes the visual length of the indentation of a - * <code>CharSequence</code>, counting a tab character as the size until - * the next tab stop and every other whitespace character as one. - * - * @param line the string to measure the indent of - * @param tabSize the visual size of a tab in space equivalents - * @return the visual length of the indentation of <code>line</code> - * - */ - public static int measureIndentLength(CharSequence line, int tabSize) { - return IndentManipulation.measureIndentInSpaces(line, tabSize); - } - - /** - * Removes the given number of indents from the line. Asserts that the given line - * has the requested number of indents. If <code>indentsToRemove <= 0</code> - * the line is returned. - * - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * - */ - public static String trimIndent(String line, int indentsToRemove, IJavaScriptProject project) { - return IndentManipulation.trimIndent(line, indentsToRemove, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project)); - } - - /** - * Removes the given number of indents from the line. Asserts that the given line - * has the requested number of indents. If <code>indentsToRemove <= 0</code> - * the line is returned. - * - * - */ - public static String trimIndent(String line, int indentsToRemove, int tabWidth, int indentWidth) { - return IndentManipulation.trimIndent(line, indentsToRemove, tabWidth, indentWidth); - } - - /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. - - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * - */ - public static void trimIndentation(String[] lines, IJavaScriptProject project) { - trimIndentation(lines, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), true); - } - /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. - * - * - */ - public static void trimIndentation(String[] lines, int tabWidth, int indentWidth) { - trimIndentation(lines, tabWidth, indentWidth, true); - } - - /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. If <code> - * considerFirstLine</code> is false the first line will be ignored. - * - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * - */ - public static void trimIndentation(String[] lines, IJavaScriptProject project, boolean considerFirstLine) { - trimIndentation(lines, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), considerFirstLine); - } - - /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. If <code> - * considerFirstLine</code> is false the first line will be ignored. - * - */ - public static void trimIndentation(String[] lines, int tabWidth, int indentWidth, boolean considerFirstLine) { - String[] toDo= new String[lines.length]; - // find indentation common to all lines - int minIndent= Integer.MAX_VALUE; // very large - for (int i= considerFirstLine ? 0 : 1; i < lines.length; i++) { - String line= lines[i]; - if (containsOnlyWhitespaces(line)) - continue; - toDo[i]= line; - int indent= computeIndentUnits(line, tabWidth, indentWidth); - if (indent < minIndent) { - minIndent= indent; - } - } - - if (minIndent > 0) { - // remove this indent from all lines - for (int i= considerFirstLine ? 0 : 1; i < toDo.length; i++) { - String s= toDo[i]; - if (s != null) - lines[i]= trimIndent(s, minIndent, tabWidth, indentWidth); - else { - String line= lines[i]; - int indent= computeIndentUnits(line, tabWidth, indentWidth); - if (indent > minIndent) - lines[i]= trimIndent(line, minIndent, tabWidth, indentWidth); - else - lines[i]= trimLeadingTabsAndSpaces(line); - } - } - } - } - - /** - * Returns that part of the indentation of <code>line</code> that makes up - * a multiple of indentation units. - * - * @param line the line to scan - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * @return the indent part of <code>line</code>, but no odd spaces - * - */ - public static String getIndentString(String line, IJavaScriptProject project) { - return IndentManipulation.extractIndentString(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project)); - } - - /** - * Returns that part of the indentation of <code>line</code> that makes up - * a multiple of indentation units. - * - * @param line the line to scan - * @param tabWidth the size of one tab in space equivalents - * @param indentWidth the size of the indent in space equivalents - * @return the indent part of <code>line</code>, but no odd spaces - * - */ - public static String getIndentString(String line, int tabWidth, int indentWidth) { - return IndentManipulation.extractIndentString(line, tabWidth, indentWidth); - } - - public static String[] removeTrailingEmptyLines(String[] sourceLines) { - int lastNonEmpty= findLastNonEmptyLineIndex(sourceLines); - String[] result= new String[lastNonEmpty + 1]; - for (int i= 0; i < result.length; i++) { - result[i]= sourceLines[i]; - } - return result; - } - - private static int findLastNonEmptyLineIndex(String[] sourceLines) { - for (int i= sourceLines.length - 1; i >= 0; i--) { - if (! sourceLines[i].trim().equals(""))//$NON-NLS-1$ - return i; - } - return -1; - } - - /** - * Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added. - * The first line of the code will not be changed. (It is considered to have no indent as it might start in - * the middle of a line) - * - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * - */ - public static String changeIndent(String code, int codeIndentLevel, IJavaScriptProject project, String newIndent, String lineDelim) { - return IndentManipulation.changeIndent(code, codeIndentLevel, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), newIndent, lineDelim); - } - - /** - * Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added. - * The first line of the code will not be changed. (It is considered to have no indent as it might start in - * the middle of a line) - * - */ - public static String changeIndent(String code, int codeIndentLevel, int tabWidth, int indentWidth, String newIndent, String lineDelim) { - return IndentManipulation.changeIndent(code, codeIndentLevel, tabWidth, indentWidth, newIndent, lineDelim); - } - - public static String trimIndentation(String source, IJavaScriptProject project, boolean considerFirstLine) { - return trimIndentation(source, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), considerFirstLine); - } - - public static String trimIndentation(String source, int tabWidth, int indentWidth, boolean considerFirstLine) { - try { - ILineTracker tracker= new DefaultLineTracker(); - tracker.set(source); - int size= tracker.getNumberOfLines(); - if (size == 1) - return source; - String lines[]= new String[size]; - for (int i= 0; i < size; i++) { - IRegion region= tracker.getLineInformation(i); - int offset= region.getOffset(); - lines[i]= source.substring(offset, offset + region.getLength()); - } - Strings.trimIndentation(lines, tabWidth, indentWidth, considerFirstLine); - StringBuffer result= new StringBuffer(); - int last= size - 1; - for (int i= 0; i < size; i++) { - result.append(lines[i]); - if (i < last) - result.append(tracker.getLineDelimiter(i)); - } - return result.toString(); - } catch (BadLocationException e) { - Assert.isTrue(false,"Can not happend"); //$NON-NLS-1$ - return null; - } - } - - - /** - * Concatenate the given strings into one strings using the passed line delimiter as a - * delimiter. No delimiter is added to the last line. - */ - public static String concatenate(String[] lines, String delimiter) { - StringBuffer buffer= new StringBuffer(); - for (int i= 0; i < lines.length; i++) { - if (i > 0) - buffer.append(delimiter); - buffer.append(lines[i]); - } - return buffer.toString(); - } - - public static boolean equals(String s, char[] c) { - if (s.length() != c.length) - return false; - - for (int i = c.length; --i >= 0;) - if (s.charAt(i) != c[i]) - return false; - return true; - } - - public static String removeTrailingCharacters(String text, char toRemove) { - int size= text.length(); - int end= size; - for (int i= size - 1; i >= 0; i--) { - char c= text.charAt(i); - if (c == toRemove) { - end= i; - } else { - break; - } - } - if (end == size) - return text; - else if (end == 0) - return ""; //$NON-NLS-1$ - else - return text.substring(0, end); - } - - public static String removeMnemonicIndicator(String string) { - return LegacyActionTools.removeMnemonics(string); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SuperTypeHierarchyCache.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SuperTypeHierarchyCache.java deleted file mode 100644 index 0d80b924..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SuperTypeHierarchyCache.java +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.ITypeHierarchy; -import org.eclipse.wst.jsdt.core.ITypeHierarchyChangedListener; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; - -public class SuperTypeHierarchyCache { - - private static class HierarchyCacheEntry implements ITypeHierarchyChangedListener { - - private ITypeHierarchy fTypeHierarchy; - private long fLastAccess; - - public HierarchyCacheEntry(ITypeHierarchy hierarchy) { - fTypeHierarchy= hierarchy; - fTypeHierarchy.addTypeHierarchyChangedListener(this); - markAsAccessed(); - } - - public void typeHierarchyChanged(ITypeHierarchy typeHierarchy) { - removeHierarchyEntryFromCache(this); - } - - public ITypeHierarchy getTypeHierarchy() { - return fTypeHierarchy; - } - - public void markAsAccessed() { - fLastAccess= System.currentTimeMillis(); - } - - public long getLastAccess() { - return fLastAccess; - } - - public void dispose() { - fTypeHierarchy.removeTypeHierarchyChangedListener(this); - fTypeHierarchy= null; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - public String toString() { - return "Super hierarchy of: " + fTypeHierarchy.getType().getElementName(); //$NON-NLS-1$ - } - - } - - - private static final int CACHE_SIZE= 8; - - private static ArrayList fgHierarchyCache= new ArrayList(CACHE_SIZE); - private static Map fgMethodOverrideTesterCache= new LRUMap(CACHE_SIZE); - - private static int fgCacheHits= 0; - private static int fgCacheMisses= 0; - - /** - * Get a hierarchy for the given type - */ - public static ITypeHierarchy getTypeHierarchy(IType type) throws JavaScriptModelException { - return getTypeHierarchy(type, null); - } - - public static MethodOverrideTester getMethodOverrideTester(IType type) throws JavaScriptModelException { - MethodOverrideTester test= null; - synchronized (fgMethodOverrideTesterCache) { - test= (MethodOverrideTester) fgMethodOverrideTesterCache.get(type); - } - if (test == null) { - ITypeHierarchy hierarchy= getTypeHierarchy(type); // don't nest the locks - synchronized (fgMethodOverrideTesterCache) { - test= (MethodOverrideTester) fgMethodOverrideTesterCache.get(type); // test again after waiting a long time for 'getTypeHierarchy' - if (test == null) { - test= new MethodOverrideTester(type, hierarchy); - fgMethodOverrideTesterCache.put(type, test); - } - } - } - return test; - } - - private static void removeMethodOverrideTester(ITypeHierarchy hierarchy) { - synchronized (fgMethodOverrideTesterCache) { - for (Iterator iter= fgMethodOverrideTesterCache.values().iterator(); iter.hasNext();) { - MethodOverrideTester curr= (MethodOverrideTester) iter.next(); - if (curr.getTypeHierarchy().equals(hierarchy)) { - iter.remove(); - } - } - } - } - - - /** - * Get a hierarchy for the given type - */ - public static ITypeHierarchy getTypeHierarchy(IType type, IProgressMonitor progressMonitor) throws JavaScriptModelException { - ITypeHierarchy hierarchy= findTypeHierarchyInCache(type); - if (hierarchy == null) { - fgCacheMisses++; - hierarchy= type.newSupertypeHierarchy(progressMonitor); - addTypeHierarchyToCache(hierarchy); - } else { - fgCacheHits++; - } - return hierarchy; - } - - private static void addTypeHierarchyToCache(ITypeHierarchy hierarchy) { - synchronized (fgHierarchyCache) { - int nEntries= fgHierarchyCache.size(); - if (nEntries >= CACHE_SIZE) { - // find obsolete entries or remove entry that was least recently accessed - HierarchyCacheEntry oldest= null; - ArrayList obsoleteHierarchies= new ArrayList(CACHE_SIZE); - for (int i= 0; i < nEntries; i++) { - HierarchyCacheEntry entry= (HierarchyCacheEntry) fgHierarchyCache.get(i); - ITypeHierarchy curr= entry.getTypeHierarchy(); - if (!curr.exists() || hierarchy.contains(curr.getType())) { - obsoleteHierarchies.add(entry); - } else { - if (oldest == null || entry.getLastAccess() < oldest.getLastAccess()) { - oldest= entry; - } - } - } - if (!obsoleteHierarchies.isEmpty()) { - for (int i= 0; i < obsoleteHierarchies.size(); i++) { - removeHierarchyEntryFromCache((HierarchyCacheEntry) obsoleteHierarchies.get(i)); - } - } else if (oldest != null) { - removeHierarchyEntryFromCache(oldest); - } - } - HierarchyCacheEntry newEntry= new HierarchyCacheEntry(hierarchy); - fgHierarchyCache.add(newEntry); - } - } - - - /** - * Check if the given type is in the hierarchy - * @param type - * @return Return <code>true</code> if a hierarchy for the given type is cached. - */ - public static boolean hasInCache(IType type) { - return findTypeHierarchyInCache(type) != null; - } - - - private static ITypeHierarchy findTypeHierarchyInCache(IType type) { - synchronized (fgHierarchyCache) { - for (int i= fgHierarchyCache.size() - 1; i>= 0; i--) { - HierarchyCacheEntry curr= (HierarchyCacheEntry) fgHierarchyCache.get(i); - ITypeHierarchy hierarchy= curr.getTypeHierarchy(); - if (!hierarchy.exists()) { - removeHierarchyEntryFromCache(curr); - } else { - if (hierarchy.contains(type)) { - curr.markAsAccessed(); - return hierarchy; - } - } - } - } - return null; - } - - private static void removeHierarchyEntryFromCache(HierarchyCacheEntry entry) { - synchronized (fgHierarchyCache) { - removeMethodOverrideTester(entry.getTypeHierarchy()); - entry.dispose(); - fgHierarchyCache.remove(entry); - } - } - - - /** - * Gets the number of times the hierarchy could be taken from the hierarchy. - * @return Returns a int - */ - public static int getCacheHits() { - return fgCacheHits; - } - - /** - * Gets the number of times the hierarchy was build. Used for testing. - * @return Returns a int - */ - public static int getCacheMisses() { - return fgCacheMisses; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeFilter.java deleted file mode 100644 index 789fac5b..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeFilter.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.util.StringTokenizer; - -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.search.TypeNameMatch; -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher; -import org.eclipse.wst.jsdt.ui.PreferenceConstants; - -/** - * - */ -public class TypeFilter implements IPropertyChangeListener { - - public static TypeFilter getDefault() { - return JavaScriptPlugin.getDefault().getTypeFilter(); - } - - public static boolean isFiltered(String fullTypeName) { - return getDefault().filter(fullTypeName); - } - - public static boolean isFiltered(char[] fullTypeName) { - return getDefault().filter(new String(fullTypeName)); - } - - public static boolean isFiltered(char[] packageName, char[] typeName) { - return getDefault().filter(JavaModelUtil.concatenateName(packageName, typeName)); - } - - public static boolean isFiltered(IType type) { - TypeFilter typeFilter = getDefault(); - if (typeFilter.hasFilters()) { - return typeFilter.filter(JavaModelUtil.getFullyQualifiedName(type)); - } - return false; - } - - public static boolean isFiltered(TypeNameMatch match) { - return getDefault().filter(match.getFullyQualifiedName()); - } - - private StringMatcher[] fStringMatchers; - - /** - * - */ - public TypeFilter() { - fStringMatchers= null; - PreferenceConstants.getPreferenceStore().addPropertyChangeListener(this); - } - - private synchronized StringMatcher[] getStringMatchers() { - if (fStringMatchers == null) { - String str= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.TYPEFILTER_ENABLED); - StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$ - int nTokens= tok.countTokens(); - - fStringMatchers= new StringMatcher[nTokens]; - for (int i= 0; i < nTokens; i++) { - String curr= tok.nextToken(); - if (curr.length() > 0) { - fStringMatchers[i]= new StringMatcher(curr, false, false); - } - } - } - return fStringMatchers; - } - - public void dispose() { - PreferenceConstants.getPreferenceStore().removePropertyChangeListener(this); - fStringMatchers= null; - } - - - public boolean hasFilters() { - return getStringMatchers().length > 0; - } - - public boolean filter(String fullTypeName) { - StringMatcher[] matchers= getStringMatchers(); - for (int i= 0; i < matchers.length; i++) { - StringMatcher curr= matchers[i]; - if (curr.match(fullTypeName)) { - return true; - } - } - return false; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) - */ - public synchronized void propertyChange(PropertyChangeEvent event) { - if (PreferenceConstants.TYPEFILTER_ENABLED.equals(event.getProperty())) { - fStringMatchers= null; - } - } - - -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoFilter.java deleted file mode 100644 index 84c6d45c..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoFilter.java +++ /dev/null @@ -1,259 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants; -import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; -import org.eclipse.wst.jsdt.core.search.SearchEngine; -import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.core.search.TypeNameMatch; -import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher; -import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoFilterExtension; - -public class TypeInfoFilter { - - private static class PatternMatcher { - - private String fPattern; - private int fMatchKind; - private StringMatcher fStringMatcher; - - private static final char END_SYMBOL= '<'; - private static final char ANY_STRING= '*'; - private static final char BLANK= ' '; - - public PatternMatcher(String pattern, boolean ignoreCase) { - this(pattern, SearchPattern.R_EXACT_MATCH | SearchPattern.R_PREFIX_MATCH | - SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CAMELCASE_MATCH); - } - - public PatternMatcher(String pattern, int allowedModes) { - initializePatternAndMatchKind(pattern); - fMatchKind= fMatchKind & allowedModes; - if (fMatchKind == SearchPattern.R_PATTERN_MATCH) { - fStringMatcher= new StringMatcher(fPattern, true, false); - } - } - - public String getPattern() { - return fPattern; - } - - public int getMatchKind() { - return fMatchKind; - } - - public boolean matches(String text) { - switch (fMatchKind) { - case SearchPattern.R_PATTERN_MATCH: - return fStringMatcher.match(text); - case SearchPattern.R_EXACT_MATCH: - return fPattern.equalsIgnoreCase(text); - case SearchPattern.R_CAMELCASE_MATCH: - if (SearchPattern.camelCaseMatch(fPattern, text)) { - return true; - } - // fall through to prefix match if camel case failed (bug 137244) - //$FALL-THROUGH$ - default: - return Strings.startsWithIgnoreCase(text, fPattern); - } - } - - private void initializePatternAndMatchKind(String pattern) { - int length= pattern.length(); - if (length == 0) { - fMatchKind= SearchPattern.R_EXACT_MATCH; - fPattern= pattern; - return; - } - char last= pattern.charAt(length - 1); - - if (pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1) { - fMatchKind= SearchPattern.R_PATTERN_MATCH; - switch (last) { - case END_SYMBOL: - fPattern= pattern.substring(0, length - 1); - break; - case BLANK: - fPattern= pattern.trim(); - break; - case ANY_STRING: - fPattern= pattern; - break; - default: - fPattern= pattern + ANY_STRING; - } - return; - } - - if (last == END_SYMBOL) { - fMatchKind= SearchPattern.R_EXACT_MATCH; - fPattern= pattern.substring(0, length - 1); - return; - } - - if (last == BLANK) { - fMatchKind= SearchPattern.R_EXACT_MATCH; - fPattern= pattern.trim(); - return; - } - - if (SearchUtils.isCamelCasePattern(pattern)) { - fMatchKind= SearchPattern.R_CAMELCASE_MATCH; - fPattern= pattern; - return; - } - - fMatchKind= SearchPattern.R_PREFIX_MATCH; - fPattern= pattern; - } - } - - private String fText; - private IJavaScriptSearchScope fSearchScope; - private boolean fIsWorkspaceScope; - private int fElementKind; - private ITypeInfoFilterExtension fFilterExtension; - private TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter(); - - private PatternMatcher fPackageMatcher; - private PatternMatcher fNameMatcher; - - public TypeInfoFilter(String text, IJavaScriptSearchScope scope, int elementKind, ITypeInfoFilterExtension extension) { - fText= text; - fSearchScope= scope; - fIsWorkspaceScope= fSearchScope.equals(SearchEngine.createWorkspaceScope()); - fElementKind= elementKind; - fFilterExtension= extension; - - int index= text.lastIndexOf("."); //$NON-NLS-1$ - if (index == -1) { - fNameMatcher= new PatternMatcher(text, true); - } else { - fPackageMatcher= new PatternMatcher(evaluatePackagePattern(text.substring(0, index)), true); - String name= text.substring(index + 1); - if (name.length() == 0) - name= "*"; //$NON-NLS-1$ - fNameMatcher= new PatternMatcher(name, true); - } - } - - /* - * Transforms o.e.j to o*.e*.j* - */ - private String evaluatePackagePattern(String s) { - StringBuffer buf= new StringBuffer(); - boolean hasWildCard= false; - for (int i= 0; i < s.length(); i++) { - char ch= s.charAt(i); - if (ch == '.') { - if (!hasWildCard) { - buf.append('*'); - } - hasWildCard= false; - } else if (ch == '*' || ch =='?') { - hasWildCard= true; - } - buf.append(ch); - } - if (!hasWildCard) { - buf.append('*'); - } - return buf.toString(); - } - - public String getText() { - return fText; - } - - public boolean isSubFilter(String text) { - if (! fText.startsWith(text)) - return false; - - return fText.indexOf('.', text.length()) == -1; - } - - public boolean isCamelCasePattern() { - return fNameMatcher.getMatchKind() == SearchPattern.R_CAMELCASE_MATCH; - } - - public String getPackagePattern() { - if (fPackageMatcher == null) - return null; - return fPackageMatcher.getPattern(); - } - - public String getNamePattern() { - return fNameMatcher.getPattern(); - } - - public int getSearchFlags() { - return fNameMatcher.getMatchKind(); - } - - public int getPackageFlags() { - if (fPackageMatcher == null) - return SearchPattern.R_EXACT_MATCH; - - return fPackageMatcher.getMatchKind(); - } - - public boolean matchesRawNamePattern(TypeNameMatch type) { - return Strings.startsWithIgnoreCase(type.getSimpleTypeName(), fNameMatcher.getPattern()); - } - - public boolean matchesCachedResult(TypeNameMatch type) { - if (!(matchesPackage(type) && matchesFilterExtension(type))) - return false; - return matchesName(type); - } - - public boolean matchesHistoryElement(TypeNameMatch type) { - if (!(matchesPackage(type) && matchesModifiers(type) && matchesScope(type) && matchesFilterExtension(type))) - return false; - return matchesName(type); - } - - public boolean matchesFilterExtension(TypeNameMatch type) { - if (fFilterExtension == null) - return true; - fAdapter.setMatch(type); - return fFilterExtension.select(fAdapter); - } - - private boolean matchesName(TypeNameMatch type) { - return fNameMatcher.matches(type.getSimpleTypeName()); - } - - private boolean matchesPackage(TypeNameMatch type) { - if (fPackageMatcher == null) - return true; - return fPackageMatcher.matches(type.getTypeContainerName()); - } - - private boolean matchesScope(TypeNameMatch type) { - if (fIsWorkspaceScope) - return true; - return fSearchScope.encloses(type.getType()); - } - - private boolean matchesModifiers(TypeNameMatch type) { - if (fElementKind == IJavaScriptSearchConstants.TYPE) - return true; - int modifiers= type.getModifiers(); - switch (fElementKind) { - case IJavaScriptSearchConstants.CLASS: - return modifiers == 0; - } - return false; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoRequestorAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoRequestorAdapter.java deleted file mode 100644 index b3421317..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoRequestorAdapter.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import org.eclipse.wst.jsdt.core.Signature; -import org.eclipse.wst.jsdt.core.search.TypeNameMatch; -import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor; - - -public class TypeInfoRequestorAdapter implements ITypeInfoRequestor { - - private TypeNameMatch fMatch; - - public void setMatch(TypeNameMatch type) { - fMatch= type; - } - - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor#getEnclosingName() - */ - public String getEnclosingName() { - return Signature.getQualifier(fMatch.getTypeQualifiedName()); - } - - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor#getModifiers() - */ - public int getModifiers() { - return fMatch.getModifiers(); - } - - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor#getPackageName() - */ - public String getPackageName() { - return fMatch.getPackageName(); - } - - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor#getTypeName() - */ - public String getTypeName() { - return fMatch.getSimpleTypeName(); - } - - -} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeNameMatchCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeNameMatchCollector.java deleted file mode 100644 index 63f7bd71..00000000 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeNameMatchCollector.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.corext.util; - -import java.util.Collection; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.wst.jsdt.core.search.TypeNameMatch; -import org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor; - -public class TypeNameMatchCollector extends TypeNameMatchRequestor { - - private final Collection fCollection; - - public TypeNameMatchCollector(Collection collection) { - Assert.isNotNull(collection); - fCollection= collection; - } - - private boolean inScope(TypeNameMatch match) { - return !TypeFilter.isFiltered(match); - } - - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor#acceptTypeNameMatch(org.eclipse.wst.jsdt.core.search.TypeNameMatch) - */ - public void acceptTypeNameMatch(TypeNameMatch match) { - if (inScope(match)) { - fCollection.add(match); - } - } - -} |