issue_id
int64 2.03k
426k
| title
stringlengths 9
251
| body
stringlengths 1
32.8k
⌀ | status
stringclasses 6
values | after_fix_sha
stringlengths 7
7
| project_name
stringclasses 6
values | repo_url
stringclasses 6
values | repo_name
stringclasses 6
values | language
stringclasses 1
value | issue_url
null | before_fix_sha
null | pull_url
null | commit_datetime
timestamp[us, tz=UTC] | report_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36,625 |
Bug 36625 "Copy Trace" Action in "Failure Trace" View enabled for empty table.
|
The "Copy Trace" action should probably be hidden or unavailable when there is nothing in the "Failure Trace" view. Currently the user is given the option to copy a trace of nothing to the clipboard.
|
resolved fixed
|
afc9c2b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T14:34:39Z | 2003-04-17T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CopyFailureListAction.java
| |
36,625 |
Bug 36625 "Copy Trace" Action in "Failure Trace" View enabled for empty table.
|
The "Copy Trace" action should probably be hidden or unavailable when there is nothing in the "Failure Trace" view. Currently the user is given the option to copy a trace of nothing to the clipboard.
|
resolved fixed
|
afc9c2b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T14:34:39Z | 2003-04-17T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureRunView.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* A view presenting the failed tests in a table.
*/
class FailureRunView implements ITestRunView, IMenuListener {
private Table fTable;
private TestRunnerViewPart fRunnerViewPart;
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fFailureTabIcon= TestRunnerViewPart.createImage("obj16/failures.gif"); //$NON-NLS-1$
public FailureRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fRunnerViewPart= runner;
CTabItem failureTab= new CTabItem(tabFolder, SWT.NONE);
failureTab.setText(getName());
failureTab.setImage(fFailureTabIcon);
Composite composite= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
composite.setLayout(gridLayout);
GridData gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
composite.setLayoutData(gridData);
fTable= new Table(composite, SWT.NONE);
gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
fTable.setLayout(gridLayout);
gridData= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTable.setLayoutData(gridData);
failureTab.setControl(composite);
failureTab.setToolTipText(JUnitMessages.getString("FailureRunView.tab.tooltip")); //$NON-NLS-1$
initMenu();
addListeners();
}
private void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fFailureTabIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTable);
fTable.setMenu(menu);
}
public String getName() {
return JUnitMessages.getString("FailureRunView.tab.title"); //$NON-NLS-1$
}
public String getSelectedTestId() {
int index= fTable.getSelectionIndex();
if (index == -1)
return null;
return getTestInfo(fTable.getItem(index)).getTestId();
}
private String getClassName() {
return cutFromTo(getSelectedText(), '(', ')');
}
private String getMethodName() {
return cutTo(getSelectedText(), '(');
}
private static String cutFromTo(String string, char from, char to){
String modified= string;
modified= modified.substring(modified.indexOf(from) + 1);
return cutTo(modified, to);
}
private static String cutTo(String string, char to){
int toIndex= string.indexOf(to);
if (toIndex == -1)
return string;
else
return string.substring(0, toIndex);
}
public void menuAboutToShow(IMenuManager manager){
if (fTable.getSelectionCount() > 0) {
String className= getClassName();
String methodName= getMethodName();
if (className != null) {
manager.add(new OpenTestAction(fRunnerViewPart, className, methodName));
manager.add(new RerunAction(fRunnerViewPart, getSelectedTestId(), className, methodName));
}
}
}
private String getSelectedText() {
int index= fTable.getSelectionIndex();
if (index == -1)
return null;
return fTable.getItem(index).getText();
}
public void setSelectedTest(String testId){
TableItem[] items= fTable.getItems();
for (int i= 0; i < items.length; i++) {
TableItem tableItem= items[i];
TestRunInfo info= getTestInfo(tableItem);
if (info.getTestId().equals(testId)){
fTable.setSelection(new TableItem[] { tableItem });
fTable.showItem(tableItem);
return;
}
}
}
private TestRunInfo getTestInfo(TableItem item) {
return (TestRunInfo)item.getData();
}
public void setFocus() {
fTable.setFocus();
}
public void endTest(String testId){
TestRunInfo testInfo= fRunnerViewPart.getTestInfo(testId);
if(testInfo == null || testInfo.getStatus() == ITestRunListener.STATUS_OK)
return;
TableItem tableItem= new TableItem(fTable, SWT.NONE);
updateTableItem(testInfo, tableItem);
fTable.showItem(tableItem);
}
private void updateTableItem(TestRunInfo testInfo, TableItem tableItem) {
tableItem.setText(testInfo.getTestName());
if (testInfo.getStatus() == ITestRunListener.STATUS_FAILURE)
tableItem.setImage(fFailureIcon);
else
tableItem.setImage(fErrorIcon);
tableItem.setData(testInfo);
}
private TableItem findItem(String testId) {
TableItem[] items= fTable.getItems();
for (int i= 0; i < items.length; i++) {
TestRunInfo info= getTestInfo(items[i]);
if (info.getTestId().equals(testId))
return items[i];
}
return null;
}
public void activate() {
testSelected();
}
public void aboutToStart() {
fTable.removeAll();
}
private void testSelected() {
fRunnerViewPart.handleTestSelected(getSelectedTestId());
}
private void addListeners() {
fTable.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTable.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTable.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e){
handleDoubleClick(e);
}
public void mouseDown(MouseEvent e) {
activate();
}
public void mouseUp(MouseEvent e) {
activate();
}
});
}
void handleDoubleClick(MouseEvent e) {
if (fTable.getSelectionCount() > 0)
new OpenTestAction(fRunnerViewPart, getClassName(), getMethodName()).run();
}
public void newTreeEntry(String treeEntry) {
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo)
*/
public void testStatusChanged(TestRunInfo info) {
TableItem item= findItem(info.getTestId());
if (item != null) {
if (info.getStatus() == ITestRunListener.STATUS_OK) {
item.dispose();
return;
}
updateTableItem(info, item);
}
if (item == null && info.getStatus() != ITestRunListener.STATUS_OK) {
item= new TableItem(fTable, SWT.NONE);
updateTableItem(info, item);
}
if (item != null)
fTable.showItem(item);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.junit.ui.ITestRunView#startTest(java.lang.String)
*/
public void startTest(String testId) {
}
}
|
36,625 |
Bug 36625 "Copy Trace" Action in "Failure Trace" View enabled for empty table.
|
The "Copy Trace" action should probably be hidden or unavailable when there is nothing in the "Failure Trace" view. Currently the user is given the option to copy a trace of nothing to the clipboard.
|
resolved fixed
|
afc9c2b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T14:34:39Z | 2003-04-17T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureTraceView.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.Assert;
/**
* A view that shows a stack trace of a failed test.
*/
class FailureTraceView implements IMenuListener {
private static final String FRAME_PREFIX= "at "; //$NON-NLS-1$
private Table fTable;
private TestRunnerViewPart fTestRunner;
private String fInputTrace;
private final Clipboard fClipboard;
private final Image fStackIcon= TestRunnerViewPart.createImage("obj16/stkfrm_obj.gif"); //$NON-NLS-1$
private final Image fExceptionIcon= TestRunnerViewPart.createImage("obj16/exc_catch.gif"); //$NON-NLS-1$
public FailureTraceView(Composite parent, TestRunnerViewPart testRunner, Clipboard clipboard) {
Assert.isNotNull(clipboard);
fTable= new Table(parent, SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL);
fTestRunner= testRunner;
fClipboard= clipboard;
fTable.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e){
handleDoubleClick(e);
}
});
initMenu();
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
}
void handleDoubleClick(MouseEvent e) {
if(fTable.getSelection().length != 0) {
Action a= createOpenEditorAction(getSelectedText());
if (a != null)
a.run();
}
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTable);
fTable.setMenu(menu);
}
public void menuAboutToShow(IMenuManager manager) {
if (fTable.getSelectionCount() > 0) {
Action a= createOpenEditorAction(getSelectedText());
if (a != null)
manager.add(a);
}
manager.add(new CopyTraceAction(FailureTraceView.this, fClipboard));
}
public String getTrace() {
return fInputTrace;
}
private String getSelectedText() {
return fTable.getSelection()[0].getText();
}
private Action createOpenEditorAction(String traceLine) {
try {
//TODO: works for JDK stack trace only
String testName= traceLine;
testName= testName.substring(testName.indexOf(FRAME_PREFIX)); //$NON-NLS-1$
testName= testName.substring(FRAME_PREFIX.length(), testName.indexOf('(')).trim();
testName= testName.substring(0, testName.lastIndexOf('.'));
int innerSeparatorIndex= testName.indexOf('$');
if (innerSeparatorIndex != -1)
testName= testName.substring(0, innerSeparatorIndex);
String lineNumber= traceLine;
lineNumber= lineNumber.substring(lineNumber.indexOf(':') + 1, lineNumber.indexOf(")")); //$NON-NLS-1$
int line= Integer.valueOf(lineNumber).intValue();
return new OpenEditorAtLineAction(fTestRunner, testName, line);
} catch(NumberFormatException e) {
}
catch(IndexOutOfBoundsException e) {
}
return null;
}
private void disposeIcons(){
if (fExceptionIcon != null && !fExceptionIcon.isDisposed())
fExceptionIcon.dispose();
if (fStackIcon != null && !fStackIcon.isDisposed())
fStackIcon.dispose();
}
/**
* Returns the composite used to present the trace
*/
Composite getComposite(){
return fTable;
}
/**
* Refresh the table from the the trace.
*/
public void refresh() {
updateTable(fInputTrace);
}
/**
* Shows a TestFailure
*/
public void showFailure(String trace) {
if (fInputTrace == trace)
return;
fInputTrace= trace;
updateTable(trace);
}
private void updateTable(String trace) {
if(trace == null || trace.trim().equals("")) { //$NON-NLS-1$
clear();
return;
}
trace= trace.trim();
fTable.setRedraw(false);
fTable.removeAll();
fillTable(filterStack(trace));
fTable.setRedraw(true);
}
private void fillTable(String trace) {
StringReader stringReader= new StringReader(trace);
BufferedReader bufferedReader= new BufferedReader(stringReader);
String line;
try {
// first line contains the thrown exception
line= bufferedReader.readLine();
if (line == null)
return;
TableItem tableItem= new TableItem(fTable, SWT.NONE);
String itemLabel= line.replace('\t', ' ');
tableItem.setText(itemLabel);
tableItem.setImage(fExceptionIcon);
// the stack frames of the trace
while ((line= bufferedReader.readLine()) != null) {
itemLabel= line.replace('\t', ' ');
tableItem= new TableItem(fTable, SWT.NONE);
// heuristic for detecting a stack frame - works for JDK
if ((itemLabel.indexOf(" at ") >= 0)) { //$NON-NLS-1$
tableItem.setImage(fStackIcon);
}
tableItem.setText(itemLabel);
}
} catch (IOException e) {
TableItem tableItem= new TableItem(fTable, SWT.NONE);
tableItem.setText(trace);
}
}
/**
* Shows other information than a stack trace.
*/
public void setInformation(String text) {
clear();
TableItem tableItem= new TableItem(fTable, SWT.NONE);
tableItem.setText(text);
}
/**
* Clears the non-stack trace info
*/
public void clear() {
fTable.removeAll();
fInputTrace= null;
}
private String filterStack(String stackTrace) {
if (!JUnitPreferencePage.getFilterStack() || stackTrace == null)
return stackTrace;
StringWriter stringWriter= new StringWriter();
PrintWriter printWriter= new PrintWriter(stringWriter);
StringReader stringReader= new StringReader(stackTrace);
BufferedReader bufferedReader= new BufferedReader(stringReader);
String line;
String[] patterns= JUnitPreferencePage.getFilterPatterns();
try {
while ((line= bufferedReader.readLine()) != null) {
if (!filterLine(patterns, line))
printWriter.println(line);
}
} catch (IOException e) {
return stackTrace; // return the stack unfiltered
}
return stringWriter.toString();
}
private boolean filterLine(String[] patterns, String line) {
String pattern;
int len;
for (int i= (patterns.length - 1); i >= 0; --i) {
pattern= patterns[i];
len= pattern.length() - 1;
if (pattern.charAt(len) == '*') {
//strip trailing * from a package filter
pattern= pattern.substring(0, len);
} else if (Character.isUpperCase(pattern.charAt(0))) {
//class in the default package
pattern= FRAME_PREFIX + pattern + '.';
} else {
//class names start w/ an uppercase letter after the .
final int lastDotIndex= pattern.lastIndexOf('.');
if ((lastDotIndex != -1) && (lastDotIndex != len) && Character.isUpperCase(pattern.charAt(lastDotIndex + 1)))
pattern += '.'; //append . to a class filter
}
if (line.indexOf(pattern) > 0)
return true;
}
return false;
}
}
|
36,625 |
Bug 36625 "Copy Trace" Action in "Failure Trace" View enabled for empty table.
|
The "Copy Trace" action should probably be hidden or unavailable when there is nothing in the "Failure Trace" view. Currently the user is given the option to copy a trace of nothing to the clipboard.
|
resolved fixed
|
afc9c2b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T14:34:39Z | 2003-04-17T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/HierarchyRunView.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/*
* A view that shows the contents of a test suite
* as a tree.
*/
class HierarchyRunView implements ITestRunView, IMenuListener {
/**
* The tree widget
*/
private Tree fTree;
/**
* Helper used to resurrect test hierarchy
*/
private static class SuiteInfo {
public int fTestCount;
public TreeItem fTreeItem;
public SuiteInfo(TreeItem treeItem, int testCount){
fTreeItem= treeItem;
fTestCount= testCount;
}
}
/**
* Vector of SuiteInfo items
*/
private Vector fSuiteInfos= new Vector();
/**
* Maps test Ids to TreeItems.
*/
private Map fTreeItemMap= new HashMap();
private TestRunnerViewPart fTestRunnerPart;
private final Image fOkIcon= TestRunnerViewPart.createImage("obj16/testok.gif"); //$NON-NLS-1$
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fHierarchyIcon= TestRunnerViewPart.createImage("obj16/testhier.gif"); //$NON-NLS-1$
private final Image fSuiteIcon= TestRunnerViewPart.createImage("obj16/tsuite.gif"); //$NON-NLS-1$
private final Image fSuiteErrorIcon= TestRunnerViewPart.createImage("obj16/tsuiteerror.gif"); //$NON-NLS-1$
private final Image fSuiteFailIcon= TestRunnerViewPart.createImage("obj16/tsuitefail.gif"); //$NON-NLS-1$
private final Image fTestIcon= TestRunnerViewPart.createImage("obj16/test.gif"); //$NON-NLS-1$
private final Image fTestRunningIcon= TestRunnerViewPart.createImage("obj16/testrun.gif"); //$NON-NLS-1$
public HierarchyRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fTestRunnerPart= runner;
CTabItem hierarchyTab= new CTabItem(tabFolder, SWT.NONE);
hierarchyTab.setText(getName());
hierarchyTab.setImage(fHierarchyIcon);
Composite testTreePanel= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
testTreePanel.setLayout(gridLayout);
GridData gridData= new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
testTreePanel.setLayoutData(gridData);
hierarchyTab.setControl(testTreePanel);
hierarchyTab.setToolTipText(JUnitMessages.getString("HierarchyRunView.tab.tooltip")); //$NON-NLS-1$
fTree= new Tree(testTreePanel, SWT.V_SCROLL);
gridData= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTree.setLayoutData(gridData);
initMenu();
addListeners();
}
private void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fOkIcon.dispose();
fHierarchyIcon.dispose();
fTestIcon.dispose();
fTestRunningIcon.dispose();
fSuiteIcon.dispose();
fSuiteErrorIcon.dispose();
fSuiteFailIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTree);
fTree.setMenu(menu);
}
private String getTestLabel() {
TreeItem treeItem= fTree.getSelection()[0];
if(treeItem == null)
return ""; //$NON-NLS-1$
return treeItem.getText();
}
private TestRunInfo getTestInfo() {
TreeItem[] treeItems= fTree.getSelection();
if(treeItems.length == 0)
return null;
return ((TestRunInfo)treeItems[0].getData());
}
private boolean isSuiteSelected() {
TreeItem[] treeItems= fTree.getSelection();
if(treeItems.length != 1)
return false;
return treeItems[0].getItems().length > 0;
}
private String getClassName() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return extractClassName(testInfo.getTestName());
}
public String getSelectedTestId() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return testInfo.getTestId();
}
private String extractClassName(String testNameString) {
if (testNameString == null)
return null;
int index= testNameString.indexOf('(');
if (index < 0)
return testNameString;
testNameString= testNameString.substring(index + 1);
return testNameString.substring(0, testNameString.indexOf(')'));
}
public String getName() {
return JUnitMessages.getString("HierarchyRunView.tab.title"); //$NON-NLS-1$
}
public void setSelectedTest(String testId) {
TreeItem treeItem= findTreeItem(testId);
if (treeItem != null)
fTree.setSelection(new TreeItem[]{treeItem});
}
public void startTest(String testId) {
TreeItem treeItem= findTreeItem(testId);
if (treeItem == null)
return;
setCurrentItem(treeItem);
}
private void setCurrentItem(TreeItem treeItem) {
treeItem.setImage(fTestRunningIcon);
}
public void endTest(String testId) {
TreeItem treeItem= findTreeItem(testId);
if (treeItem == null)
return;
TestRunInfo testInfo= fTestRunnerPart.getTestInfo(testId);
updateItem(treeItem, testInfo);
//if (testInfo.getTrace() != null)
fTree.showItem(treeItem);
}
private void updateItem(TreeItem treeItem, TestRunInfo testInfo) {
treeItem.setData(testInfo);
if(testInfo.getStatus() == ITestRunListener.STATUS_OK) {
treeItem.setImage(fOkIcon);
return;
}
if (testInfo.getStatus() == ITestRunListener.STATUS_FAILURE)
treeItem.setImage(fFailureIcon);
else if (testInfo.getStatus() == ITestRunListener.STATUS_ERROR)
treeItem.setImage(fErrorIcon);
propagateStatus(treeItem, testInfo.getStatus());
}
private void propagateStatus(TreeItem item, int status) {
TreeItem parent= item.getParentItem();
if (parent == null)
return;
Image parentImage= parent.getImage();
if (status == ITestRunListener.STATUS_FAILURE) {
if (parentImage == fSuiteErrorIcon || parentImage == fSuiteFailIcon)
return;
parent.setImage(fSuiteFailIcon);
} else {
if (parentImage == fSuiteErrorIcon)
return;
parent.setImage(fSuiteErrorIcon);
}
propagateStatus(parent, status);
}
public void activate() {
testSelected();
}
public void setFocus() {
fTree.setFocus();
}
public void aboutToStart() {
fTree.removeAll();
fSuiteInfos.removeAllElements();
fTreeItemMap= new HashMap();
}
private void testSelected() {
fTestRunnerPart.handleTestSelected(getSelectedTestId());
}
private void addListeners() {
fTree.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTree.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTree.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e) {
handleDoubleClick(e);
}
});
}
void handleDoubleClick(MouseEvent e) {
TestRunInfo testInfo= getTestInfo();
String testLabel= testInfo.getTestName();
OpenTestAction action= null;
if (isSuiteSelected())
action= new OpenTestAction(fTestRunnerPart, testLabel);
else
action= new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel());
if (action != null && action.isEnabled())
action.run();
}
public void menuAboutToShow(IMenuManager manager) {
if (fTree.getSelectionCount() > 0) {
TreeItem treeItem= fTree.getSelection()[0];
TestRunInfo testInfo= (TestRunInfo) treeItem.getData();
String testLabel= testInfo.getTestName();
if (isSuiteSelected()) {
manager.add(new OpenTestAction(fTestRunnerPart, testLabel));
} else {
manager.add(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel()));
manager.add(new RerunAction(fTestRunnerPart, getSelectedTestId(), getClassName(), getTestLabel()));
}
}
}
public void newTreeEntry(String treeEntry) {
// format: testId","testName","isSuite","testcount
int index0= treeEntry.indexOf(',');
int index1= treeEntry.indexOf(',', index0+1);
int index2= treeEntry.indexOf(',', index1+1);
String label= treeEntry.substring(index0+1, index1).trim();
String id= treeEntry.substring(0, index0);
TestRunInfo testInfo= new TestRunInfo(id, label);
//fTestInfo.addElement(testInfo);
int index3;
if((index3= label.indexOf('(')) > 0)
label= label.substring(0, index3);
if((index3= label.indexOf('@')) > 0)
label= label.substring(0, index3);
String isSuite= treeEntry.substring(index1+1, index2);
int testCount= Integer.parseInt(treeEntry.substring(index2+1));
TreeItem treeItem;
while((fSuiteInfos.size() > 0) && (((SuiteInfo) fSuiteInfos.lastElement()).fTestCount == 0)) {
fSuiteInfos.removeElementAt(fSuiteInfos.size()-1);
}
if(fSuiteInfos.size() == 0){
treeItem= new TreeItem(fTree, SWT.NONE);
treeItem.setImage(fSuiteIcon);
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else if(isSuite.equals("true")) { //$NON-NLS-1$
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fHierarchyIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else {
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fTestIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
mapTest(testInfo, treeItem);
}
treeItem.setText(label);
treeItem.setData(testInfo);
}
private void mapTest(TestRunInfo info, TreeItem item) {
fTreeItemMap.put(info.getTestId(), item);
}
private TreeItem findTreeItem(String testId) {
Object o= fTreeItemMap.get(testId);
if (o instanceof TreeItem)
return (TreeItem)o;
return null;
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo, int)
*/
public void testStatusChanged(TestRunInfo newInfo) {
Object o= fTreeItemMap.get(newInfo.getTestId());
if (o instanceof TreeItem) {
updateItem((TreeItem)o, newInfo);
return;
}
}
}
|
36,625 |
Bug 36625 "Copy Trace" Action in "Failure Trace" View enabled for empty table.
|
The "Copy Trace" action should probably be hidden or unavailable when there is nothing in the "Failure Trace" view. Currently the user is given the option to copy a trace of nothing to the clipboard.
|
resolved fixed
|
afc9c2b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T14:34:39Z | 2003-04-17T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/IJUnitHelpContextIds.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
/**
* Help context ids for the JUnit UI.
*/
public interface IJUnitHelpContextIds {
public static final String PREFIX= JUnitPlugin.PLUGIN_ID + '.';
// Actions
public static final String COPYTRACE_ACTION= PREFIX + "copy_trace_action_context"; //$NON-NLS-1$
public static final String ENABLEFILTER_ACTION= PREFIX + "enable_filter_action_context"; //$NON-NLS-1$
public static final String OPENEDITORATLINE_ACTION= PREFIX + "open_editor_atline_action_context"; //$NON-NLS-1$
public static final String OPENTEST_ACTION= PREFIX + "open_test_action_context"; //$NON-NLS-1$
public static final String RERUN_ACTION= PREFIX + "rerun_test_action_context"; //$NON-NLS-1$
public static final String GOTO_REFERENCED_TEST_ACTION_CONTEXT= PREFIX + "goto_referenced_test_action_context"; //$NON-NLS-1$
// view parts
public static final String RESULTS_VIEW= PREFIX + "results_view_context"; //$NON-NLS-1$
// Preference/Property pages
public static final String JUNIT_PREFERENCE_PAGE= PREFIX + "junit_preference_page_context"; //$NON-NLS-1$
// Wizard pages
public static final String NEW_TESTCASE_WIZARD_PAGE= PREFIX + "new_testcase_wizard_page_context"; //$NON-NLS-1$
public static final String NEW_TESTCASE_WIZARD_PAGE2= PREFIX + "new_testcase_wizard_page2_context"; //$NON-NLS-1$
public static final String NEW_TESTSUITE_WIZARD_PAGE= PREFIX + "new_testsuite_wizard_page2_context"; //$NON-NLS-1$
// Dialogs
public static final String TEST_SELECTION_DIALOG= PREFIX + "test_selection_context"; //$NON-NLS-1$
}
|
36,625 |
Bug 36625 "Copy Trace" Action in "Failure Trace" View enabled for empty table.
|
The "Copy Trace" action should probably be hidden or unavailable when there is nothing in the "Failure Trace" view. Currently the user is given the option to copy a trace of nothing to the clipboard.
|
resolved fixed
|
afc9c2b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T14:34:39Z | 2003-04-17T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Julien Ruaux: [email protected] see bug 25324 Ability to know when tests are finished [junit]
* Vincent Massol: [email protected] 25324 Ability to know when tests are finished [junit]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener2, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrors;
/**
* Number of failures during this test run
*/
protected int fFailures;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos= new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private TestRunInfo fFirstFailure;
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
private Clipboard fClipboard;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch= null;
/**
* Actions
*/
private Action fRerunLastTestAction;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
Image fOriginalViewImage= null;
IElementChangedListener fDirtyListener= null;
private class StopAction extends Action{
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action{
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit unit= (ICompilationUnit)delta.getElement();
// If we change a working copy we do nothing
if (unit.isWorkingCopy()) {
// Don't examine children of a working copy but keep processing siblings.
return true;
} else {
codeHasChanged();
return false;
}
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void reset(){
reset(0);
setViewPartTitle(null);
clearStatus();
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrors), String.valueOf(fFailures)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFirstFailure != null) {
fActiveRunView.setSelectedTest(fFirstFailure.getTestId());
handleTestSelected(fFirstFailure.getTestId());
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrors+fFailures > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testId, String testName) {
postStartTest(testId, testName);
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
postInfo(JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", testName)); //$NON-NLS-1$
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null)
fTestInfos.put(testId, new TestRunInfo(testId, testName));
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testId, String testName){
postEndTest(testId, testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace){
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testName, testInfo);
}
testInfo.setTrace(trace);
testInfo.setStatus(status);
if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
else
fFailures++;
if (fFirstFailure == null)
fFirstFailure= testInfo;
// show the view on the first error only
if (fShowOnErrorOnly && (fErrors + fFailures == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String testId, String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
TestRunInfo info= getTestInfo(testId);
updateTest(info, status);
if (info.getTrace() == null || !info.getTrace().equals(trace)) {
info.setTrace(trace);
showFailure(info.getTrace());
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.getStatus())
return;
if (info.getStatus() == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailures++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
} else if (info.getStatus() == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrors--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrors--;
fFailures++;
}
} else if (info.getStatus() == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailures--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailures--;
fErrors++;
}
}
info.setStatus(status);
final TestRunInfo finalInfo= info;
postAsyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
Vector listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.copyInto(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
if (fClipboard != null)
fClipboard.dispose();
getSite().getKeyBindingService().unregisterAction(fRerunLastTestAction);
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void postAsyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
}
}
});
}
private void postEndTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testId);
}
}
});
}
private void postStartTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.startTest(testId);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailures+fErrors);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrors, fFailures);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrors);
fCounterPanel.setFailureValue(fFailures);
fCounterPanel.setRunValue(fExecutedTests);
fProgressBar.refresh(fErrors+fFailures> 0);
}
protected void postShowTestResultsView() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getSelectedTestId());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
SashForm sashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(sashForm, SWT.NONE);
CTabFolder tabFolder= createTestRunViews(top);
tabFolder.setLayoutData(new TabFolderLayout());
top.setContent(tabFolder);
ViewForm bottom= new ViewForm(sashForm, SWT.NONE);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, this, fClipboard);
bottom.setContent(fFailureView.getComposite());
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
// fill the failure trace viewer toolbar
ToolBarManager failureToolBarmanager= new ToolBarManager(failureToolBar);
failureToolBarmanager.add(new EnableStackFilterAction(fFailureView));
failureToolBarmanager.update(true);
sashForm.setWeights(new int[]{50, 50});
return sashForm;
}
private void reset(final int testCount) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailures= 0;
fErrors= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFirstFailure= null;
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
fClipboard= new Clipboard(parent.getDisplay());
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
parent.setLayout(gridLayout);
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fRerunLastTestAction= new RerunLastAction();
fRerunLastTestAction.setActionDefinitionId("org.eclipse.jdt.junit.reruntest"); //$NON-NLS-1$
toolBar.add(new StopAction());
toolBar.add(fRerunLastTestAction);
actionBars.updateActionBars();
Composite counterPanel= createProgressCountPanel(parent);
counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
actionBars.setGlobalActionHandler(
IWorkbenchActionConstants.COPY,
new CopyTraceAction(fFailureView, fClipboard));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
getSite().getKeyBindingService().registerAction(fRerunLastTestAction);
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testId) {
if (testId == null)
return null;
return (TestRunInfo) fTestInfos.get(testId);
}
public void handleTestSelected(String testId) {
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
showFailure(""); //$NON-NLS-1$
} else {
showFailure(testInfo.getTrace());
}
}
private void showFailure(final String failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
public void rerunTest(String testId, String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(testId, className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
}
|
36,625 |
Bug 36625 "Copy Trace" Action in "Failure Trace" View enabled for empty table.
|
The "Copy Trace" action should probably be hidden or unavailable when there is nothing in the "Failure Trace" view. Currently the user is given the option to copy a trace of nothing to the clipboard.
|
resolved fixed
|
afc9c2b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T14:34:39Z | 2003-04-17T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/NewTestCaseCreationWizardPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.wizards;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.wizards.NewTypeWizardPage;
import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
import org.eclipse.jdt.internal.junit.util.JUnitStatus;
import org.eclipse.jdt.internal.junit.util.JUnitStubUtility;
import org.eclipse.jdt.internal.junit.util.LayoutUtil;
import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
/**
* The first page of the TestCase creation wizard.
*/
public class NewTestCaseCreationWizardPage extends NewTypeWizardPage {
protected final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$
protected final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$
protected final static String TEST_CLASS= PAGE_NAME + ".testclass"; //$NON-NLS-1$
protected final static String TEST_SUFFIX= "Test"; //$NON-NLS-1$
protected final static String SETUP= "setUp"; //$NON-NLS-1$
protected final static String TEARDOWN= "tearDown"; //$NON-NLS-1$
protected final static String STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$
protected final static String STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$
protected final static String STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; //$NON-NLS-1$
private String fDefaultClassToTest;
private NewTestCaseCreationWizardPage2 fPage2;
private MethodStubsSelectionButtonGroup fMethodStubsButtons;
private IType fClassToTest;
protected IStatus fClassToTestStatus;
protected IStatus fTestClassStatus;
private int fIndexOfFirstTestMethod;
private Label fClassToTestLabel;
private Text fClassToTestText;
private Button fClassToTestButton;
private Label fTestClassLabel;
private Text fTestClassText;
private String fTestClassTextInitialValue;
private boolean fFirstTime;
public NewTestCaseCreationWizardPage() {
super(true, PAGE_NAME);
fFirstTime= true;
fTestClassTextInitialValue= ""; //$NON-NLS-1$
setTitle(WizardMessages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$
setDescription(WizardMessages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$
String[] buttonNames= new String[] {
"public static void main(Strin&g[] args)", //$NON-NLS-1$
/* Add testrunner statement to main Method */
WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$
WizardMessages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$
WizardMessages.getString("NewTestClassWizPage.methodStub.tearDown") //$NON-NLS-1$
};
fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1);
fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$
fClassToTestStatus= new JUnitStatus();
fTestClassStatus= new JUnitStatus();
fDefaultClassToTest= ""; //$NON-NLS-1$
}
// -------- Initialization ---------
/**
* Should be called from the wizard with the initial selection and the 2nd page of the wizard..
*/
public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) {
fPage2= page2;
IJavaElement element= getInitialJavaElement(selection);
initContainerPage(element);
initTypePage(element);
doStatusUpdate();
// put default class to test
if (element != null) {
IType classToTest= null;
// evaluate the enclosing type
IType typeInCompUnit= (IType) element.getAncestor(IJavaElement.TYPE);
if (typeInCompUnit != null) {
if (typeInCompUnit.getCompilationUnit() != null) {
classToTest= typeInCompUnit;
}
} else {
ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null)
classToTest= cu.findPrimaryType();
else {
if (element instanceof IClassFile) {
try {
IClassFile cf= (IClassFile) element;
if (cf.isStructureKnown())
classToTest= cf.getType();
} catch(JavaModelException e) {
JUnitPlugin.log(e);
}
}
}
}
if (classToTest != null) {
try {
if (!TestSearchEngine.isTestImplementor(classToTest)) {
fDefaultClassToTest= classToTest.getFullyQualifiedName();
}
} catch (JavaModelException e) {
JUnitPlugin.log(e);
}
}
}
fMethodStubsButtons.setSelection(0, false); //main
fMethodStubsButtons.setSelection(1, false); //add textrunner
fMethodStubsButtons.setEnabled(1, false); //add text
fMethodStubsButtons.setSelection(2, false); //setUp
fMethodStubsButtons.setSelection(3, false); //tearDown
}
/**
* @see NewContainerWizardPage#handleFieldChanged
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName.equals(CLASS_TO_TEST)) {
fClassToTestStatus= classToTestClassChanged();
} else if (fieldName.equals(SUPER)) {
validateSuperClass();
if (!fFirstTime)
fTestClassStatus= testClassChanged();
} else if (fieldName.equals(TEST_CLASS)) {
fTestClassStatus= testClassChanged();
} else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER) || fieldName.equals(SUPER)) {
if (fieldName.equals(PACKAGE))
fPackageStatus= packageChanged();
if (!fFirstTime) {
validateSuperClass();
fClassToTestStatus= classToTestClassChanged();
fTestClassStatus= testClassChanged();
}
if (fieldName.equals(CONTAINER)) {
validateJUnitOnBuildPath();
}
}
doStatusUpdate();
}
// ------ validation --------
private void doStatusUpdate() {
// status of all used components
IStatus[] status= new IStatus[] {
fContainerStatus,
fPackageStatus,
fTestClassStatus,
fClassToTestStatus,
fModifierStatus,
fSuperClassStatus
};
// the mode severe status will be displayed and the ok button enabled/disabled.
updateStatus(status);
}
/*
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NONE);
int nColumns= 4;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
composite.setLayout(layout);
createContainerControls(composite, nColumns);
createPackageControls(composite, nColumns);
createSeparator(composite, nColumns);
createClassToTestControls(composite, nColumns);
createSeparator(composite, nColumns);
createTestClassControls(composite, nColumns);
createSuperClassControls(composite, nColumns);
createMethodStubSelectionControls(composite, nColumns);
setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true);
setControl(composite);
//set default and focus
if (fDefaultClassToTest.length() > 0) {
fClassToTestText.setText(fDefaultClassToTest);
fTestClassText.setText(fDefaultClassToTest+TEST_SUFFIX);
}
restoreWidgetValues();
Dialog.applyDialogFont(composite);
WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE);
}
protected void createMethodStubSelectionControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns);
LayoutUtil.createEmptySpace(composite,1);
LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1);
}
protected void createClassToTestControls(Composite composite, int nColumns) {
fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP);
fClassToTestLabel.setFont(composite.getFont());
fClassToTestLabel.setText(WizardMessages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 1;
fClassToTestLabel.setLayoutData(gd);
fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER);
fClassToTestText.setEnabled(true);
fClassToTestText.setFont(composite.getFont());
fClassToTestText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
handleFieldChanged(CLASS_TO_TEST);
}
});
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.horizontalSpan= nColumns - 2;
fClassToTestText.setLayoutData(gd);
fClassToTestButton= new Button(composite, SWT.PUSH);
fClassToTestButton.setText(WizardMessages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$
fClassToTestButton.setEnabled(true);
fClassToTestButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
classToTestButtonPressed();
}
public void widgetSelected(SelectionEvent e) {
classToTestButtonPressed();
}
});
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.horizontalSpan= 1;
gd.heightHint = SWTUtil.getButtonHeigthHint(fClassToTestButton);
gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton);
fClassToTestButton.setLayoutData(gd);
}
private void classToTestButtonPressed() {
IType type= chooseClassToTestType();
if (type != null) {
fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type));
handleFieldChanged(CLASS_TO_TEST);
}
}
private IType chooseClassToTestType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null)
return null;
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
IType type= null;
try {
SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, getClassToTestText());
dialog.setTitle(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$
dialog.setMessage(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$
dialog.open();
if (dialog.getReturnCode() != SelectionDialog.OK)
return type;
else {
Object[] resultArray= dialog.getResult();
if (resultArray != null && resultArray.length > 0)
type= (IType) resultArray[0];
}
} catch (JavaModelException e) {
JUnitPlugin.log(e);
}
return type;
}
protected IStatus classToTestClassChanged() {
fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); // sets the test class field?
IStatus status= validateClassToTest();
return status;
}
/**
* Returns the content of the class to test text field.
*/
public String getClassToTestText() {
return fClassToTestText.getText();
}
/**
* Returns the class to be tested.
*/
public IType getClassToTest() {
return fClassToTest;
}
/**
* Sets the name of the class to test.
*/
public void setClassToTest(String name) {
fClassToTestText.setText(name);
}
/**
* @see NewTypeWizardPage#createTypeMembers
*/
protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
fIndexOfFirstTestMethod= 0;
if (fPage2.getCreateConstructorButtonSelection())
createConstructor(type, imports);
if (fMethodStubsButtons.isSelected(0))
createMain(type);
if (fMethodStubsButtons.isSelected(2)) {
createSetUp(type, imports);
}
if (fMethodStubsButtons.isSelected(3)) {
createTearDown(type, imports);
}
if (isNextPageValid()) {
createTestMethodStubs(type);
}
}
protected void createConstructor(IType type, ImportsManager imports) throws JavaModelException {
ITypeHierarchy typeHierarchy= null;
IType[] superTypes= null;
String constr= ""; //$NON-NLS-1$
IMethod methodTemplate= null;
if (type.exists()) {
typeHierarchy= type.newSupertypeHierarchy(null);
superTypes= typeHierarchy.getAllSuperclasses(type);
for (int i= 0; i < superTypes.length; i++) {
if (superTypes[i].exists()) {
IMethod constrMethod= superTypes[i].getMethod(superTypes[i].getElementName(), new String[] {"Ljava.lang.String;"}); //$NON-NLS-1$
if (constrMethod.exists() && constrMethod.isConstructor()) {
methodTemplate= constrMethod;
break;
}
}
}
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (methodTemplate != null) {
GenStubSettings genStubSettings= new GenStubSettings(settings);
genStubSettings.fCallSuper= true;
genStubSettings.fMethodOverwrites= true;
constr= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports);
} else {
constr += "public "+getTypeName()+"(String name) {" + //$NON-NLS-1$ //$NON-NLS-2$
getLineDelimiter() +
"super(name);" + //$NON-NLS-1$
getLineDelimiter() +
"}" + //$NON-NLS-1$
getLineDelimiter() + getLineDelimiter();
}
type.createMethod(constr, null, true, null);
fIndexOfFirstTestMethod++;
}
protected void createMain(IType type) throws JavaModelException {
type.createMethod(fMethodStubsButtons.getMainMethod(getTypeName()), null, false, null);
fIndexOfFirstTestMethod++;
}
protected void createSetUp(IType type, ImportsManager imports) throws JavaModelException {
ITypeHierarchy typeHierarchy= null;
IType[] superTypes= null;
String setUp= ""; //$NON-NLS-1$
IMethod methodTemplate= null;
if (type.exists()) {
typeHierarchy= type.newSupertypeHierarchy(null);
superTypes= typeHierarchy.getAllSuperclasses(type);
for (int i= 0; i < superTypes.length; i++) {
if (superTypes[i].exists()) {
IMethod testMethod= superTypes[i].getMethod(SETUP, new String[] {});
if (testMethod.exists()) {
methodTemplate= testMethod;
break;
}
}
}
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (methodTemplate != null) {
GenStubSettings genStubSettings= new GenStubSettings(settings);
genStubSettings.fCallSuper= true;
genStubSettings.fMethodOverwrites= true;
setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports);
} else {
if (settings.createComments)
setUp= "/**" + //$NON-NLS-1$
getLineDelimiter() +
" * Sets up the fixture, for example, open a network connection." + //$NON-NLS-1$
getLineDelimiter() +
" * This method is called before a test is executed." + //$NON-NLS-1$
getLineDelimiter() +
" * @throws Exception" + //$NON-NLS-1$
getLineDelimiter() +
" */" + //$NON-NLS-1$
getLineDelimiter();
setUp+= "protected void "+SETUP+"() throws Exception {}" + //$NON-NLS-1$ //$NON-NLS-2$
getLineDelimiter() + getLineDelimiter();
}
type.createMethod(setUp, null, false, null);
fIndexOfFirstTestMethod++;
}
protected void createTearDown(IType type, ImportsManager imports) throws JavaModelException {
ITypeHierarchy typeHierarchy= null;
IType[] superTypes= null;
String tearDown= ""; //$NON-NLS-1$
IMethod methodTemplate= null;
if (type.exists()) {
if (typeHierarchy == null) {
typeHierarchy= type.newSupertypeHierarchy(null);
superTypes= typeHierarchy.getAllSuperclasses(type);
}
for (int i= 0; i < superTypes.length; i++) {
if (superTypes[i].exists()) {
IMethod testM= superTypes[i].getMethod(TEARDOWN, new String[] {});
if (testM.exists()) {
methodTemplate= testM;
break;
}
}
}
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (methodTemplate != null) {
GenStubSettings genStubSettings= new GenStubSettings(settings);
genStubSettings.fCallSuper= true;
genStubSettings.fMethodOverwrites= true;
tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports);
type.createMethod(tearDown, null, false, null);
fIndexOfFirstTestMethod++;
}
}
protected void createTestMethodStubs(IType type) throws JavaModelException {
IMethod[] methods= fPage2.getCheckedMethods();
if (methods.length == 0)
return;
/* find overloaded methods */
IMethod[] allMethodsArray= fPage2.getAllMethods();
List allMethods= new ArrayList();
allMethods.addAll(Arrays.asList(allMethodsArray));
List overloadedMethods= getOveloadedMethods(allMethods);
/* used when for example both sum and Sum methods are present. Then
* sum -> testSum
* Sum -> testSum1
*/
List newMethodsNames= new ArrayList();
for (int i = 0; i < methods.length; i++) {
IMethod testedMethod= methods[i];
String elementName= testedMethod.getElementName();
StringBuffer methodName= new StringBuffer(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1));
StringBuffer newMethod= new StringBuffer();
if (overloadedMethods.contains(testedMethod)) {
appendMethodComment(newMethod, testedMethod);
String[] params= testedMethod.getParameterTypes();
appendParameterNamesToMethodName(methodName, params);
}
/* Should I for examples have methods
* void foo(java.lang.StringBuffer sb) {}
* void foo(mypackage1.StringBuffer sb) {}
* void foo(mypackage2.StringBuffer sb) {}
* I will get in the test class:
* testFooStringBuffer()
* testFooStringBuffer1()
* testFooStringBuffer2()
*/
if (newMethodsNames.contains(methodName.toString())) {
int suffix= 1;
while (newMethodsNames.contains(methodName.toString() + Integer.toString(suffix)))
suffix++;
methodName.append(Integer.toString(suffix));
}
newMethodsNames.add(methodName.toString());
if (fPage2.getCreateFinalMethodStubsButtonSelection())
newMethod.append("final "); //$NON-NLS-1$
newMethod.append("public void ");//$NON-NLS-1$
newMethod.append(methodName.toString());
newMethod.append("()");//$NON-NLS-1$
appendTestMethodBody(newMethod, testedMethod);
type.createMethod(newMethod.toString(), null, false, null);
}
}
private String getLineDelimiter(){
IType classToTest= getClassToTest();
if (classToTest != null && classToTest.exists())
return JUnitStubUtility.getLineDelimiterUsed(classToTest);
else
return JUnitStubUtility.getLineDelimiterUsed(getPackageFragment());
}
private void appendTestMethodBody(StringBuffer newMethod, IMethod testedMethod) {
newMethod.append("{"); //$NON-NLS-1$
if (createTasks()){
newMethod.append(getLineDelimiter());
newMethod.append("//"); //$NON-NLS-1$
newMethod.append(JUnitStubUtility.getTodoTaskTag(getPackageFragment().getJavaProject()));
newMethod.append(WizardMessages.getFormattedString("NewTestClassWizPage.marker.message", testedMethod.getElementName())); //$NON-NLS-1$
newMethod.append(getLineDelimiter());
}
newMethod.append("}").append(getLineDelimiter()).append(getLineDelimiter()); //$NON-NLS-1$
}
public void appendParameterNamesToMethodName(StringBuffer methodName, String[] params) {
for (int i= 0; i < params.length; i++) {
String param= params[i];
methodName.append(Signature.getSimpleName(Signature.toString(Signature.getElementType(param))));
for (int j= 0, arrayCount= Signature.getArrayCount(param); j < arrayCount; j++) {
methodName.append("Array"); //$NON-NLS-1$
}
}
}
private void appendMethodComment(StringBuffer newMethod, IMethod method) throws JavaModelException {
String returnType= Signature.toString(method.getReturnType());
String body= WizardMessages.getFormattedString("NewTestClassWizPage.comment.class_to_test", new String[]{returnType, method.getElementName()}); //$NON-NLS-1$
newMethod.append("/*");//$NON-NLS-1$
newMethod.append(getLineDelimiter());
newMethod.append(" * ");//$NON-NLS-1$
newMethod.append(body);
newMethod.append("(");//$NON-NLS-1$
String[] paramTypes= method.getParameterTypes();
if (paramTypes.length > 0) {
if (paramTypes.length > 1) {
for (int j= 0; j < paramTypes.length-1; j++) {
newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$
}
}
newMethod.append(Signature.toString(paramTypes[paramTypes.length-1]));
}
newMethod.append(")");//$NON-NLS-1$
newMethod.append(getLineDelimiter());
newMethod.append(" */");//$NON-NLS-1$
newMethod.append(getLineDelimiter());
}
private List getOveloadedMethods(List allMethods) {
List overloadedMethods= new ArrayList();
for (int i= 0; i < allMethods.size(); i++) {
IMethod current= (IMethod) allMethods.get(i);
String currentName= current.getElementName();
boolean currentAdded= false;
for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) {
IMethod iterMethod= (IMethod) iter.next();
if (iterMethod.getElementName().equals(currentName)) {
//method is overloaded
if (!currentAdded) {
overloadedMethods.add(current);
currentAdded= true;
}
overloadedMethods.add(iterMethod);
iter.remove();
}
}
}
return overloadedMethods;
}
/**
* @see DialogPage#setVisible(boolean)
*/
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible && fFirstTime) {
handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists
if (getClassToTestText().equals("")) //$NON-NLS-1$
setPageComplete(false);
fFirstTime= false;
}
if (visible) setFocus();
}
private void validateJUnitOnBuildPath() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null)
return;
IJavaProject jp= root.getJavaProject();
try {
if (jp.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) != null)
return;
} catch (JavaModelException e) {
}
JUnitStatus status= new JUnitStatus();
status.setError(WizardMessages.getString("NewTestClassWizPage.error.junitNotOnbuildpath")); //$NON-NLS-1$
fContainerStatus= status;
}
/**
* Returns the index of the first method that is a test method, i.e. excluding main, setUp() and tearDown().
* If none of the aforementioned method stubs is created, then 0 is returned. As such method stubs are created,
* this counter is incremented.
*/
public int getIndexOfFirstMethod() {
return fIndexOfFirstTestMethod;
}
private boolean createTasks() {
return fPage2.getCreateTasksButtonSelection();
}
private void validateSuperClass() {
fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox
fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox
String superClassName= getSuperClass();
if (superClassName == null || superClassName.trim().equals("")) { //$NON-NLS-1$
fSuperClassStatus= new JUnitStatus();
((JUnitStatus)fSuperClassStatus).setError("Super class name is empty"); //$NON-NLS-1$
return;
}
if (getPackageFragmentRoot() != null) { //$NON-NLS-1$
try {
IType type= resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName);
JUnitStatus status = new JUnitStatus();
if (type == null) {
status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$
fSuperClassStatus= status;
} else {
if (type.isInterface()) {
status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$
fSuperClassStatus= status;
}
if (!TestSearchEngine.isTestImplementor(type)) {
status.setError(WizardMessages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$
fSuperClassStatus= status;
} else {
IMethod setupMethod= type.getMethod(SETUP, new String[] {});
IMethod teardownMethod= type.getMethod(TEARDOWN, new String[] {});
if (setupMethod.exists())
fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags()));
if (teardownMethod.exists())
fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags()));
}
}
} catch (JavaModelException e) {
JUnitPlugin.log(e);
}
}
}
protected void createTestClassControls(Composite composite, int nColumns) {
fTestClassLabel= new Label(composite, SWT.LEFT | SWT.WRAP);
fTestClassLabel.setFont(composite.getFont());
fTestClassLabel.setText(WizardMessages.getString("NewTestClassWizPage.testcase.label")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 1;
fTestClassLabel.setLayoutData(gd);
fTestClassText= new Text(composite, SWT.SINGLE | SWT.BORDER);
fTestClassText.setEnabled(true);
fTestClassText.setFont(composite.getFont());
fTestClassText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
handleFieldChanged(TEST_CLASS);
}
});
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.horizontalSpan= nColumns - 2;
fTestClassText.setLayoutData(gd);
Label space= new Label(composite, SWT.LEFT);
space.setText(" "); //$NON-NLS-1$
gd= new GridData();
gd.horizontalSpan= 1;
space.setLayoutData(gd);
}
/**
* Gets the type name.
*/
public String getTypeName() {
return (fTestClassText==null)?fTestClassTextInitialValue:fTestClassText.getText();
}
/**
* Called when the type name has changed.
* The method validates the type name and returns the status of the validation.
* Can be extended to add more validation
*/
protected IStatus testClassChanged() {
JUnitStatus status= new JUnitStatus();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_empty")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_qualified")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_not_valid")+val.getMessage()); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(WizardMessages.getString("NewTestClassWizPage.error.testcase.name_discouraged")+val.getMessage()); //$NON-NLS-1$
// continue checking
}
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
if (cu.exists()) {
status.setError(WizardMessages.getFormattedString("NewTestClassWizPage.error.testcase.already_exists", typeName));//$NON-NLS-1$
return status;
}
}
return status;
}
/**
* @see IWizardPage#canFlipToNextPage
*/
public boolean canFlipToNextPage() {
return isPageComplete() && getNextPage() != null && isNextPageValid();
}
protected boolean isNextPageValid() {
return !getClassToTestText().equals(""); //$NON-NLS-1$
}
protected JUnitStatus validateClassToTest() {
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
String classToTestName= getClassToTestText();
JUnitStatus status= new JUnitStatus();
fClassToTest= null;
if (classToTestName.length() == 0) {
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(classToTestName);
// if (!val.isOK()) {
if (val.getSeverity() == IStatus.ERROR) {
status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= NewTestCaseCreationWizardPage.resolveClassNameToType(root.getJavaProject(), pack, classToTestName);
//IType type= wizpage.resolveClassToTestName();
if (type == null) {
//status.setWarning("Warning: "+typeLabel+" does not exist in current project.");
status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$
}
if (pack != null && !JavaModelUtil.isVisible(type, pack)) {
status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.not_visible", new String[] {(type.isInterface())?WizardMessages.getString("Interface"):WizardMessages.getString("Class") , classToTestName})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
fClassToTest= type;
} catch (JavaModelException e) {
status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
static public IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException {
IType type= null;
if (type == null && pack != null) {
String packName= pack.getElementName();
// search in own package
if (!pack.isDefaultPackage()) {
type= jproject.findType(packName, classToTestName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= jproject.findType("java.lang", classToTestName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= jproject.findType(classToTestName);
}
return type;
}
/**
* Sets the focus on the type name.
*/
protected void setFocus() {
fTestClassText.setFocus();
fTestClassText.setSelection(fTestClassText.getText().length(), fTestClassText.getText().length());
}
/**
* Use the dialog store to restore widget values to the values that they held
* last time this wizard was used to completion
*/
private void restoreWidgetValues() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN);
fMethodStubsButtons.setSelection(0, generateMain);
fMethodStubsButtons.setEnabled(1, generateMain);
fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER));
try {
fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE));
} catch(NumberFormatException e) {}
}
}
/**
* Since Finish was pressed, write widget values to the dialog store so that they
* will persist into the next invocation of this wizard page
*/
void saveWidgetValues() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0));
settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1));
settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection());
}
}
}
|
36,625 |
Bug 36625 "Copy Trace" Action in "Failure Trace" View enabled for empty table.
|
The "Copy Trace" action should probably be hidden or unavailable when there is nothing in the "Failure Trace" view. Currently the user is given the option to copy a trace of nothing to the clipboard.
|
resolved fixed
|
afc9c2b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T14:34:39Z | 2003-04-17T11:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/NewTestCaseCreationWizardPage2.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.wizards;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.dialogs.ContainerCheckedTreeViewer;
/**
* Wizard page to select the methods from a class under test.
*/
public class NewTestCaseCreationWizardPage2 extends WizardPage {
private final static String PAGE_NAME= "NewTestCaseCreationWizardPage2"; //$NON-NLS-1$
private final static String STORE_USE_TASKMARKER= PAGE_NAME + ".USE_TASKMARKER"; //$NON-NLS-1$
private final static String STORE_CREATE_FINAL_METHOD_STUBS= PAGE_NAME + ".CREATE_FINAL_METHOD_STUBS"; //$NON-NLS-1$
private final static String STORE_CREATE_CONSTRUCTOR= PAGE_NAME + ".CREATE_CONSTRUCTOR"; //$NON-NLS-1$
public final static String PREFIX= "test"; //$NON-NLS-1$
private NewTestCaseCreationWizardPage fFirstPage;
private IType fClassToTest;
private Button fCreateFinalMethodStubsButton;
private Button fCreateTasksButton;
private Button fCreateConstructorButton;
private ContainerCheckedTreeViewer fMethodsTree;
private Button fSelectAllButton;
private Button fDeselectAllButton;
private Label fSelectedMethodsLabel;
/**
* Constructor for NewTestCaseCreationWizardPage2.
*/
protected NewTestCaseCreationWizardPage2(NewTestCaseCreationWizardPage firstPage) {
super(PAGE_NAME);
fFirstPage= firstPage;
setTitle(WizardMessages.getString("NewTestClassWizPage2.title")); //$NON-NLS-1$
setDescription(WizardMessages.getString("NewTestClassWizPage2.description")); //$NON-NLS-1$
}
/**
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
Composite container= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
container.setLayout(layout);
createMethodsTreeControls(container);
createSpacer(container);
createFinalMethodStubsControls(container);
createTasksControls(container);
createConstructorControls(container);
setControl(container);
restoreWidgetValues();
Dialog.applyDialogFont(container);
WorkbenchHelp.setHelp(container, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE2);
}
protected void createFinalMethodStubsControls(Composite container) {
GridLayout layout;
GridData gd;
Composite prefixContainer= new Composite(container, SWT.NONE);
gd= new GridData();
gd.horizontalAlignment = GridData.FILL;
gd.horizontalSpan = 2;
prefixContainer.setLayoutData(gd);
layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = 0;
layout.marginHeight = 0;
prefixContainer.setLayout(layout);
fCreateFinalMethodStubsButton= new Button(prefixContainer, SWT.CHECK | SWT.LEFT);
fCreateFinalMethodStubsButton.setText(WizardMessages.getString("NewTestClassWizPage2.create_final_method_stubs.text")); //$NON-NLS-1$
fCreateFinalMethodStubsButton.setEnabled(true);
fCreateFinalMethodStubsButton.setSelection(true);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalSpan= 2;
fCreateFinalMethodStubsButton.setLayoutData(gd);
}
protected void createTasksControls(Composite container) {
GridLayout layout;
GridData gd;
Composite prefixContainer= new Composite(container, SWT.NONE);
gd= new GridData();
gd.horizontalAlignment = GridData.FILL;
gd.horizontalSpan = 2;
prefixContainer.setLayoutData(gd);
layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = 0;
layout.marginHeight = 0;
prefixContainer.setLayout(layout);
fCreateTasksButton= new Button(prefixContainer, SWT.CHECK | SWT.LEFT);
fCreateTasksButton.setText(WizardMessages.getString("NewTestClassWizPage2.create_tasks.text")); //$NON-NLS-1$
fCreateTasksButton.setEnabled(true);
fCreateTasksButton.setSelection(true);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalSpan= 2;
fCreateTasksButton.setLayoutData(gd);
}
protected void createConstructorControls(Composite container) {
GridLayout layout;
GridData gd;
Composite prefixContainer= new Composite(container, SWT.NONE);
gd= new GridData();
gd.horizontalAlignment = GridData.FILL;
gd.horizontalSpan = 2;
prefixContainer.setLayoutData(gd);
layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = 0;
layout.marginHeight = 0;
prefixContainer.setLayout(layout);
fCreateConstructorButton= new Button(prefixContainer, SWT.CHECK | SWT.LEFT);
fCreateConstructorButton.setText(WizardMessages.getString("NewTestClassWizPage2.create_constructor.text")); //$NON-NLS-1$
fCreateConstructorButton.setEnabled(true);
fCreateConstructorButton.setSelection(false);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalSpan= 2;
fCreateConstructorButton.setLayoutData(gd);
}
protected void createMethodsTreeControls(Composite container) {
Label label= new Label(container, SWT.LEFT | SWT.WRAP);
label.setFont(container.getFont());
label.setText(WizardMessages.getString("NewTestClassWizPage2.methods_tree.label")); //$NON-NLS-1$
GridData gd = new GridData();
gd.horizontalSpan = 2;
label.setLayoutData(gd);
fMethodsTree= new ContainerCheckedTreeViewer(container, SWT.BORDER);
gd= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
gd.heightHint= 180;
fMethodsTree.getTree().setLayoutData(gd);
fMethodsTree.setLabelProvider(new AppearanceAwareLabelProvider());
fMethodsTree.setAutoExpandLevel(2);
fMethodsTree.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateSelectedMethodsLabel();
}
});
fMethodsTree.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof IMethod) {
IMethod method = (IMethod) element;
return !method.getElementName().equals("<clinit>"); //$NON-NLS-1$
}
return true;
}
});
Composite buttonContainer= new Composite(container, SWT.NONE);
gd= new GridData(GridData.FILL_VERTICAL);
buttonContainer.setLayoutData(gd);
GridLayout buttonLayout= new GridLayout();
buttonLayout.marginWidth= 0;
buttonLayout.marginHeight= 0;
buttonContainer.setLayout(buttonLayout);
fSelectAllButton= new Button(buttonContainer, SWT.PUSH);
fSelectAllButton.setText(WizardMessages.getString("NewTestClassWizPage2.selectAll")); //$NON-NLS-1$
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
fSelectAllButton.setLayoutData(gd);
fSelectAllButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fMethodsTree.setCheckedElements((Object[]) fMethodsTree.getInput());
updateSelectedMethodsLabel();
}
});
fDeselectAllButton= new Button(buttonContainer, SWT.PUSH);
fDeselectAllButton.setText(WizardMessages.getString("NewTestClassWizPage2.deselectAll")); //$NON-NLS-1$
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
fDeselectAllButton.setLayoutData(gd);
fDeselectAllButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fMethodsTree.setCheckedElements(new Object[0]);
updateSelectedMethodsLabel();
}
});
/* No of selected methods label */
fSelectedMethodsLabel= new Label(container, SWT.LEFT);
fSelectedMethodsLabel.setFont(container.getFont());
updateSelectedMethodsLabel();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 1;
fSelectedMethodsLabel.setLayoutData(gd);
Label emptyLabel= new Label(container, SWT.LEFT);
gd= new GridData();
gd.horizontalSpan= 1;
emptyLabel.setLayoutData(gd);
}
protected void createSpacer(Composite container) {
Label spacer= new Label(container, SWT.NONE);
GridData data= new GridData();
data.horizontalSpan= 2;
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
data.heightHint= 4;
spacer.setLayoutData(data);
}
/**
* @see DialogPage#setVisible(boolean)
*/
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
fClassToTest= fFirstPage.getClassToTest();
IType currType= fClassToTest;
ArrayList types= null;
try {
ITypeHierarchy hierarchy= currType.newSupertypeHierarchy(null);
IType[] superTypes;
if (currType.isClass())
superTypes= hierarchy.getAllSuperclasses(currType);
else if (currType.isInterface())
superTypes= hierarchy.getAllSuperInterfaces(currType);
else
superTypes= new IType[0];
types= new ArrayList(superTypes.length+1);
types.add(currType);
types.addAll(Arrays.asList(superTypes));
} catch(JavaModelException e) {
JUnitPlugin.log(e);
}
fMethodsTree.setContentProvider(new MethodsTreeContentProvider(types.toArray()));
if (types == null)
types= new ArrayList();
fMethodsTree.setInput(types.toArray());
fMethodsTree.setSelection(new StructuredSelection(currType), true);
updateSelectedMethodsLabel();
setFocus();
}
}
/**
* Returns all checked methods in the Methods tree.
*/
public IMethod[] getCheckedMethods() {
Object[] checkedObjects= fMethodsTree.getCheckedElements();
int methodCount= 0;
for (int i = 0; i < checkedObjects.length; i++) {
if (checkedObjects[i] instanceof IMethod)
methodCount++;
}
IMethod[] checkedMethods= new IMethod[methodCount];
int j= 0;
for (int i = 0; i < checkedObjects.length; i++) {
if (checkedObjects[i] instanceof IMethod) {
checkedMethods[j]= (IMethod)checkedObjects[i];
j++;
}
}
return checkedMethods;
}
private static class MethodsTreeContentProvider implements ITreeContentProvider {
private Object[] fTypes;
private IMethod[] fMethods;
private final Object[] fEmpty= new Object[0];
public MethodsTreeContentProvider(Object[] types) {
fTypes= types;
Vector methods= new Vector();
for (int i = types.length-1; i > -1; i--) {
Object object = types[i];
if (object instanceof IType) {
IType type = (IType) object;
try {
IMethod[] currMethods= type.getMethods();
for_currMethods:
for (int j = 0; j < currMethods.length; j++) {
IMethod currMethod = currMethods[j];
int flags= currMethod.getFlags();
if (!Flags.isPrivate(flags)) {
for (int k = 0; k < methods.size(); k++) {
IMethod m= ((IMethod)methods.get(k));
if (m.getElementName().equals(currMethod.getElementName())
&& m.getSignature().equals(currMethod.getSignature())) {
methods.set(k,currMethod);
continue for_currMethods;
}
}
methods.add(currMethod);
}
}
} catch (JavaModelException e) {
JUnitPlugin.log(e);
}
}
}
fMethods= new IMethod[methods.size()];
methods.copyInto(fMethods);
}
/*
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IType) {
IType parentType= (IType)parentElement;
ArrayList result= new ArrayList(fMethods.length);
for (int i= 0; i < fMethods.length; i++) {
if (fMethods[i].getDeclaringType().equals(parentType)) {
result.add(fMethods[i]);
}
}
return result.toArray();
}
return fEmpty;
}
/*
* @see ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
if (element instanceof IMethod)
return ((IMethod)element).getDeclaringType();
return null;
}
/*
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return fTypes;
}
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public IMethod[] getAllMethods() {
return fMethods;
}
}
/**
* Returns true if the checkbox for creating tasks is checked.
*/
public boolean getCreateTasksButtonSelection() {
return fCreateTasksButton.getSelection();
}
/**
* Returns true if the checkbox for final method stubs is checked.
*/
public boolean getCreateFinalMethodStubsButtonSelection() {
return fCreateFinalMethodStubsButton.getSelection();
}
/**
* Returns true if the checkbox for creating the constructor is checked.
*/
public boolean getCreateConstructorButtonSelection() {
return fCreateConstructorButton.getSelection();
}
private void updateSelectedMethodsLabel() {
Object[] checked= fMethodsTree.getCheckedElements();
int checkedMethodCount= 0;
for (int i= 0; i < checked.length; i++) {
if (checked[i] instanceof IMethod)
checkedMethodCount++;
}
String label= ""; //$NON-NLS-1$
if (checkedMethodCount == 1)
label= WizardMessages.getFormattedString("NewTestClassWizPage2.selected_methods.label_one", new Integer(checkedMethodCount)); //$NON-NLS-1$
else
label= WizardMessages.getFormattedString("NewTestClassWizPage2.selected_methods.label_many", new Integer(checkedMethodCount)); //$NON-NLS-1$
fSelectedMethodsLabel.setText(label);
}
/**
* Returns all the methods in the Methods tree.
*/
public IMethod[] getAllMethods() {
return ((MethodsTreeContentProvider)fMethodsTree.getContentProvider()).getAllMethods();
}
/**
* Sets the focus on the type name.
*/
protected void setFocus() {
fMethodsTree.getControl().setFocus();
}
/**
* Use the dialog store to restore widget values to the values that they held
* last time this wizard was used to completion
*/
private void restoreWidgetValues() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
fCreateTasksButton.setSelection(settings.getBoolean(STORE_USE_TASKMARKER));
fCreateFinalMethodStubsButton.setSelection(settings.getBoolean(STORE_CREATE_FINAL_METHOD_STUBS));
fCreateConstructorButton.setSelection(settings.getBoolean(STORE_CREATE_CONSTRUCTOR));
}
}
/**
* Since Finish was pressed, write widget values to the dialog store so that they
* will persist into the next invocation of this wizard page
*/
void saveWidgetValues() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
settings.put(STORE_USE_TASKMARKER, fCreateTasksButton.getSelection());
settings.put(STORE_CREATE_FINAL_METHOD_STUBS, fCreateFinalMethodStubsButton.getSelection());
settings.put(STORE_CREATE_CONSTRUCTOR, fCreateConstructorButton.getSelection());
}
}
}
|
8,165 |
Bug 8165 NLS: various bloopers on first wizard page [refactoring]
|
1) When the wizard opens, the wizard expands to the full height of the screen, even if only a few entries exist in the table. 2) check boxes should be combo boxes. 3) buttons on the left are not top-aligned with the table 4) the table is not left-aligned with the other widgets 5) If there's a legend to the table, it should be next to the table, not at the bottom of the wizard. 6) Windows only: The context is displayed w/ proportional font, although I never use proportional fonts in the editor.
|
closed wontfix
|
3340aba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T16:54:35Z | 2002-01-23T15:33:20Z |
org.eclipse.jdt.ui/ui
| |
8,165 |
Bug 8165 NLS: various bloopers on first wizard page [refactoring]
|
1) When the wizard opens, the wizard expands to the full height of the screen, even if only a few entries exist in the table. 2) check boxes should be combo boxes. 3) buttons on the left are not top-aligned with the table 4) the table is not left-aligned with the other widgets 5) If there's a legend to the table, it should be next to the table, not at the bottom of the wizard. 6) Windows only: The context is displayed w/ proportional font, although I never use proportional fonts in the editor.
|
closed wontfix
|
3340aba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-25T16:54:35Z | 2002-01-23T15:33:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/ExternalizeWizardPage.java
| |
34,315 |
Bug 34315 Refactoring lost source folder property on Java Project [refactoring]
|
RC2 In the process of "just working'. Renaming Java projects and contained java packages and classes I eventually go an error that a particular "path" could not be found and a bunch of stuff in my .log file. After all this the source folder in the refactored Java project is no longer a source folder. I will work on steps to reproduce but can not get to it until after I to the copyright updating. For now I will give you the general flavour of what I was doing and I will attach my .log file. 1) I had a Java project that was orignally created with the New Project Plugin Development - > Plug-in Project wizard (plug-in with a popup menu). 2) Several days development in this project under an older (pre RC2 build. Probably RC1). 3) Delete everything in Eclipse directory except Workspace 4) Unzip RC2. 5) Do more work in project 6) Refactor project doing the following: a) Refactor-Rename project (Noticed oddnesss is a Meta-Inf folder was created in new place 7) Renamed several classes in the project. 8) Deleted the Meta-Inf folder as uninteresting. Just one simple text file in it. 9) Renamed some more classes. On a class rename got an error dialog stating it could not find the class and output sent to .log.
|
resolved fixed
|
1068ef8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-28T12:12:47Z | 2003-03-10T15:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchUtil.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.browsing.JavaElementTypeComparator;
import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* This class contains some utility methods for J Search.
*/
public class SearchUtil extends JavaModelUtil {
// LRU working sets
public static int LRU_WORKINGSET_LIST_SIZE= 3;
private static LRUWorkingSetsList fgLRUWorkingSets;
// Settings store
private static final String DIALOG_SETTINGS_KEY= "JavaElementSearchActions"; //$NON-NLS-1$
private static final String STORE_LRU_WORKING_SET_NAMES= "lastUsedWorkingSetNames"; //$NON-NLS-1$
private static final JavaElementTypeComparator fgJavaElementTypeComparator= new JavaElementTypeComparator();
private static IDialogSettings fgSettingsStore;
private static final String BIN_PRIM_CONST_WARN_DIALOG_ID= "BinaryPrimitiveConstantWarningDialog"; //$NON-NLS-1$
public static IJavaElement getJavaElement(IMarker marker) {
if (marker == null || !marker.exists())
return null;
try {
String handleId= (String)marker.getAttribute(IJavaSearchUIConstants.ATT_JE_HANDLE_ID);
IJavaElement je= JavaCore.create(handleId);
if (je == null)
return null;
if (!marker.getAttribute(IJavaSearchUIConstants.ATT_IS_WORKING_COPY, false)) {
if (je != null && je.exists())
return je;
}
if (isBinary(je) || fgJavaElementTypeComparator.compare(je, IJavaElement.COMPILATION_UNIT) > 0)
return je;
ICompilationUnit cu= findCompilationUnit(je);
if (cu == null || !cu.exists()) {
cu= (ICompilationUnit)JavaCore.create(marker.getResource());
}
// Find working copy element
IWorkingCopy[] workingCopies= JavaUI.getSharedWorkingCopiesOnClasspath();
int i= 0;
while (i < workingCopies.length) {
if (workingCopies[i].getOriginalElement().equals(cu)) {
je= findInWorkingCopy(workingCopies[i], je, true);
break;
}
i++;
}
if (je != null && !je.exists()) {
IJavaElement[] jElements= cu.findElements(je);
if (jElements == null || jElements.length == 0)
je= cu.getElementAt(marker.getAttribute(IMarker.CHAR_START, 0));
else
je= jElements[0];
}
return je;
} catch (CoreException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.createJavaElement.title"), SearchMessages.getString("Search.Error.createJavaElement.message")); //$NON-NLS-2$ //$NON-NLS-1$
return null;
}
}
public static IJavaElement getJavaElement(Object entry) {
if (entry != null && isISearchResultViewEntry(entry))
return getJavaElement((ISearchResultViewEntry)entry);
return null;
}
public static IResource getResource(Object entry) {
if (entry != null && isISearchResultViewEntry(entry))
return ((ISearchResultViewEntry)entry).getResource();
return null;
}
public static IJavaElement getJavaElement(ISearchResultViewEntry entry) {
if (entry != null)
return getJavaElement(entry.getSelectedMarker());
return null;
}
public static boolean isSearchPlugInActivated() {
return Platform.getPluginRegistry().getPluginDescriptor("org.eclipse.search").isPluginActivated(); //$NON-NLS-1$
}
public static boolean isISearchResultViewEntry(Object object) {
return object != null && isSearchPlugInActivated() && (object instanceof ISearchResultViewEntry);
}
private static boolean isBinary(IJavaElement jElement) {
if (jElement instanceof IMember)
return ((IMember)jElement).isBinary();
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)jElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (pkgRoot != null && pkgRoot.isArchive())
return true;
return false;
}
/**
* Returns the working copy of the given java element.
* @param javaElement the javaElement for which the working copyshould be found
* @param reconcile indicates whether the working copy must be reconcile prior to searching it
* @return the working copy of the given element or <code>null</code> if none
*/
private static IJavaElement findInWorkingCopy(IWorkingCopy workingCopy, IJavaElement element, boolean reconcile) throws JavaModelException {
if (workingCopy != null) {
if (reconcile) {
synchronized (workingCopy) {
workingCopy.reconcile();
return SearchUtil.findInCompilationUnit((ICompilationUnit)workingCopy, element);
}
} else {
return SearchUtil.findInCompilationUnit((ICompilationUnit)workingCopy, element);
}
}
return null;
}
/**
* Returns the compilation unit for the given java element.
*
* @param element the java element whose compilation unit is searched for
* @return the compilation unit of the given java element
*/
static ICompilationUnit findCompilationUnit(IJavaElement element) {
if (element == null)
return null;
if (element.getElementType() == IJavaElement.COMPILATION_UNIT)
return (ICompilationUnit)element;
if (element instanceof IMember)
return ((IMember)element).getCompilationUnit();
return findCompilationUnit(element.getParent());
}
/*
* Copied from JavaModelUtil and patched to allow members which do not exist.
* The only case where this is a problem is for methods which have same name and
* paramters as a constructor. The constructor will win in such a situation.
*
* @see JavaModelUtil#findMemberInCompilationUnit(ICompilationUnit, IMember)
*/
public static IMember findInCompilationUnit(ICompilationUnit cu, IMember member) throws JavaModelException {
if (member.getElementType() == IJavaElement.TYPE) {
return findTypeInCompilationUnit(cu, getTypeQualifiedName((IType)member));
} else {
IType declaringType= findTypeInCompilationUnit(cu, getTypeQualifiedName(member.getDeclaringType()));
if (declaringType != null) {
IMember result= null;
switch (member.getElementType()) {
case IJavaElement.FIELD:
result= declaringType.getField(member.getElementName());
break;
case IJavaElement.METHOD:
IMethod meth= (IMethod) member;
// XXX: Begin patch ---------------------
boolean isConstructor;
if (meth.exists())
isConstructor= meth.isConstructor();
else
isConstructor= declaringType.getElementName().equals(meth.getElementName());
// XXX: End patch -----------------------
result= findMethod(meth.getElementName(), meth.getParameterTypes(), isConstructor, declaringType);
break;
case IJavaElement.INITIALIZER:
result= declaringType.getInitializer(1);
break;
}
if (result != null && result.exists()) {
return result;
}
}
}
return null;
}
/*
* XXX: Unchanged copy from JavaModelUtil
*/
public static IJavaElement findInCompilationUnit(ICompilationUnit cu, IJavaElement element) throws JavaModelException {
if (element instanceof IMember)
return findInCompilationUnit(cu, (IMember)element);
int type= element.getElementType();
switch (type) {
case IJavaElement.IMPORT_CONTAINER:
return cu.getImportContainer();
case IJavaElement.PACKAGE_DECLARATION:
return find(cu.getPackageDeclarations(), element.getElementName());
case IJavaElement.IMPORT_DECLARATION:
return find(cu.getImports(), element.getElementName());
case IJavaElement.COMPILATION_UNIT:
return cu;
}
return null;
}
/*
* XXX: Unchanged copy from JavaModelUtil
*/
private static IJavaElement find(IJavaElement[] elements, String name) {
if (elements == null || name == null)
return null;
for (int i= 0; i < elements.length; i++) {
if (name.equals(elements[i].getElementName()))
return elements[i];
}
return null;
}
public static String toString(IWorkingSet[] workingSets) {
Arrays.sort(workingSets, new WorkingSetComparator());
String result= ""; //$NON-NLS-1$
if (workingSets != null && workingSets.length > 0) {
boolean firstFound= false;
for (int i= 0; i < workingSets.length; i++) {
String workingSetName= workingSets[i].getName();
if (firstFound)
result= SearchMessages.getFormattedString("SearchUtil.workingSetConcatenation", new String[] {result, workingSetName}); //$NON-NLS-1$
else {
result= workingSetName;
firstFound= true;
}
}
}
return result;
}
// ---------- LRU working set handling ----------
/**
* Updates the LRU list of working sets.
*
* @param workingSets the workings sets to be added to the LRU list
*/
public static void updateLRUWorkingSets(IWorkingSet[] workingSets) {
if (workingSets == null || workingSets.length < 1)
return;
getLRUWorkingSets().add(workingSets);
saveState();
}
private static void saveState() {
IWorkingSet[] workingSets;
Iterator iter= fgLRUWorkingSets.iterator();
int i= 0;
while (iter.hasNext()) {
workingSets= (IWorkingSet[])iter.next();
String[] names= new String[workingSets.length];
for (int j= 0; j < workingSets.length; j++)
names[j]= workingSets[j].getName();
fgSettingsStore.put(STORE_LRU_WORKING_SET_NAMES + i, names);
i++;
}
}
public static LRUWorkingSetsList getLRUWorkingSets() {
if (fgLRUWorkingSets == null) {
restoreState();
}
return fgLRUWorkingSets;
}
static void restoreState() {
fgLRUWorkingSets= new LRUWorkingSetsList(LRU_WORKINGSET_LIST_SIZE);
fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS_KEY);
if (fgSettingsStore == null)
fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS_KEY);
boolean foundLRU= false;
for (int i= LRU_WORKINGSET_LIST_SIZE - 1; i >= 0; i--) {
String[] lruWorkingSetNames= fgSettingsStore.getArray(STORE_LRU_WORKING_SET_NAMES + i);
if (lruWorkingSetNames != null) {
Set workingSets= new HashSet(2);
for (int j= 0; j < lruWorkingSetNames.length; j++) {
IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[j]);
if (workingSet != null) {
workingSets.add(workingSet);
}
}
foundLRU= true;
if (!workingSets.isEmpty())
fgLRUWorkingSets.add((IWorkingSet[])workingSets.toArray(new IWorkingSet[workingSets.size()]));
}
}
if (!foundLRU)
// try old preference format
restoreFromOldFormat();
}
private static void restoreFromOldFormat() {
fgLRUWorkingSets= new LRUWorkingSetsList(LRU_WORKINGSET_LIST_SIZE);
fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS_KEY);
if (fgSettingsStore == null)
fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS_KEY);
boolean foundLRU= false;
String[] lruWorkingSetNames= fgSettingsStore.getArray(STORE_LRU_WORKING_SET_NAMES);
if (lruWorkingSetNames != null) {
for (int i= lruWorkingSetNames.length - 1; i >= 0; i--) {
IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[i]);
if (workingSet != null) {
foundLRU= true;
fgLRUWorkingSets.add(new IWorkingSet[]{workingSet});
}
}
}
if (foundLRU)
// save in new format
saveState();
}
public static void warnIfBinaryConstant(IJavaElement element, Shell shell) {
if (isBinaryPrimitveConstantOrString(element))
OptionalMessageDialog.open(
BIN_PRIM_CONST_WARN_DIALOG_ID,
shell,
SearchMessages.getString("Search.FindReferencesAction.BinPrimConstWarnDialog.title"), //$NON-NLS-1$
null,
SearchMessages.getString("Search.FindReferencesAction.BinPrimConstWarnDialog.message"), //$NON-NLS-1$
OptionalMessageDialog.INFORMATION,
new String[] { IDialogConstants.OK_LABEL },
0);
}
private static boolean isBinaryPrimitveConstantOrString(IJavaElement element) {
if (element != null && element.getElementType() == IJavaElement.FIELD) {
IField field= (IField)element;
int flags;
try {
flags= field.getFlags();
} catch (JavaModelException ex) {
return false;
}
return field.isBinary() && Flags.isStatic(flags) && Flags.isFinal(flags) && isPrimitiveOrString(field);
}
return false;
}
private static boolean isPrimitiveOrString(IField field) {
String fieldType;
try {
fieldType= field.getTypeSignature();
} catch (JavaModelException ex) {
return false;
}
char first= fieldType.charAt(0);
return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED && first != Signature.C_ARRAY)
|| (first == Signature.C_RESOLVED && fieldType.substring(1, fieldType.length() - 1).equals(String.class.getName()));
}
}
|
36,519 |
Bug 36519 [call hierarchy] ability to copy the view's content to the clipboard
|
we should add the ability to copy the view's content to the clipboard (it may be useful for people to take a pic of the callgraph and show to other people, for example)
|
resolved fixed
|
2bdf14e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T08:57:53Z | 2003-04-15T18:06:40Z |
org.eclipse.jdt.ui/core
| |
36,519 |
Bug 36519 [call hierarchy] ability to copy the view's content to the clipboard
|
we should add the ability to copy the view's content to the clipboard (it may be useful for people to take a pic of the callgraph and show to other people, for example)
|
resolved fixed
|
2bdf14e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T08:57:53Z | 2003-04-15T18:06:40Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/CallHierarchyVisitor.java
| |
36,519 |
Bug 36519 [call hierarchy] ability to copy the view's content to the clipboard
|
we should add the ability to copy the view's content to the clipboard (it may be useful for people to take a pic of the callgraph and show to other people, for example)
|
resolved fixed
|
2bdf14e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T08:57:53Z | 2003-04-15T18:06:40Z |
org.eclipse.jdt.ui/core
| |
36,519 |
Bug 36519 [call hierarchy] ability to copy the view's content to the clipboard
|
we should add the ability to copy the view's content to the clipboard (it may be useful for people to take a pic of the callgraph and show to other people, for example)
|
resolved fixed
|
2bdf14e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T08:57:53Z | 2003-04-15T18:06:40Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/MethodWrapper.java
| |
36,519 |
Bug 36519 [call hierarchy] ability to copy the view's content to the clipboard
|
we should add the ability to copy the view's content to the clipboard (it may be useful for people to take a pic of the callgraph and show to other people, for example)
|
resolved fixed
|
2bdf14e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T08:57:53Z | 2003-04-15T18:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.corext.callhierarchy.CallHierarchy;
import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
/**
* This is the main view for the callers plugin. It builds a tree of callers/callees
* and allows the user to double click an entry to go to the selected method.
*
*/
public class CallHierarchyViewPart extends ViewPart implements ICallHierarchyViewPart, IDoubleClickListener,
ISelectionChangedListener {
private CallHierarchyViewSiteAdapter fViewSiteAdapter;
private CallHierarchyViewAdapter fViewAdapter;
private static final String DIALOGSTORE_VIEWORIENTATION = "CallHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String DIALOGSTORE_CALL_MODE = "CallHierarchyViewPart.call_mode"; //$NON-NLS-1$
private static final String TAG_ORIENTATION = "orientation"; //$NON-NLS-1$
private static final String TAG_CALL_MODE = "call_mode"; //$NON-NLS-1$
private static final String TAG_IMPLEMENTORS_MODE = "implementors_mode"; //$NON-NLS-1$
private static final String TAG_RATIO = "ratio"; //$NON-NLS-1$
static final int VIEW_ORIENTATION_VERTICAL = 0;
static final int VIEW_ORIENTATION_HORIZONTAL = 1;
static final int VIEW_ORIENTATION_SINGLE = 2;
static final int CALL_MODE_CALLERS = 0;
static final int CALL_MODE_CALLEES = 1;
static final int IMPLEMENTORS_ENABLED = 0;
static final int IMPLEMENTORS_DISABLED = 1;
static final String GROUP_SEARCH_SCOPE = "MENU_SEARCH_SCOPE"; //$NON-NLS-1$
static final String ID_CALL_HIERARCHY = "org.eclipse.jdt.callhierarchy.view"; //$NON-NLS-1$
private static final String GROUP_FOCUS = "group.focus"; //$NON-NLS-1$
private static final int PAGE_EMPTY = 0;
private static final int PAGE_VIEWER = 1;
private Label fNoHierarchyShownLabel;
private PageBook fPagebook;
private IDialogSettings fDialogSettings;
private int fCurrentOrientation;
private int fCurrentCallMode;
private int fCurrentImplementorsMode;
private MethodWrapper fCalleeRoot;
private MethodWrapper fCallerRoot;
private IMemento fMemento;
private IMethod fShownMethod;
private SelectionProviderMediator fSelectionProviderMediator;
private List fMethodHistory;
private TableViewer fLocationViewer;
private Menu fLocationContextMenu;
private SashForm fHierarchyLocationSplitter;
private SearchScopeActionGroup fSearchScopeActions;
private ToggleOrientationAction[] fToggleOrientationActions;
private ToggleCallModeAction[] fToggleCallModeActions;
private ToggleImplementorsAction[] fToggleImplementorsActions;
private CallHierarchyFiltersActionGroup fFiltersActionGroup;
private HistoryDropDownAction fHistoryDropDownAction;
private RefreshAction fRefreshAction;
private OpenLocationAction fOpenLocationAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private CompositeActionGroup fActionGroups;
private CallHierarchyViewer fCallHierarchyViewer;
private boolean fShowCallDetails;
public CallHierarchyViewPart() {
super();
fDialogSettings = JavaPlugin.getDefault().getDialogSettings();
fMethodHistory = new ArrayList();
}
public void setFocus() {
fPagebook.setFocus();
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IMethod[] elems) {
fMethodHistory.clear();
for (int i = 0; i < elems.length; i++) {
fMethodHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Gets all history entries.
*/
public IMethod[] getHistoryEntries() {
if (fMethodHistory.size() > 0) {
updateHistoryEntries();
}
return (IMethod[]) fMethodHistory.toArray(new IMethod[fMethodHistory.size()]);
}
/**
* Method setMethod.
* @param method
*/
public void setMethod(IMethod method) {
if (method == null) {
showPage(PAGE_EMPTY);
return;
}
if ((method != null) && !method.equals(fShownMethod)) {
addHistoryEntry(method);
}
this.fShownMethod = method;
refresh();
}
public IMethod getMethod() {
return fShownMethod;
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
if ((fLocationViewer != null) && !fLocationViewer.getControl().isDisposed() &&
(fHierarchyLocationSplitter != null) &&
!fHierarchyLocationSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
setShowCallDetails(false);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
setShowCallDetails(true);
}
boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL;
fHierarchyLocationSplitter.setOrientation(horizontal ? SWT.HORIZONTAL
: SWT.VERTICAL);
}
fHierarchyLocationSplitter.layout();
}
for (int i = 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation = orientation;
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
/**
* called from ToggleCallModeAction.
* @param orientation CALL_MODE_CALLERS or CALL_MODE_CALLEES
*/
void setCallMode(int mode) {
if (fCurrentCallMode != mode) {
for (int i = 0; i < fToggleCallModeActions.length; i++) {
fToggleCallModeActions[i].setChecked(mode == fToggleCallModeActions[i].getMode());
}
fCurrentCallMode = mode;
fDialogSettings.put(DIALOGSTORE_CALL_MODE, mode);
updateView();
}
}
/**
* called from ToggleImplementorsAction.
* @param implementorsMode IMPLEMENTORS_USED or IMPLEMENTORS_NOT_USED
*/
void setImplementorsMode(int implementorsMode) {
if (fCurrentImplementorsMode != implementorsMode) {
for (int i = 0; i < fToggleImplementorsActions.length; i++) {
fToggleImplementorsActions[i].setChecked(implementorsMode == fToggleImplementorsActions[i].getImplementorsMode());
}
fCurrentImplementorsMode = implementorsMode;
CallHierarchy.getDefault().setSearchUsingImplementorsEnabled(implementorsMode == IMPLEMENTORS_ENABLED);
updateView();
}
}
public IJavaSearchScope getSearchScope() {
return fSearchScopeActions.getSearchScope();
}
public void setShowCallDetails(boolean show) {
fShowCallDetails = show;
showOrHideCallDetailsView();
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
addDragAdapters(fCallHierarchyViewer, ops, transfers);
addDropAdapters(fCallHierarchyViewer, ops | DND.DROP_DEFAULT, transfers);
addDropAdapters(fLocationViewer, ops | DND.DROP_DEFAULT, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new CallHierarchyTransferDropAdapter(this, fCallHierarchyViewer));
}
private void addDropAdapters(StructuredViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new CallHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) {
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(new SelectionProviderAdapter(viewer))
};
viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
}
public void createPartControl(Composite parent) {
fPagebook = new PageBook(parent, SWT.NONE);
// Page 1: Viewers
createHierarchyLocationSplitter(fPagebook);
createCallHierarchyViewer(fHierarchyLocationSplitter);
createLocationViewer(fHierarchyLocationSplitter);
// Page 2: Nothing selected
fNoHierarchyShownLabel = new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(CallHierarchyMessages.getString(
"CallHierarchyViewPart.empty")); //$NON-NLS-1$
showPage(PAGE_EMPTY);
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fSelectionProviderMediator = new SelectionProviderMediator(new Viewer[] {
fCallHierarchyViewer, fLocationViewer
});
IStatusLineManager slManager = getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(
slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
makeActions();
fillViewMenu();
fillActionBars();
initOrientation();
initCallMode();
initImplementorsMode();
if (fMemento != null) {
restoreState(fMemento);
}
initDragAndDrop();
}
/**
* @param PAGE_EMPTY
*/
private void showPage(int page) {
if (page == PAGE_EMPTY) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
fPagebook.showPage(fHierarchyLocationSplitter);
}
enableActions(page != PAGE_EMPTY);
}
/**
* @param b
*/
private void enableActions(boolean enabled) {
fLocationContextMenu.setEnabled(enabled);
// TODO: Is it possible to disable the actions on the toolbar and on the view menu?
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento) {
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer callMode= memento.getInteger(TAG_CALL_MODE);
if (callMode != null) {
setCallMode(callMode.intValue());
}
Integer implementorsMode= memento.getInteger(TAG_IMPLEMENTORS_MODE);
if (implementorsMode != null) {
setImplementorsMode(implementorsMode.intValue());
}
Integer ratio = memento.getInteger(TAG_RATIO);
if (ratio != null) {
fHierarchyLocationSplitter.setWeights(new int[] {
ratio.intValue(), 1000 - ratio.intValue()
});
}
}
private void initCallMode() {
int mode;
try {
mode = fDialogSettings.getInt(DIALOGSTORE_CALL_MODE);
if ((mode < 0) || (mode > 1)) {
mode = CALL_MODE_CALLERS;
}
} catch (NumberFormatException e) {
mode = CALL_MODE_CALLERS;
}
// force the update
fCurrentCallMode = -1;
// will fill the main tool bar
setCallMode(mode);
}
private void initImplementorsMode() {
int mode;
mode= CallHierarchy.getDefault().isSearchUsingImplementorsEnabled() ? IMPLEMENTORS_ENABLED : IMPLEMENTORS_DISABLED;
fCurrentImplementorsMode= -1;
// will fill the main tool bar
setImplementorsMode(mode);
}
private void initOrientation() {
int orientation;
try {
orientation = fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if ((orientation < 0) || (orientation > 2)) {
orientation = VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation = VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation = -1;
// will fill the main tool bar
setOrientation(orientation);
}
private void fillViewMenu() {
IActionBars actionBars = getViewSite().getActionBars();
IMenuManager viewMenu = actionBars.getMenuManager();
viewMenu.add(new Separator());
for (int i = 0; i < fToggleCallModeActions.length; i++) {
viewMenu.add(fToggleCallModeActions[i]);
}
viewMenu.add(new Separator());
// TODO: Should be reenabled if this toggle should actually be used
// for (int i = 0; i < fToggleImplementorsActions.length; i++) {
// viewMenu.add(fToggleImplementorsActions[i]);
// }
//
// viewMenu.add(new Separator());
for (int i = 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
}
/**
*
*/
public void dispose() {
disposeMenu(fLocationContextMenu);
if (fActionGroups != null)
fActionGroups.dispose();
super.dispose();
}
/**
* Double click listener which jumps to the method in the source code.
*
* @return IDoubleClickListener
*/
public void doubleClick(DoubleClickEvent event) {
jumpToSelection(event.getSelection());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IMethod entry) {
if (fMethodHistory.contains(entry)) {
setMethod(entry);
}
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento)
throws PartInitException {
super.init(site, memento);
fMemento = memento;
}
public void jumpToDeclarationOfSelection() {
ISelection selection = null;
selection = getSelection();
if ((selection != null) && selection instanceof IStructuredSelection) {
Object structuredSelection = ((IStructuredSelection) selection).getFirstElement();
if (structuredSelection instanceof IMember) {
CallHierarchyUI.jumpToMember((IMember) structuredSelection);
} else if (structuredSelection instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) structuredSelection;
CallHierarchyUI.jumpToMember(methodWrapper.getMember());
} else if (structuredSelection instanceof CallLocation) {
CallHierarchyUI.jumpToMember(((CallLocation) structuredSelection).getCalledMember());
}
}
}
public void jumpToSelection(ISelection selection) {
if ((selection != null) && selection instanceof IStructuredSelection) {
Object structuredSelection = ((IStructuredSelection) selection).getFirstElement();
if (structuredSelection instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) structuredSelection;
CallLocation firstCall = methodWrapper.getMethodCall()
.getFirstCallLocation();
if (firstCall != null) {
CallHierarchyUI.jumpToLocation(firstCall);
} else {
CallHierarchyUI.jumpToMember(methodWrapper.getMember());
}
} else if (structuredSelection instanceof CallLocation) {
CallHierarchyUI.jumpToLocation((CallLocation) structuredSelection);
}
}
}
/**
*
*/
public void refresh() {
setCalleeRoot(null);
setCallerRoot(null);
updateView();
}
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
memento.putInteger(TAG_CALL_MODE, fCurrentCallMode);
memento.putInteger(TAG_IMPLEMENTORS_MODE, fCurrentImplementorsMode);
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int[] weigths = fHierarchyLocationSplitter.getWeights();
int ratio = (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
}
/**
* @return ISelectionChangedListener
*/
public void selectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fCallHierarchyViewer) {
methodSelectionChanged(e.getSelection());
}
}
/**
* @param selection
*/
private void methodSelectionChanged(ISelection selection) {
if (selection instanceof IStructuredSelection) {
Object selectedElement = ((IStructuredSelection) selection).getFirstElement();
if (selectedElement instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) selectedElement;
revealElementInEditor(methodWrapper, fCallHierarchyViewer);
updateLocationsView(methodWrapper);
} else {
updateLocationsView(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
if (elem instanceof MethodWrapper) {
CallLocation callLocation = CallHierarchy.getCallLocation(elem);
if (callLocation != null) {
IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(callLocation);
if (editorPart != null) {
getSite().getPage().bringToTop(editorPart);
if (editorPart instanceof ITextEditor) {
ITextEditor editor = (ITextEditor) editorPart;
editor.selectAndReveal(callLocation.getStart(),
(callLocation.getEnd() - callLocation.getStart()));
}
}
} else {
IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(elem);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart,
((MethodWrapper) elem).getMember());
}
} else if (elem instanceof IJavaElement) {
IEditorPart editorPart = EditorUtility.isOpenInEditor(elem);
if (editorPart != null) {
// getSite().getPage().removePartListener(fPartListener);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
// getSite().getPage().addPartListener(fPartListener);
}
}
}
/**
* Returns the current selection.
*/
protected ISelection getSelection() {
return getSite().getSelectionProvider().getSelection();
}
protected void fillContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
}
protected void handleKeyEvent(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
if ((fRefreshAction != null) && fRefreshAction.isEnabled()) {
fRefreshAction.run();
return;
}
}
}
}
private IActionBars getActionBars() {
return getViewSite().getActionBars();
}
private void setCalleeRoot(MethodWrapper calleeRoot) {
this.fCalleeRoot = calleeRoot;
}
private MethodWrapper getCalleeRoot() {
if (fCalleeRoot == null) {
fCalleeRoot = (MethodWrapper) CallHierarchy.getDefault().getCalleeRoot(fShownMethod);
}
return fCalleeRoot;
}
private void setCallerRoot(MethodWrapper callerRoot) {
this.fCallerRoot = callerRoot;
}
private MethodWrapper getCallerRoot() {
if (fCallerRoot == null) {
fCallerRoot = (MethodWrapper) CallHierarchy.getDefault().getCallerRoot(fShownMethod);
}
return fCallerRoot;
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fMethodHistory.contains(entry)) {
fMethodHistory.remove(entry);
}
fMethodHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
}
/**
* @param parent
*/
private void createLocationViewer(Composite parent) {
fLocationViewer = new TableViewer(parent, SWT.NONE);
fLocationViewer.setContentProvider(new ArrayContentProvider());
fLocationViewer.setLabelProvider(new LocationLabelProvider());
fLocationViewer.setInput(new ArrayList());
fLocationViewer.getControl().addKeyListener(createKeyListener());
JavaUIHelp.setHelp(fLocationViewer, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fOpenLocationAction = new OpenLocationAction(getSite());
fLocationViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fOpenLocationAction.run();
}
});
// fListViewer.addDoubleClickListener(this);
MenuManager menuMgr = new MenuManager(); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
/* (non-Javadoc)
* @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
public void menuAboutToShow(IMenuManager manager) {
fillContextMenu(manager);
}
});
fLocationContextMenu = menuMgr.createContextMenu(fLocationViewer.getControl());
fLocationViewer.getControl().setMenu(fLocationContextMenu);
// Register viewer with site. This must be done before making the actions.
getSite().registerContextMenu(menuMgr, fLocationViewer);
}
private void createHierarchyLocationSplitter(Composite parent) {
fHierarchyLocationSplitter = new SashForm(parent, SWT.NONE);
fHierarchyLocationSplitter.addKeyListener(createKeyListener());
}
private void createCallHierarchyViewer(Composite parent) {
fCallHierarchyViewer = new CallHierarchyViewer(parent, this);
fCallHierarchyViewer.addKeyListener(createKeyListener());
fCallHierarchyViewer.addSelectionChangedListener(this);
fCallHierarchyViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillCallHierarchyViewerContextMenu(menu);
}
}, ID_CALL_HIERARCHY, getSite());
}
/**
* @param fCallHierarchyViewer
* @param menu
*/
protected void fillCallHierarchyViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
if (fFocusOnSelectionAction.canActionBeAdded()) {
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
}
fActionGroups.setContext(new ActionContext(getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
private void disposeMenu(Menu contextMenu) {
if ((contextMenu != null) && !contextMenu.isDisposed()) {
contextMenu.dispose();
}
}
private void fillActionBars() {
IActionBars actionBars = getActionBars();
IToolBarManager toolBar = actionBars.getToolBarManager();
fActionGroups.fillActionBars(actionBars);
toolBar.add(fHistoryDropDownAction);
for (int i = 0; i < fToggleCallModeActions.length; i++) {
toolBar.add(fToggleCallModeActions[i]);
}
}
private KeyListener createKeyListener() {
KeyListener keyListener = new KeyAdapter() {
public void keyReleased(KeyEvent event) {
handleKeyEvent(event);
}
};
return keyListener;
}
/**
*
*/
private void makeActions() {
fRefreshAction = new RefreshAction(this);
fFocusOnSelectionAction = new FocusOnSelectionAction(this);
fSearchScopeActions = new SearchScopeActionGroup(this);
fFiltersActionGroup = new CallHierarchyFiltersActionGroup(this,
fCallHierarchyViewer);
fHistoryDropDownAction = new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions = new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fToggleCallModeActions = new ToggleCallModeAction[] {
new ToggleCallModeAction(this, CALL_MODE_CALLERS),
new ToggleCallModeAction(this, CALL_MODE_CALLEES)
};
fToggleImplementorsActions = new ToggleImplementorsAction[] {
new ToggleImplementorsAction(this, IMPLEMENTORS_ENABLED),
new ToggleImplementorsAction(this, IMPLEMENTORS_DISABLED)
};
fActionGroups = new CompositeActionGroup(new ActionGroup[] {
new OpenEditorActionGroup(getViewAdapter()),
new OpenViewActionGroup(getViewAdapter()),
new CCPActionGroup(getViewAdapter()),
new GenerateActionGroup(getViewAdapter()),
new RefactorActionGroup(getViewAdapter()),
new JavaSearchActionGroup(getViewAdapter()),
fSearchScopeActions, fFiltersActionGroup
});
}
private CallHierarchyViewAdapter getViewAdapter() {
if (fViewAdapter == null) {
fViewAdapter= new CallHierarchyViewAdapter(getViewSiteAdapter());
}
return fViewAdapter;
}
private CallHierarchyViewSiteAdapter getViewSiteAdapter() {
if (fViewSiteAdapter == null) {
fViewSiteAdapter= new CallHierarchyViewSiteAdapter(this.getViewSite());
}
return fViewSiteAdapter;
}
private void showOrHideCallDetailsView() {
if (fShowCallDetails) {
fHierarchyLocationSplitter.setMaximizedControl(null);
} else {
fHierarchyLocationSplitter.setMaximizedControl(fCallHierarchyViewer.getControl());
}
}
private void updateLocationsView(MethodWrapper methodWrapper) {
if (methodWrapper != null) {
fLocationViewer.setInput(methodWrapper.getMethodCall().getCallLocations());
} else {
fLocationViewer.setInput(""); //$NON-NLS-1$
}
}
private void updateHistoryEntries() {
for (int i = fMethodHistory.size() - 1; i >= 0; i--) {
IMethod method = (IMethod) fMethodHistory.get(i);
if (!method.exists()) {
fMethodHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
}
/**
* Method updateView.
*/
private void updateView() {
if ((fShownMethod != null)) {
showPage(PAGE_VIEWER);
CallHierarchy.getDefault().setSearchScope(getSearchScope());
if (fCurrentCallMode == CALL_MODE_CALLERS) {
setTitle(CallHierarchyMessages.getString("CallHierarchyViewPart.callsToMethod")); //$NON-NLS-1$
fCallHierarchyViewer.setMethodWrapper(getCallerRoot());
} else {
setTitle(CallHierarchyMessages.getString("CallHierarchyViewPart.callsFromMethod")); //$NON-NLS-1$
fCallHierarchyViewer.setMethodWrapper(getCalleeRoot());
}
updateLocationsView(null);
}
}
static CallHierarchyViewPart findAndShowCallersView(IWorkbenchPartSite site) {
IWorkbenchPage workbenchPage = site.getPage();
CallHierarchyViewPart callersView = null;
try {
callersView = (CallHierarchyViewPart) workbenchPage.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
return callersView;
}
}
|
36,519 |
Bug 36519 [call hierarchy] ability to copy the view's content to the clipboard
|
we should add the ability to copy the view's content to the clipboard (it may be useful for people to take a pic of the callgraph and show to other people, for example)
|
resolved fixed
|
2bdf14e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T08:57:53Z | 2003-04-15T18:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CopyCallHierarchyAction.java
| |
35,379 |
Bug 35379 (possibly regression) Moving to default package adds ".*" import[ccp]
|
Build I20030319 - import JUnit 3.7 - create a class Foo in the default package - in the package explorer grab junit.awtui.ProgressBar - drag it to the default package - click OK in the apearing dialog - click OK in the apearing dialog ==> a new package import is added to TestRunner: import .*;
|
verified fixed
|
7392bc8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T09:30:49Z | 2003-03-20T17:06:40Z |
org.eclipse.jdt.ui/core
| |
35,379 |
Bug 35379 (possibly regression) Moving to default package adds ".*" import[ccp]
|
Build I20030319 - import JUnit 3.7 - create a class Foo in the default package - in the package explorer grab junit.awtui.ProgressBar - drag it to the default package - click OK in the apearing dialog - click OK in the apearing dialog ==> a new package import is added to TestRunner: import .*;
|
verified fixed
|
7392bc8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T09:30:49Z | 2003-03-20T17:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveCuUpdateCreator.java
| |
36,990 |
Bug 36990 Quickfix for generating missing method ignores array dimension [quick fix]
|
Build 20030422 When activating quickfix on: Object ob[] = tabList.getSelectedValues(); where #getSelectedValues is missing, it will generate a method of type Object, where it should have been typed with Object[]
|
resolved fixed
|
1bf20d9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-29T15:05:25Z | 2003-04-28T11:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.PrimitiveType.Code;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
public class ASTResolving {
public static ITypeBinding normalizeTypeBinding(ITypeBinding binding) {
if (binding != null && !binding.isNullType() && !"void".equals(binding.getName())) { //$NON-NLS-1$
if (binding.isAnonymous()) {
ITypeBinding[] baseBindings= binding.getInterfaces();
if (baseBindings.length > 0) {
return baseBindings[0];
}
return binding.getSuperclass();
}
return binding;
}
return null;
}
public static ITypeBinding guessBindingForReference(ASTNode node) {
return normalizeTypeBinding(getPossibleReferenceBinding(node));
}
private static ITypeBinding getPossibleReferenceBinding(ASTNode node) {
ASTNode parent= node.getParent();
switch (parent.getNodeType()) {
case ASTNode.ASSIGNMENT:
Assignment assignment= (Assignment) parent;
if (node.equals(assignment.getLeftHandSide())) {
// field write access: xx= expression
return assignment.getRightHandSide().resolveTypeBinding();
}
// read access
return assignment.getLeftHandSide().resolveTypeBinding();
case ASTNode.INFIX_EXPRESSION:
InfixExpression infix= (InfixExpression) parent;
if (node.equals(infix.getLeftOperand())) {
// xx == expression
return infix.getRightOperand().resolveTypeBinding();
}
// expression == xx
InfixExpression.Operator op= infix.getOperator();
if (op == InfixExpression.Operator.LEFT_SHIFT || op == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED
|| op == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) {
return infix.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
return infix.getLeftOperand().resolveTypeBinding();
case ASTNode.INSTANCEOF_EXPRESSION:
InstanceofExpression instanceofExpression= (InstanceofExpression) parent;
return instanceofExpression.getRightOperand().resolveBinding();
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
if (frag.getInitializer().equals(node)) {
ASTNode declaration= frag.getParent();
if (declaration instanceof VariableDeclarationStatement) {
return ((VariableDeclarationStatement)declaration).getType().resolveBinding();
} else if (declaration instanceof FieldDeclaration) {
return ((FieldDeclaration)declaration).getType().resolveBinding();
}
}
break;
case ASTNode.SUPER_METHOD_INVOCATION:
SuperMethodInvocation superMethodInvocation= (SuperMethodInvocation) parent;
IMethodBinding superMethodBinding= ASTNodes.getMethodBinding(superMethodInvocation.getName());
if (superMethodBinding != null) {
return getParameterTypeBinding(node, superMethodInvocation.arguments(), superMethodBinding);
}
break;
case ASTNode.METHOD_INVOCATION:
MethodInvocation methodInvocation= (MethodInvocation) parent;
IMethodBinding methodBinding= ASTNodes.getMethodBinding(methodInvocation.getName());
if (methodBinding != null) {
return getParameterTypeBinding(node, methodInvocation.arguments(), methodBinding);
}
break;
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
SuperConstructorInvocation superInvocation= (SuperConstructorInvocation) parent;
IMethodBinding superBinding= superInvocation.resolveConstructorBinding();
if (superBinding != null) {
return getParameterTypeBinding(node, superInvocation.arguments(), superBinding);
}
break;
case ASTNode.CONSTRUCTOR_INVOCATION:
ConstructorInvocation constrInvocation= (ConstructorInvocation) parent;
IMethodBinding constrBinding= constrInvocation.resolveConstructorBinding();
if (constrBinding != null) {
return getParameterTypeBinding(node, constrInvocation.arguments(), constrBinding);
}
break;
case ASTNode.CLASS_INSTANCE_CREATION:
ClassInstanceCreation creation= (ClassInstanceCreation) parent;
IMethodBinding creationBinding= creation.resolveConstructorBinding();
if (creationBinding != null) {
return getParameterTypeBinding(node, creation.arguments(), creationBinding);
}
break;
case ASTNode.PARENTHESIZED_EXPRESSION:
return guessBindingForReference(parent);
case ASTNode.ARRAY_ACCESS:
if (((ArrayAccess) parent).getIndex().equals(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
break;
case ASTNode.ARRAY_CREATION:
if (((ArrayCreation) parent).dimensions().contains(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
break;
case ASTNode.ARRAY_INITIALIZER:
ASTNode initializerParent= parent.getParent();
if (initializerParent instanceof ArrayCreation) {
return ((ArrayCreation) initializerParent).getType().getElementType().resolveBinding();
}
break;
case ASTNode.CONDITIONAL_EXPRESSION:
ConditionalExpression expression= (ConditionalExpression) parent;
if (node.equals(expression.getExpression())) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
if (node.equals(expression.getElseExpression())) {
return expression.getThenExpression().resolveTypeBinding();
}
return expression.getElseExpression().resolveTypeBinding();
case ASTNode.POSTFIX_EXPRESSION:
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
case ASTNode.PREFIX_EXPRESSION:
if (((PrefixExpression) parent).getOperator() == PrefixExpression.Operator.NOT) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
case ASTNode.IF_STATEMENT:
case ASTNode.WHILE_STATEMENT:
case ASTNode.DO_STATEMENT:
if (node instanceof Expression) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
break;
case ASTNode.SWITCH_STATEMENT:
if (((SwitchStatement) parent).getExpression().equals(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
break;
case ASTNode.RETURN_STATEMENT:
MethodDeclaration decl= findParentMethodDeclaration(parent);
if (decl != null) {
return decl.getReturnType().resolveBinding();
}
break;
case ASTNode.CAST_EXPRESSION:
return ((CastExpression) parent).getType().resolveBinding();
case ASTNode.THROW_STATEMENT:
case ASTNode.CATCH_CLAUSE:
return parent.getAST().resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
case ASTNode.FIELD_ACCESS:
if (node.equals(((FieldAccess) parent).getName())) {
return getPossibleReferenceBinding(parent);
}
break;
case ASTNode.QUALIFIED_NAME:
if (node.equals(((QualifiedName) parent).getName())) {
return getPossibleReferenceBinding(parent);
}
break;
}
return null;
}
private static ITypeBinding getParameterTypeBinding(ASTNode node, List args, IMethodBinding binding) {
ITypeBinding[] paramTypes= binding.getParameterTypes();
int index= args.indexOf(node);
if (index >= 0 && index < paramTypes.length) {
return paramTypes[index];
}
return null;
}
public static ITypeBinding guessBindingForTypeReference(ASTNode node) {
return normalizeTypeBinding(getPossibleTypeBinding(node));
}
private static ITypeBinding getPossibleTypeBinding(ASTNode node) {
ASTNode parent= node.getParent();
while (parent instanceof Type) {
parent= parent.getParent();
}
switch (parent.getNodeType()) {
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
return guessVariableType(((VariableDeclarationStatement) parent).fragments());
case ASTNode.FIELD_DECLARATION:
return guessVariableType(((FieldDeclaration) parent).fragments());
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
return guessVariableType(((VariableDeclarationExpression) parent).fragments());
case ASTNode.SINGLE_VARIABLE_DECLARATION:
SingleVariableDeclaration varDecl= (SingleVariableDeclaration) parent;
if (varDecl.getInitializer() != null) {
return varDecl.getInitializer().resolveTypeBinding();
}
break;
case ASTNode.ARRAY_CREATION:
ArrayCreation creation= (ArrayCreation) parent;
if (creation.getInitializer() != null) {
return creation.getInitializer().resolveTypeBinding();
}
return getPossibleReferenceBinding(parent);
case ASTNode.TYPE_LITERAL:
case ASTNode.CLASS_INSTANCE_CREATION:
return getPossibleReferenceBinding(parent);
}
return null;
}
private static ITypeBinding guessVariableType(List fragments) {
for (Iterator iter= fragments.iterator(); iter.hasNext();) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) iter.next();
if (frag.getInitializer() != null) {
return frag.getInitializer().resolveTypeBinding();
}
}
return null;
}
private static int getTypeOrder(Code type) {
if (type == PrimitiveType.BYTE) return 2;
if (type == PrimitiveType.CHAR) return 3;
if (type == PrimitiveType.SHORT) return 3;
if (type == PrimitiveType.INT) return 4;
if (type == PrimitiveType.LONG) return 5;
if (type == PrimitiveType.FLOAT) return 6;
if (type == PrimitiveType.DOUBLE) return 7;
return 0;
}
/**
* Tests if a two primitive types are assign compatible
* @param typeToAssign The binding of the type to assign
* @param definedType The type of the object that is assigned
* @return boolean Returns true if definedType = typeToAssign is true
*/
public static boolean canAssignPrimitive(Code toAssignCode, Code definedTypeCode) {
// definedTypeCode = typeCodeToAssign;
if (toAssignCode == definedTypeCode) {
return true;
}
if (definedTypeCode == PrimitiveType.BOOLEAN || toAssignCode == PrimitiveType.BOOLEAN) {
return false;
}
if (definedTypeCode == PrimitiveType.CHAR && toAssignCode == PrimitiveType.BYTE) {
return false;
}
return getTypeOrder(definedTypeCode) > getTypeOrder(toAssignCode);
}
/**
* Tests if a two types are assign compatible
* @param typeToAssign The binding of the type to assign
* @param definedType The type of the object that is assigned
* @return boolean Returns true if definedType = typeToAssign is true
*/
public static boolean canAssign(ITypeBinding typeToAssign, String definedType) {
// definedType = typeToAssign;
int arrStart= definedType.indexOf('[');
if (arrStart != -1) {
if (!typeToAssign.isArray()) {
return false; // can not assign a non-array type
}
int definedDim= definedType.length() - arrStart;
int toAssignDim= typeToAssign.getDimensions() * 2;
if (definedDim == toAssignDim) {
definedType= definedType.substring(0, arrStart);
typeToAssign= typeToAssign.getElementType();
if (typeToAssign.isPrimitive() && !definedType.equals(typeToAssign.getName())) {
return false; // can't assign arrays of primitive types to each other
}
return canAssign(typeToAssign, definedType);
} else if (definedDim < toAssignDim) {
return isArrayCompatible(definedType.substring(0, arrStart));
}
return false;
}
Code definedTypeCode= PrimitiveType.toCode(definedType);
if (typeToAssign.isPrimitive()) {
if (definedTypeCode == null) {
return false;
}
Code toAssignCode= PrimitiveType.toCode(typeToAssign.getName());
return canAssignPrimitive(toAssignCode, definedTypeCode);
} else {
if (definedTypeCode != null) {
return false;
}
if (typeToAssign.isArray()) {
return isArrayCompatible(definedType);
}
if ("java.lang.Object".equals(definedType)) { //$NON-NLS-1$
return true;
}
return (Bindings.findTypeInHierarchy(typeToAssign, definedType) != null);
}
}
/**
* Tests if a two types are assign compatible
* @param typeToAssign The binding of the type to assign
* @param definedType The type of the object that is assigned
* @return boolean Returns true if definedType = typeToAssign is true
*/
public static boolean canAssign(ITypeBinding typeToAssign, ITypeBinding definedType) {
// definedType = typeToAssign;
if (definedType.isArray()) {
if (!typeToAssign.isArray()) {
return false; // can not assign a non-array type to an array
}
int definedDim= definedType.getDimensions();
int toAssignDim= typeToAssign.getDimensions();
if (definedDim == toAssignDim) {
definedType= definedType.getElementType();
typeToAssign= typeToAssign.getElementType();
if (typeToAssign.isPrimitive() && typeToAssign != definedType) {
return false; // can't assign arrays of different primitive types to each other
}
// fall through
} else if (definedDim < toAssignDim) {
return isArrayCompatible(definedType.getElementType().getQualifiedName());
} else {
return false;
}
}
if (typeToAssign.isPrimitive()) {
if (!definedType.isPrimitive()) {
return false;
}
Code toAssignCode= PrimitiveType.toCode(typeToAssign.getName());
Code definedTypeCode= PrimitiveType.toCode(definedType.getName());
return canAssignPrimitive(toAssignCode, definedTypeCode);
} else {
if (definedType.isPrimitive()) {
return false;
}
String definedTypeName= definedType.getQualifiedName();
if (typeToAssign.isArray()) {
return isArrayCompatible(definedTypeName);
}
if ("java.lang.Object".equals(definedTypeName)) { //$NON-NLS-1$
return true;
}
return Bindings.isSuperType(definedType, typeToAssign);
}
}
private static boolean isArrayCompatible(String definedType) {
return "java.lang.Object".equals(definedType) || "java.io.Serializable".equals(definedType) || "java.lang.Cloneable".equals(definedType); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public static MethodDeclaration findParentMethodDeclaration(ASTNode node) {
while ((node != null) && (node.getNodeType() != ASTNode.METHOD_DECLARATION)) {
node= node.getParent();
}
return (MethodDeclaration) node;
}
public static BodyDeclaration findParentBodyDeclaration(ASTNode node) {
while ((node != null) && (!(node instanceof BodyDeclaration))) {
node= node.getParent();
}
return (BodyDeclaration) node;
}
public static CompilationUnit findParentCompilationUnit(ASTNode node) {
return (CompilationUnit) findAncestor(node, ASTNode.COMPILATION_UNIT);
}
/**
* Returns either a TypeDeclaration or an AnonymousTypeDeclaration
* @param node
* @return CompilationUnit
*/
public static ASTNode findParentType(ASTNode node) {
while ((node != null) && (node.getNodeType() != ASTNode.TYPE_DECLARATION) && (node.getNodeType() != ASTNode.ANONYMOUS_CLASS_DECLARATION)) {
node= node.getParent();
}
return node;
}
public static ASTNode findAncestor(ASTNode node, int nodeType) {
while ((node != null) && (node.getNodeType() != nodeType)) {
node= node.getParent();
}
return node;
}
/**
* Returns the type binding of the node's parent type declararation
* @param node
* @return CompilationUnit
*/
public static ITypeBinding getBindingOfParentType(ASTNode node) {
while (node != null) {
if (node instanceof TypeDeclaration) {
return ((TypeDeclaration) node).resolveBinding();
} else if (node instanceof AnonymousClassDeclaration) {
return ((AnonymousClassDeclaration) node).resolveBinding();
}
node= node.getParent();
}
return null;
}
public static Statement findParentStatement(ASTNode node) {
while ((node != null) && (!(node instanceof Statement))) {
node= node.getParent();
if (node instanceof BodyDeclaration) {
return null;
}
}
return (Statement) node;
}
public static TryStatement findParentTryStatement(ASTNode node) {
while ((node != null) && (!(node instanceof TryStatement))) {
node= node.getParent();
if (node instanceof BodyDeclaration) {
return null;
}
}
return (TryStatement) node;
}
public static boolean isInStaticContext(ASTNode selectedNode) {
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
return Modifier.isStatic(((MethodDeclaration)decl).getModifiers());
} else if (decl instanceof Initializer) {
return Modifier.isStatic(((Initializer)decl).getModifiers());
} else if (decl instanceof FieldDeclaration) {
return Modifier.isStatic(((FieldDeclaration)decl).getModifiers());
}
return false;
}
public static Type getTypeFromTypeBinding(AST ast, ITypeBinding binding) {
if (binding.isArray()) {
int dim= binding.getDimensions();
return ast.newArrayType(getTypeFromTypeBinding(ast, binding.getElementType()), dim);
} else if (binding.isPrimitive()) {
String name= binding.getName();
return ast.newPrimitiveType(PrimitiveType.toCode(name));
} else if (!binding.isNullType() && !binding.isAnonymous()) {
return ast.newSimpleType(ast.newSimpleName(binding.getName()));
}
return null;
}
public static Expression getInitExpression(Type type, int extraDimensions) {
if (extraDimensions == 0 && type.isPrimitiveType()) {
PrimitiveType primitiveType= (PrimitiveType) type;
if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) {
return type.getAST().newBooleanLiteral(false);
} else if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID) {
return null;
} else {
return type.getAST().newNumberLiteral("0"); //$NON-NLS-1$
}
}
return type.getAST().newNullLiteral();
}
public static Expression getInitExpression(AST ast, ITypeBinding type) {
if (type.isPrimitive()) {
String name= type.getName();
if ("boolean".equals(name)) { //$NON-NLS-1$
return ast.newBooleanLiteral(false);
} else if ("void".equals(name)) { //$NON-NLS-1$
return null;
} else {
return ast.newNumberLiteral("0"); //$NON-NLS-1$
}
}
return ast.newNullLiteral();
}
private static TypeDeclaration findTypeDeclaration(List decls, String name) {
for (Iterator iter= decls.iterator(); iter.hasNext();) {
ASTNode elem= (ASTNode) iter.next();
if (elem instanceof TypeDeclaration) {
TypeDeclaration decl= (TypeDeclaration) elem;
if (name.equals(decl.getName().getIdentifier())) {
return decl;
}
}
}
return null;
}
public static TypeDeclaration findTypeDeclaration(CompilationUnit root, ITypeBinding binding) {
ArrayList names= new ArrayList(5);
while (binding != null) {
names.add(binding.getName());
binding= binding.getDeclaringClass();
}
List types= root.types();
for (int i= names.size() - 1; i >= 0; i--) {
String name= (String) names.get(i);
TypeDeclaration decl= findTypeDeclaration(types, name);
if (decl == null || i == 0) {
return decl;
}
types= decl.bodyDeclarations();
}
return null;
}
public static String getFullName(Name name) {
return ASTNodes.asString(name);
}
public static String getQualifier(Name name) {
if (name.isQualifiedName()) {
return getFullName(((QualifiedName) name).getQualifier());
}
return ""; //$NON-NLS-1$
}
public static String getSimpleName(Name name) {
if (name.isQualifiedName()) {
return ((QualifiedName) name).getName().getIdentifier();
} else {
return ((SimpleName) name).getIdentifier();
}
}
public static ICompilationUnit findCompilationUnitForBinding(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding) throws JavaModelException {
if (binding != null && binding.isFromSource() && astRoot.findDeclaringNode(binding) == null) {
ICompilationUnit targetCU= Bindings.findCompilationUnit(binding, cu.getJavaProject());
if (targetCU != null) {
return JavaModelUtil.toWorkingCopy(targetCU);
}
return null;
}
return cu;
}
}
|
36,981 |
Bug 36981 call hierarchy: Search scope should be persisted
|
Search scope should be persisted when the platform shuts down or when the view is closed and reopened.
|
resolved fixed
|
63bbebc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T14:34:09Z | 2003-04-27T19:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.corext.callhierarchy.CallHierarchy;
import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
/**
* This is the main view for the callers plugin. It builds a tree of callers/callees
* and allows the user to double click an entry to go to the selected method.
*
*/
public class CallHierarchyViewPart extends ViewPart implements ICallHierarchyViewPart, IDoubleClickListener,
ISelectionChangedListener {
private CallHierarchyViewSiteAdapter fViewSiteAdapter;
private CallHierarchyViewAdapter fViewAdapter;
private static final String DIALOGSTORE_VIEWORIENTATION = "CallHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String DIALOGSTORE_CALL_MODE = "CallHierarchyViewPart.call_mode"; //$NON-NLS-1$
private static final String TAG_ORIENTATION = "orientation"; //$NON-NLS-1$
private static final String TAG_CALL_MODE = "call_mode"; //$NON-NLS-1$
private static final String TAG_IMPLEMENTORS_MODE = "implementors_mode"; //$NON-NLS-1$
private static final String TAG_RATIO = "ratio"; //$NON-NLS-1$
static final int VIEW_ORIENTATION_VERTICAL = 0;
static final int VIEW_ORIENTATION_HORIZONTAL = 1;
static final int VIEW_ORIENTATION_SINGLE = 2;
static final int CALL_MODE_CALLERS = 0;
static final int CALL_MODE_CALLEES = 1;
static final int IMPLEMENTORS_ENABLED = 0;
static final int IMPLEMENTORS_DISABLED = 1;
static final String GROUP_SEARCH_SCOPE = "MENU_SEARCH_SCOPE"; //$NON-NLS-1$
static final String ID_CALL_HIERARCHY = "org.eclipse.jdt.callhierarchy.view"; //$NON-NLS-1$
private static final String GROUP_FOCUS = "group.focus"; //$NON-NLS-1$
private static final int PAGE_EMPTY = 0;
private static final int PAGE_VIEWER = 1;
private Label fNoHierarchyShownLabel;
private PageBook fPagebook;
private IDialogSettings fDialogSettings;
private int fCurrentOrientation;
private int fCurrentCallMode;
private int fCurrentImplementorsMode;
private MethodWrapper fCalleeRoot;
private MethodWrapper fCallerRoot;
private IMemento fMemento;
private IMethod fShownMethod;
private SelectionProviderMediator fSelectionProviderMediator;
private List fMethodHistory;
private TableViewer fLocationViewer;
private Menu fLocationContextMenu;
private SashForm fHierarchyLocationSplitter;
private Clipboard fClipboard;
private SearchScopeActionGroup fSearchScopeActions;
private ToggleOrientationAction[] fToggleOrientationActions;
private ToggleCallModeAction[] fToggleCallModeActions;
private ToggleImplementorsAction[] fToggleImplementorsActions;
private CallHierarchyFiltersActionGroup fFiltersActionGroup;
private HistoryDropDownAction fHistoryDropDownAction;
private RefreshAction fRefreshAction;
private OpenLocationAction fOpenLocationAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private CopyCallHierarchyAction fCopyAction;
private CompositeActionGroup fActionGroups;
private CallHierarchyViewer fCallHierarchyViewer;
private boolean fShowCallDetails;
public CallHierarchyViewPart() {
super();
fDialogSettings = JavaPlugin.getDefault().getDialogSettings();
fMethodHistory = new ArrayList();
}
public void setFocus() {
fPagebook.setFocus();
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IMethod[] elems) {
fMethodHistory.clear();
for (int i = 0; i < elems.length; i++) {
fMethodHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Gets all history entries.
*/
public IMethod[] getHistoryEntries() {
if (fMethodHistory.size() > 0) {
updateHistoryEntries();
}
return (IMethod[]) fMethodHistory.toArray(new IMethod[fMethodHistory.size()]);
}
/**
* Method setMethod.
* @param method
*/
public void setMethod(IMethod method) {
if (method == null) {
showPage(PAGE_EMPTY);
return;
}
if ((method != null) && !method.equals(fShownMethod)) {
addHistoryEntry(method);
}
this.fShownMethod = method;
refresh();
}
public IMethod getMethod() {
return fShownMethod;
}
public MethodWrapper getCurrentMethodWrapper() {
if (fCurrentCallMode == CALL_MODE_CALLERS) {
return fCallerRoot;
} else {
return fCalleeRoot;
}
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
if ((fLocationViewer != null) && !fLocationViewer.getControl().isDisposed() &&
(fHierarchyLocationSplitter != null) &&
!fHierarchyLocationSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
setShowCallDetails(false);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
setShowCallDetails(true);
}
boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL;
fHierarchyLocationSplitter.setOrientation(horizontal ? SWT.HORIZONTAL
: SWT.VERTICAL);
}
fHierarchyLocationSplitter.layout();
}
for (int i = 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation = orientation;
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
/**
* called from ToggleCallModeAction.
* @param orientation CALL_MODE_CALLERS or CALL_MODE_CALLEES
*/
void setCallMode(int mode) {
if (fCurrentCallMode != mode) {
for (int i = 0; i < fToggleCallModeActions.length; i++) {
fToggleCallModeActions[i].setChecked(mode == fToggleCallModeActions[i].getMode());
}
fCurrentCallMode = mode;
fDialogSettings.put(DIALOGSTORE_CALL_MODE, mode);
updateView();
}
}
/**
* called from ToggleImplementorsAction.
* @param implementorsMode IMPLEMENTORS_USED or IMPLEMENTORS_NOT_USED
*/
void setImplementorsMode(int implementorsMode) {
if (fCurrentImplementorsMode != implementorsMode) {
for (int i = 0; i < fToggleImplementorsActions.length; i++) {
fToggleImplementorsActions[i].setChecked(implementorsMode == fToggleImplementorsActions[i].getImplementorsMode());
}
fCurrentImplementorsMode = implementorsMode;
CallHierarchy.getDefault().setSearchUsingImplementorsEnabled(implementorsMode == IMPLEMENTORS_ENABLED);
updateView();
}
}
public IJavaSearchScope getSearchScope() {
return fSearchScopeActions.getSearchScope();
}
public void setShowCallDetails(boolean show) {
fShowCallDetails = show;
showOrHideCallDetailsView();
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
addDragAdapters(fCallHierarchyViewer, ops, transfers);
addDropAdapters(fCallHierarchyViewer, ops | DND.DROP_DEFAULT, transfers);
addDropAdapters(fLocationViewer, ops | DND.DROP_DEFAULT, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new CallHierarchyTransferDropAdapter(this, fCallHierarchyViewer));
}
private void addDropAdapters(StructuredViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new CallHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) {
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(new SelectionProviderAdapter(viewer))
};
viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
}
public void createPartControl(Composite parent) {
fPagebook = new PageBook(parent, SWT.NONE);
// Page 1: Viewers
createHierarchyLocationSplitter(fPagebook);
createCallHierarchyViewer(fHierarchyLocationSplitter);
createLocationViewer(fHierarchyLocationSplitter);
// Page 2: Nothing selected
fNoHierarchyShownLabel = new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(CallHierarchyMessages.getString(
"CallHierarchyViewPart.empty")); //$NON-NLS-1$
showPage(PAGE_EMPTY);
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fSelectionProviderMediator = new SelectionProviderMediator(new Viewer[] {
fCallHierarchyViewer, fLocationViewer
});
IStatusLineManager slManager = getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(
slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
fClipboard= new Clipboard(parent.getDisplay());
makeActions();
fillViewMenu();
fillActionBars();
initOrientation();
initCallMode();
initImplementorsMode();
if (fMemento != null) {
restoreState(fMemento);
}
initDragAndDrop();
}
/**
* @param PAGE_EMPTY
*/
private void showPage(int page) {
if (page == PAGE_EMPTY) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
fPagebook.showPage(fHierarchyLocationSplitter);
}
enableActions(page != PAGE_EMPTY);
}
/**
* @param b
*/
private void enableActions(boolean enabled) {
fLocationContextMenu.setEnabled(enabled);
// TODO: Is it possible to disable the actions on the toolbar and on the view menu?
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento) {
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer callMode= memento.getInteger(TAG_CALL_MODE);
if (callMode != null) {
setCallMode(callMode.intValue());
}
Integer implementorsMode= memento.getInteger(TAG_IMPLEMENTORS_MODE);
if (implementorsMode != null) {
setImplementorsMode(implementorsMode.intValue());
}
Integer ratio = memento.getInteger(TAG_RATIO);
if (ratio != null) {
fHierarchyLocationSplitter.setWeights(new int[] {
ratio.intValue(), 1000 - ratio.intValue()
});
}
}
private void initCallMode() {
int mode;
try {
mode = fDialogSettings.getInt(DIALOGSTORE_CALL_MODE);
if ((mode < 0) || (mode > 1)) {
mode = CALL_MODE_CALLERS;
}
} catch (NumberFormatException e) {
mode = CALL_MODE_CALLERS;
}
// force the update
fCurrentCallMode = -1;
// will fill the main tool bar
setCallMode(mode);
}
private void initImplementorsMode() {
int mode;
mode= CallHierarchy.getDefault().isSearchUsingImplementorsEnabled() ? IMPLEMENTORS_ENABLED : IMPLEMENTORS_DISABLED;
fCurrentImplementorsMode= -1;
// will fill the main tool bar
setImplementorsMode(mode);
}
private void initOrientation() {
int orientation;
try {
orientation = fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if ((orientation < 0) || (orientation > 2)) {
orientation = VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation = VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation = -1;
// will fill the main tool bar
setOrientation(orientation);
}
private void fillViewMenu() {
IActionBars actionBars = getViewSite().getActionBars();
IMenuManager viewMenu = actionBars.getMenuManager();
viewMenu.add(new Separator());
for (int i = 0; i < fToggleCallModeActions.length; i++) {
viewMenu.add(fToggleCallModeActions[i]);
}
viewMenu.add(new Separator());
// TODO: Should be reenabled if this toggle should actually be used
// for (int i = 0; i < fToggleImplementorsActions.length; i++) {
// viewMenu.add(fToggleImplementorsActions[i]);
// }
//
// viewMenu.add(new Separator());
for (int i = 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
}
/**
*
*/
public void dispose() {
disposeMenu(fLocationContextMenu);
if (fActionGroups != null)
fActionGroups.dispose();
if (fClipboard != null)
fClipboard.dispose();
super.dispose();
}
/**
* Double click listener which jumps to the method in the source code.
*
* @return IDoubleClickListener
*/
public void doubleClick(DoubleClickEvent event) {
jumpToSelection(event.getSelection());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IMethod entry) {
if (fMethodHistory.contains(entry)) {
setMethod(entry);
}
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento)
throws PartInitException {
super.init(site, memento);
fMemento = memento;
}
public void jumpToDeclarationOfSelection() {
ISelection selection = null;
selection = getSelection();
if ((selection != null) && selection instanceof IStructuredSelection) {
Object structuredSelection = ((IStructuredSelection) selection).getFirstElement();
if (structuredSelection instanceof IMember) {
CallHierarchyUI.jumpToMember((IMember) structuredSelection);
} else if (structuredSelection instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) structuredSelection;
CallHierarchyUI.jumpToMember(methodWrapper.getMember());
} else if (structuredSelection instanceof CallLocation) {
CallHierarchyUI.jumpToMember(((CallLocation) structuredSelection).getCalledMember());
}
}
}
public void jumpToSelection(ISelection selection) {
if ((selection != null) && selection instanceof IStructuredSelection) {
Object structuredSelection = ((IStructuredSelection) selection).getFirstElement();
if (structuredSelection instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) structuredSelection;
CallLocation firstCall = methodWrapper.getMethodCall()
.getFirstCallLocation();
if (firstCall != null) {
CallHierarchyUI.jumpToLocation(firstCall);
} else {
CallHierarchyUI.jumpToMember(methodWrapper.getMember());
}
} else if (structuredSelection instanceof CallLocation) {
CallHierarchyUI.jumpToLocation((CallLocation) structuredSelection);
}
}
}
/**
*
*/
public void refresh() {
setCalleeRoot(null);
setCallerRoot(null);
updateView();
}
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
memento.putInteger(TAG_CALL_MODE, fCurrentCallMode);
memento.putInteger(TAG_IMPLEMENTORS_MODE, fCurrentImplementorsMode);
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int[] weigths = fHierarchyLocationSplitter.getWeights();
int ratio = (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
}
/**
* @return ISelectionChangedListener
*/
public void selectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fCallHierarchyViewer) {
methodSelectionChanged(e.getSelection());
}
}
/**
* @param selection
*/
private void methodSelectionChanged(ISelection selection) {
if (selection instanceof IStructuredSelection) {
Object selectedElement = ((IStructuredSelection) selection).getFirstElement();
if (selectedElement instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) selectedElement;
revealElementInEditor(methodWrapper, fCallHierarchyViewer);
updateLocationsView(methodWrapper);
} else {
updateLocationsView(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
if (elem instanceof MethodWrapper) {
CallLocation callLocation = CallHierarchy.getCallLocation(elem);
if (callLocation != null) {
IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(callLocation);
if (editorPart != null) {
getSite().getPage().bringToTop(editorPart);
if (editorPart instanceof ITextEditor) {
ITextEditor editor = (ITextEditor) editorPart;
editor.selectAndReveal(callLocation.getStart(),
(callLocation.getEnd() - callLocation.getStart()));
}
}
} else {
IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(elem);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart,
((MethodWrapper) elem).getMember());
}
} else if (elem instanceof IJavaElement) {
IEditorPart editorPart = EditorUtility.isOpenInEditor(elem);
if (editorPart != null) {
// getSite().getPage().removePartListener(fPartListener);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
// getSite().getPage().addPartListener(fPartListener);
}
}
}
/**
* Returns the current selection.
*/
protected ISelection getSelection() {
return getSite().getSelectionProvider().getSelection();
}
protected void fillContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
}
protected void handleKeyEvent(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
if ((fRefreshAction != null) && fRefreshAction.isEnabled()) {
fRefreshAction.run();
return;
}
}
}
}
private IActionBars getActionBars() {
return getViewSite().getActionBars();
}
private void setCalleeRoot(MethodWrapper calleeRoot) {
this.fCalleeRoot = calleeRoot;
}
private MethodWrapper getCalleeRoot() {
if (fCalleeRoot == null) {
fCalleeRoot = (MethodWrapper) CallHierarchy.getDefault().getCalleeRoot(fShownMethod);
}
return fCalleeRoot;
}
private void setCallerRoot(MethodWrapper callerRoot) {
this.fCallerRoot = callerRoot;
}
private MethodWrapper getCallerRoot() {
if (fCallerRoot == null) {
fCallerRoot = (MethodWrapper) CallHierarchy.getDefault().getCallerRoot(fShownMethod);
}
return fCallerRoot;
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fMethodHistory.contains(entry)) {
fMethodHistory.remove(entry);
}
fMethodHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
}
/**
* @param parent
*/
private void createLocationViewer(Composite parent) {
fLocationViewer = new TableViewer(parent, SWT.NONE);
fLocationViewer.setContentProvider(new ArrayContentProvider());
fLocationViewer.setLabelProvider(new LocationLabelProvider());
fLocationViewer.setInput(new ArrayList());
fLocationViewer.getControl().addKeyListener(createKeyListener());
JavaUIHelp.setHelp(fLocationViewer, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fOpenLocationAction = new OpenLocationAction(getSite());
fLocationViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fOpenLocationAction.run();
}
});
// fListViewer.addDoubleClickListener(this);
MenuManager menuMgr = new MenuManager(); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
/* (non-Javadoc)
* @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
public void menuAboutToShow(IMenuManager manager) {
fillContextMenu(manager);
}
});
fLocationContextMenu = menuMgr.createContextMenu(fLocationViewer.getControl());
fLocationViewer.getControl().setMenu(fLocationContextMenu);
// Register viewer with site. This must be done before making the actions.
getSite().registerContextMenu(menuMgr, fLocationViewer);
}
private void createHierarchyLocationSplitter(Composite parent) {
fHierarchyLocationSplitter = new SashForm(parent, SWT.NONE);
fHierarchyLocationSplitter.addKeyListener(createKeyListener());
}
private void createCallHierarchyViewer(Composite parent) {
fCallHierarchyViewer = new CallHierarchyViewer(parent, this);
fCallHierarchyViewer.addKeyListener(createKeyListener());
fCallHierarchyViewer.addSelectionChangedListener(this);
fCallHierarchyViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillCallHierarchyViewerContextMenu(menu);
}
}, ID_CALL_HIERARCHY, getSite());
}
/**
* @param fCallHierarchyViewer
* @param menu
*/
protected void fillCallHierarchyViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
if (fFocusOnSelectionAction.canActionBeAdded()) {
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
}
menu.appendToGroup(GROUP_FOCUS, fCopyAction);
fActionGroups.setContext(new ActionContext(getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
private void disposeMenu(Menu contextMenu) {
if ((contextMenu != null) && !contextMenu.isDisposed()) {
contextMenu.dispose();
}
}
private void fillActionBars() {
IActionBars actionBars = getActionBars();
IToolBarManager toolBar = actionBars.getToolBarManager();
fActionGroups.fillActionBars(actionBars);
toolBar.add(fHistoryDropDownAction);
for (int i = 0; i < fToggleCallModeActions.length; i++) {
toolBar.add(fToggleCallModeActions[i]);
}
}
private KeyListener createKeyListener() {
KeyListener keyListener = new KeyAdapter() {
public void keyReleased(KeyEvent event) {
handleKeyEvent(event);
}
};
return keyListener;
}
/**
*
*/
private void makeActions() {
fRefreshAction = new RefreshAction(this);
fFocusOnSelectionAction = new FocusOnSelectionAction(this);
fCopyAction= new CopyCallHierarchyAction(this, fClipboard, fCallHierarchyViewer);
fSearchScopeActions = new SearchScopeActionGroup(this);
fFiltersActionGroup = new CallHierarchyFiltersActionGroup(this,
fCallHierarchyViewer);
fHistoryDropDownAction = new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions = new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fToggleCallModeActions = new ToggleCallModeAction[] {
new ToggleCallModeAction(this, CALL_MODE_CALLERS),
new ToggleCallModeAction(this, CALL_MODE_CALLEES)
};
fToggleImplementorsActions = new ToggleImplementorsAction[] {
new ToggleImplementorsAction(this, IMPLEMENTORS_ENABLED),
new ToggleImplementorsAction(this, IMPLEMENTORS_DISABLED)
};
fActionGroups = new CompositeActionGroup(new ActionGroup[] {
new OpenEditorActionGroup(getViewAdapter()),
new OpenViewActionGroup(getViewAdapter()),
new CCPActionGroup(getViewAdapter()),
new GenerateActionGroup(getViewAdapter()),
new RefactorActionGroup(getViewAdapter()),
new JavaSearchActionGroup(getViewAdapter()),
fSearchScopeActions, fFiltersActionGroup
});
}
private CallHierarchyViewAdapter getViewAdapter() {
if (fViewAdapter == null) {
fViewAdapter= new CallHierarchyViewAdapter(getViewSiteAdapter());
}
return fViewAdapter;
}
private CallHierarchyViewSiteAdapter getViewSiteAdapter() {
if (fViewSiteAdapter == null) {
fViewSiteAdapter= new CallHierarchyViewSiteAdapter(this.getViewSite());
}
return fViewSiteAdapter;
}
private void showOrHideCallDetailsView() {
if (fShowCallDetails) {
fHierarchyLocationSplitter.setMaximizedControl(null);
} else {
fHierarchyLocationSplitter.setMaximizedControl(fCallHierarchyViewer.getControl());
}
}
private void updateLocationsView(MethodWrapper methodWrapper) {
if (methodWrapper != null) {
fLocationViewer.setInput(methodWrapper.getMethodCall().getCallLocations());
} else {
fLocationViewer.setInput(""); //$NON-NLS-1$
}
}
private void updateHistoryEntries() {
for (int i = fMethodHistory.size() - 1; i >= 0; i--) {
IMethod method = (IMethod) fMethodHistory.get(i);
if (!method.exists()) {
fMethodHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
}
/**
* Method updateView.
*/
private void updateView() {
if ((fShownMethod != null)) {
showPage(PAGE_VIEWER);
CallHierarchy.getDefault().setSearchScope(getSearchScope());
if (fCurrentCallMode == CALL_MODE_CALLERS) {
setTitle(CallHierarchyMessages.getString("CallHierarchyViewPart.callsToMethod")); //$NON-NLS-1$
fCallHierarchyViewer.setMethodWrapper(getCallerRoot());
} else {
setTitle(CallHierarchyMessages.getString("CallHierarchyViewPart.callsFromMethod")); //$NON-NLS-1$
fCallHierarchyViewer.setMethodWrapper(getCalleeRoot());
}
updateLocationsView(null);
}
}
static CallHierarchyViewPart findAndShowCallersView(IWorkbenchPartSite site) {
IWorkbenchPage workbenchPage = site.getPage();
CallHierarchyViewPart callersView = null;
try {
callersView = (CallHierarchyViewPart) workbenchPage.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
return callersView;
}
}
|
36,981 |
Bug 36981 call hierarchy: Search scope should be persisted
|
Search scope should be persisted when the platform shuts down or when the view is closed and reopened.
|
resolved fixed
|
63bbebc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T14:34:09Z | 2003-04-27T19:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/SearchScopeActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
class SearchScopeActionGroup extends ActionGroup {
private SearchScopeAction fSelectedAction = null;
private String fSelectedWorkingSetName = null;
private CallHierarchyViewPart fView;
private SearchScopeHierarchyAction fSearchScopeHierarchyAction;
private SearchScopeProjectAction fSearchScopeProjectAction;
private SearchScopeWorkspaceAction fSearchScopeWorkspaceAction;
private SelectWorkingSetAction fSelectWorkingSetAction;
private abstract class SearchScopeAction extends Action {
public SearchScopeAction(String text) {
super(text);
}
public abstract IJavaSearchScope getSearchScope();
public void run() {
setSelected(this);
}
}
private class SearchScopeHierarchyAction extends SearchScopeAction {
public SearchScopeHierarchyAction() {
super(CallHierarchyMessages.getString("SearchScopeActionGroup.hierarchy.text")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("SearchScopeActionGroup.hierarchy.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
}
public IJavaSearchScope getSearchScope() {
try {
IMethod method = getView().getMethod();
if (method != null) {
return SearchEngine.createHierarchyScope(method.getDeclaringType());
} else {
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
}
private class SearchScopeProjectAction extends SearchScopeAction {
public SearchScopeProjectAction() {
super(CallHierarchyMessages.getString("SearchScopeActionGroup.project.text")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("SearchScopeActionGroup.project.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
}
public IJavaSearchScope getSearchScope() {
IMethod method = getView().getMethod();
IJavaProject project = null;
if (method != null) {
project = method.getJavaProject();
}
if (project != null) {
return SearchEngine.createJavaSearchScope(new IJavaElement[] { project },
false);
} else {
return null;
}
}
}
private class SearchScopeWorkingSetAction extends SearchScopeAction {
private IWorkingSet mWorkingSet;
public SearchScopeWorkingSetAction(IWorkingSet workingSet) {
super(workingSet.getName());
setToolTipText(CallHierarchyMessages.getString("SearchScopeActionGroup.workingset.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
this.mWorkingSet = workingSet;
}
public IJavaSearchScope getSearchScope() {
return SearchEngine.createJavaSearchScope(getJavaElements(
mWorkingSet.getElements()));
}
/**
*
*/
public IWorkingSet getWorkingSet() {
return mWorkingSet;
}
/**
* @param adaptables
* @return IResource[]
*/
private IJavaElement[] getJavaElements(IAdaptable[] adaptables) {
Collection result = new ArrayList();
for (int i = 0; i < adaptables.length; i++) {
IJavaElement element = (IJavaElement) adaptables[i].getAdapter(IJavaElement.class);
if (element != null) {
result.add(element);
}
}
return (IJavaElement[]) result.toArray(new IJavaElement[result.size()]);
}
}
private class SearchScopeWorkspaceAction extends SearchScopeAction {
public SearchScopeWorkspaceAction() {
super(CallHierarchyMessages.getString("SearchScopeActionGroup.workspace.text")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("SearchScopeActionGroup.workspace.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
}
public IJavaSearchScope getSearchScope() {
return SearchEngine.createWorkspaceScope();
}
}
private class SelectWorkingSetAction extends Action {
public SelectWorkingSetAction() {
super(CallHierarchyMessages.getString("SearchScopeActionGroup.workingset.select.text")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("SearchScopeActionGroup.workingset.select.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
IWorkingSetManager workingSetManager = getWorkingSetManager();
IWorkingSetSelectionDialog dialog = workingSetManager.createWorkingSetSelectionDialog(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(),
false);
IWorkingSet workingSet = getActiveWorkingSet();
if (workingSet != null) {
dialog.setSelection(new IWorkingSet[] { workingSet });
}
if (dialog.open() == Window.OK) {
IWorkingSet[] result = dialog.getSelection();
if ((result != null) && (result.length > 0)) {
setActiveWorkingSet(result[0]);
workingSetManager.addRecentWorkingSet(result[0]);
} else {
setActiveWorkingSet(null);
}
}
}
}
public SearchScopeActionGroup(CallHierarchyViewPart view) {
this.fView = view;
createActions();
}
/**
* @return IJavaSearchScope
*/
public IJavaSearchScope getSearchScope() {
if (fSelectedAction != null) {
return fSelectedAction.getSearchScope();
}
return null;
}
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
fillViewMenu(actionBars.getMenuManager());
}
public void fillContextMenu(IMenuManager menu) {
}
/**
* @param set
* @param b
*/
protected void setActiveWorkingSet(IWorkingSet set) {
if (set != null) {
fSelectedWorkingSetName = set.getName();
fSelectedAction = new SearchScopeWorkingSetAction(set);
} else {
fSelectedWorkingSetName = null;
fSelectedAction = null;
}
}
/**
* @return
*/
protected IWorkingSet getActiveWorkingSet() {
if (fSelectedWorkingSetName != null) {
return getWorkingSetManager().getWorkingSet(fSelectedWorkingSetName);
}
return null;
}
protected void setSelected(SearchScopeAction newSelection) {
if (newSelection instanceof SearchScopeWorkingSetAction) {
fSelectedWorkingSetName = ((SearchScopeWorkingSetAction) newSelection).getWorkingSet()
.getName();
} else {
fSelectedWorkingSetName = null;
}
fSelectedAction = newSelection;
}
/**
* @return CallHierarchyViewPart
*/
protected CallHierarchyViewPart getView() {
return fView;
}
protected IWorkingSetManager getWorkingSetManager() {
IWorkingSetManager workingSetManager = PlatformUI.getWorkbench()
.getWorkingSetManager();
return workingSetManager;
}
protected void fillSearchActions(IMenuManager javaSearchMM) {
javaSearchMM.removeAll();
Action[] actions = getActions();
for (int i = 0; i < actions.length; i++) {
Action action = actions[i];
if (action.isEnabled()) {
javaSearchMM.add(action);
}
}
javaSearchMM.setVisible(!javaSearchMM.isEmpty());
}
void fillViewMenu(IMenuManager menu) {
menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
MenuManager javaSearchMM = new MenuManager(CallHierarchyMessages.getString("SearchScopeActionGroup.searchScope"), //$NON-NLS-1$
IContextMenuConstants.GROUP_SEARCH);
javaSearchMM.addMenuListener(new IMenuListener() {
/* (non-Javadoc)
* @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
public void menuAboutToShow(IMenuManager manager) {
fillSearchActions(manager);
}
});
menu.appendToGroup(IContextMenuConstants.GROUP_SEARCH, javaSearchMM);
}
/**
* @return SearchScopeAction[]
*/
private Action[] getActions() {
List actions = new ArrayList();
addAction(actions, fSearchScopeWorkspaceAction);
addAction(actions, fSearchScopeProjectAction);
addAction(actions, fSearchScopeHierarchyAction);
addAction(actions, fSelectWorkingSetAction);
IWorkingSetManager workingSetManager = PlatformUI.getWorkbench()
.getWorkingSetManager();
IWorkingSet[] sets = workingSetManager.getRecentWorkingSets();
for (int i = 0; i < sets.length; i++) {
SearchScopeWorkingSetAction workingSetAction = new SearchScopeWorkingSetAction(sets[i]);
if (sets[i].getName().equals(fSelectedWorkingSetName)) {
workingSetAction.setChecked(true);
}
actions.add(workingSetAction);
}
return (Action[]) actions.toArray(new Action[actions.size()]);
}
private void addAction(List actions, Action action) {
if (action == fSelectedAction) {
action.setChecked(true);
} else {
action.setChecked(false);
}
actions.add(action);
}
/**
* @param view
*/
private void createActions() {
fSearchScopeWorkspaceAction = new SearchScopeWorkspaceAction();
fSelectWorkingSetAction = new SelectWorkingSetAction();
fSearchScopeHierarchyAction = new SearchScopeHierarchyAction();
fSearchScopeProjectAction = new SearchScopeProjectAction();
setSelected(fSearchScopeWorkspaceAction);
}
}
|
36,481 |
Bug 36481 Quickfix (create method) generates wrong parameter type if same name exists in other package [quick fix]
|
given two types with same name, package a; public class A { } package b; public class A { public void doSomething(a.A obj) { newMethod(obj); // this should be quickfixed } } the generated method has the signature private void newMethod(A obj), but should have private void newMethod(a.A obj). I admit this to be not the classic style, we experience this behaviour, because we are generating lots of code and all the generated code goes to one directory, making calls to handwritten code with the same type name (by convention) in other packages.
|
resolved fixed
|
678e41d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T20:47:40Z | 2003-04-15T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AssignToVariableAssistProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.NamingConventions;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.IPackageBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.textmanipulation.GroupDescription;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.corext.textmanipulation.TextRange;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class AssignToVariableAssistProposal extends ASTRewriteCorrectionProposal {
public static final int LOCAL= 1;
public static final int FIELD= 2;
private int fVariableKind;
private ExpressionStatement fExpressionStatement;
private ITypeBinding fTypeBinding;
public AssignToVariableAssistProposal(ICompilationUnit cu, int variableKind, ExpressionStatement node, ITypeBinding typeBinding, int relevance) {
super(null, cu, null, relevance, null);
fVariableKind= variableKind;
fExpressionStatement= node;
fTypeBinding= typeBinding;
if (variableKind == LOCAL) {
setDisplayName(CorrectionMessages.getString("AssignToVariableAssistProposal.assigntolocal.description")); //$NON-NLS-1$
setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL));
} else {
setDisplayName(CorrectionMessages.getString("AssignToVariableAssistProposal.assigntofield.description")); //$NON-NLS-1$
setImage(JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE));
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#createCompilationUnitChange(java.lang.String, org.eclipse.jdt.core.ICompilationUnit, org.eclipse.jdt.internal.corext.textmanipulation.TextEdit)
*/
protected CompilationUnitChange createCompilationUnitChange(String name, ICompilationUnit cu, TextEdit rootEdit) throws CoreException {
CompilationUnitChange change= super.createCompilationUnitChange(name, cu, rootEdit);
change.setKeepExecutedTextEdits(true);
return change;
}
protected ASTRewrite getRewrite() throws CoreException {
if (fVariableKind == FIELD) {
return doAddField();
} else { // LOCAL
return doAddLocal();
}
}
private ASTRewrite doAddLocal() throws CoreException {
Expression expression= fExpressionStatement.getExpression();
ASTRewrite rewrite= new ASTRewrite(fExpressionStatement.getParent());
AST ast= fExpressionStatement.getAST();
String varName= suggestLocalVariableNames(fTypeBinding);
VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
newDeclFrag.setName(ast.newSimpleName(varName));
newDeclFrag.setInitializer((Expression) rewrite.createCopy(expression));
VariableDeclarationStatement newDecl= ast.newVariableDeclarationStatement(newDeclFrag);
newDecl.setType(ASTResolving.getTypeFromTypeBinding(ast, fTypeBinding));
rewrite.markAsReplaced(fExpressionStatement, newDecl, "ID"); //$NON-NLS-1$
addImport(fTypeBinding);
return rewrite;
}
private ASTRewrite doAddField() throws CoreException {
ASTNode newTypeDecl= ASTResolving.findParentType(fExpressionStatement);
Expression expression= fExpressionStatement.getExpression();
boolean isAnonymous= newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
List decls= isAnonymous ? ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations() : ((TypeDeclaration) newTypeDecl).bodyDeclarations();
ASTRewrite rewrite= new ASTRewrite(newTypeDecl);
AST ast= fExpressionStatement.getAST();
String varName= suggestFieldNames(fTypeBinding);
VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
newDeclFrag.setName(ast.newSimpleName(varName));
FieldDeclaration newDecl= ast.newFieldDeclaration(newDeclFrag);
newDecl.setType(ASTResolving.getTypeFromTypeBinding(ast, fTypeBinding));
newDecl.setModifiers(Modifier.PRIVATE);
Assignment assignment= ast.newAssignment();
assignment.setLeftHandSide(ast.newSimpleName(varName));
assignment.setRightHandSide((Expression) rewrite.createCopy(expression));
rewrite.markAsReplaced(expression, assignment, "ID"); //$NON-NLS-1$
decls.add(findInsertIndex(decls, fExpressionStatement.getStartPosition()), newDecl);
addImport(fTypeBinding);
rewrite.markAsInserted(newDecl);
return rewrite;
}
private String suggestLocalVariableNames(ITypeBinding binding) {
IJavaProject project= getCompilationUnit().getJavaProject();
ITypeBinding base= binding.isArray() ? binding.getElementType() : binding;
IPackageBinding packBinding= base.getPackage();
String packName= packBinding != null ? packBinding.getName() : ""; //$NON-NLS-1$
String[] excludedNames= new String[0];
String typeName= base.getName();
String[] names= NamingConventions.suggestLocalVariableNames(project, packName, typeName, binding.getDimensions(), excludedNames);
if (names.length == 0) {
return "class1"; // fix for pr, remoev after 20030127 //$NON-NLS-1$
}
return names[0];
}
private String suggestFieldNames(ITypeBinding binding) {
IJavaProject project= getCompilationUnit().getJavaProject();
ITypeBinding base= binding.isArray() ? binding.getElementType() : binding;
IPackageBinding packBinding= base.getPackage();
String packName= packBinding != null ? packBinding.getName() : ""; //$NON-NLS-1$
String[] excludedNames= new String[0];
String typeName= base.getName();
String[] names= NamingConventions.suggestFieldNames(project, packName, typeName, binding.getDimensions(), binding.getModifiers(), excludedNames);
if (names.length == 0) {
return "class1"; // fix for pr, remoev after 20030127 //$NON-NLS-1$
}
return names[0];
}
private int findInsertIndex(List decls, int currPos) {
for (int i= decls.size() - 1; i >= 0; i--) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof FieldDeclaration && currPos > curr.getStartPosition() + curr.getLength()) {
return i + 1;
}
}
return 0;
}
/**
* Returns the variable kind.
* @return int
*/
public int getVariableKind() {
return fVariableKind;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection(org.eclipse.jface.text.IDocument)
*/
public Point getSelection(IDocument document) {
try {
CompilationUnitChange change= getCompilationUnitChange();
GroupDescription[] desc= change.getGroupDescriptions();
TextRange range= change.getNewTextRange(desc[0].getTextEdits());
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
scanner.setSource(document.get(range.getOffset(), range.getLength()).toCharArray());
Point res= new Point(0, 0);
int tok= scanner.getNextToken();
while (tok != ITerminalSymbols.TokenNameEOF) {
res.x= scanner.getCurrentTokenStartPosition() + range.getOffset();
res.y= scanner.getCurrentTokenEndPosition() - scanner.getCurrentTokenStartPosition() + 1;
tok= scanner.getNextToken();
if (tok == ITerminalSymbols.TokenNameEQUAL) {
return res;
}
}
} catch (CoreException e) {
// can't happen (change already exists at this point)
} catch (InvalidInputException e) {
// ignore
} catch (BadLocationException e) {
// ignore
}
return null;
}
}
|
36,481 |
Bug 36481 Quickfix (create method) generates wrong parameter type if same name exists in other package [quick fix]
|
given two types with same name, package a; public class A { } package b; public class A { public void doSomething(a.A obj) { newMethod(obj); // this should be quickfixed } } the generated method has the signature private void newMethod(A obj), but should have private void newMethod(a.A obj). I admit this to be not the classic style, we experience this behaviour, because we are generating lots of code and all the generated code goes to one directory, making calls to handwritten code with the same type name (by convention) in other packages.
|
resolved fixed
|
678e41d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T20:47:40Z | 2003-04-15T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ConstructorFromSuperclassProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.Javadoc;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
public class ConstructorFromSuperclassProposal extends ASTRewriteCorrectionProposal {
private TypeDeclaration fTypeNode;
private IMethodBinding fSuperConstructor;
public ConstructorFromSuperclassProposal(ICompilationUnit cu, TypeDeclaration typeNode, IMethodBinding superConstructor, int relevance) {
super(null, cu, null, relevance, null);
fTypeNode= typeNode;
fSuperConstructor= superConstructor;
}
/**
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
*/
public Image getImage() {
return JavaPlugin.getImageDescriptorRegistry().get(
new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE)
);
}
/**
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
StringBuffer buf= new StringBuffer();
buf.append(fTypeNode.getName().getIdentifier());
buf.append('(');
if (fSuperConstructor != null) {
ITypeBinding[] paramTypes= fSuperConstructor.getParameterTypes();
for (int i= 0; i < paramTypes.length; i++) {
if (i > 0) {
buf.append(',');
}
buf.append(paramTypes[i].getName());
}
}
buf.append(')');
return CorrectionMessages.getFormattedString("ConstructorFromSuperclassProposal.description", buf.toString()); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
*/
protected ASTRewrite getRewrite() throws CoreException {
ASTRewrite rewrite= new ASTRewrite(fTypeNode);
AST ast= fTypeNode.getAST();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (!settings.createComments) {
settings= null;
}
MethodDeclaration newMethodDecl= createNewMethodDeclaration(ast, fSuperConstructor, rewrite, settings);
rewrite.markAsInserted(newMethodDecl);
fTypeNode.bodyDeclarations().add(0, newMethodDecl);
return rewrite;
}
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, CodeGenerationSettings commentSettings) throws CoreException {
String name= fTypeNode.getName().getIdentifier();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setConstructor(true);
decl.setName(ast.newSimpleName(name));
Block body= ast.newBlock();
decl.setBody(body);
String bodyStatement= ""; //$NON-NLS-1$
if (binding == null) {
decl.setModifiers(Modifier.PUBLIC);
} else {
decl.setModifiers(binding.getModifiers());
List parameters= decl.parameters();
ITypeBinding[] params= binding.getParameterTypes();
String[] paramNames= getArgumentNames(binding);
for (int i= 0; i < params.length; i++) {
ITypeBinding curr= params[i];
addImport(curr);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setType(ASTResolving.getTypeFromTypeBinding(ast, curr));
var.setName(ast.newSimpleName(paramNames[i]));
parameters.add(var);
}
List thrownExceptions= decl.thrownExceptions();
ITypeBinding[] excTypes= binding.getExceptionTypes();
for (int i= 0; i < excTypes.length; i++) {
ITypeBinding curr= excTypes[i];
addImport(curr);
thrownExceptions.add(ast.newSimpleName(curr.getName())); // can only be single type, no array
}
SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
List arguments= invocation.arguments();
for (int i= 0; i < paramNames.length; i++) {
arguments.add(ast.newSimpleName(paramNames[i]));
}
bodyStatement= ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'));
}
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT);
body.statements().add(todoNode);
}
if (commentSettings != null) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private String[] getArgumentNames(IMethodBinding binding) {
int nParams= binding.getParameterTypes().length;
if (nParams > 0) {
try {
IMethod method= Bindings.findMethod(binding, getCompilationUnit().getJavaProject());
if (method != null) {
return method.getParameterNames();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
String[] names= new String[nParams];
for (int i= 0; i < names.length; i++) {
names[i]= "arg" + i; //$NON-NLS-1$
}
return names;
}
}
|
36,481 |
Bug 36481 Quickfix (create method) generates wrong parameter type if same name exists in other package [quick fix]
|
given two types with same name, package a; public class A { } package b; public class A { public void doSomething(a.A obj) { newMethod(obj); // this should be quickfixed } } the generated method has the signature private void newMethod(A obj), but should have private void newMethod(a.A obj). I admit this to be not the classic style, we experience this behaviour, because we are generating lots of code and all the generated code goes to one directory, making calls to handwritten code with the same type name (by convention) in other packages.
|
resolved fixed
|
678e41d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T20:47:40Z | 2003-04-15T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - Access to static proposal
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.ISharedImages;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.PrimitiveType.Code;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Selection;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil;
import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
/**
*/
public class LocalCorrectionsSubProcessor {
public static void addCastProposals(ICorrectionContext context, List proposals) throws CoreException {
String[] args= context.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast= (Expression) selectedNode;
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
if (selectedNode.equals(assign.getLeftHandSide())) {
nodeToCast= assign.getRightHandSide();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
nodeToCast= frag.getInitializer();
}
}
ASTRewriteCorrectionProposal castProposal= getCastProposal(context, castType, nodeToCast);
if (castProposal != null) {
proposals.add(castProposal);
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (binding != null && decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
binding= ASTResolving.normalizeTypeBinding(binding);
if (binding == null) {
binding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(binding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type type= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
type= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
type= decl.getType();
}
}
if (type != null) {
ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String typeName= edit.addImport(args[0]);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1);
varProposal.getRootTextEdit().add(edit);
proposals.add(varProposal);
}
}
}
private static boolean canCast(String castTarget, ITypeBinding bindingToCast) {
bindingToCast= ASTResolving.normalizeTypeBinding(bindingToCast);
if (bindingToCast == null) {
return false;
}
int arrStart= castTarget.indexOf('[');
if (arrStart != -1) {
if (!bindingToCast.isArray()) {
return "java.lang.Object".equals(bindingToCast.getQualifiedName()); //$NON-NLS-1$
}
castTarget= castTarget.substring(0, arrStart);
bindingToCast= bindingToCast.getElementType();
if (bindingToCast.isPrimitive() && !castTarget.equals(bindingToCast.getName())) {
return false; // can't cast arrays of primitive types into each other
}
}
Code targetCode= PrimitiveType.toCode(castTarget);
if (bindingToCast.isPrimitive()) {
Code castCode= PrimitiveType.toCode(bindingToCast.getName());
if (castCode == targetCode) {
return true;
}
return (targetCode != null && targetCode != PrimitiveType.BOOLEAN && castCode != PrimitiveType.BOOLEAN);
} else {
return targetCode == null;
}
}
public static ASTRewriteCorrectionProposal getCastProposal(ICorrectionContext context, String castType, Expression nodeToCast) throws CoreException {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding != null && !canCast(castType, binding)) {
return null;
}
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
String label;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 1, image); //$NON-NLS-1$
String simpleCastType= proposal.addImport(castType);
if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$
CastExpression expression= (CastExpression) nodeToCast;
rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE));
} else {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$
Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast);
int nodeType= nodeToCast.getNodeType();
if (nodeType == ASTNode.INFIX_EXPRESSION || nodeType == ASTNode.CONDITIONAL_EXPRESSION
|| nodeType == ASTNode.ASSIGNMENT || nodeType == ASTNode.INSTANCEOF_EXPRESSION) {
// nodes have weaker precedence than cast
ParenthesizedExpression parenthesizedExpression= astRoot.getAST().newParenthesizedExpression();
parenthesizedExpression.setExpression(expressionCopy);
expressionCopy= parenthesizedExpression;
}
Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression);
}
proposal.setDisplayName(label);
proposal.ensureNoModifications();
return proposal;
}
public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
if (refactoring == null)
return;
refactoring.setSaveChanges(false);
if (refactoring.checkActivationBasics(astRoot, null).isOK()) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image);
proposals.add(proposal);
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl == null) {
return;
}
ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength()));
if (uncaughtExceptions.length == 0) {
return;
}
TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode);
if (surroundingTry != null && ASTNodes.isParent(selectedNode, surroundingTry.getBody())) {
ASTRewrite rewrite= new ASTRewrite(surroundingTry);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
AST ast= astRoot.getAST();
List catchClauses= surroundingTry.catchClauses();
for (int i= 0; i < uncaughtExceptions.length; i++) {
ITypeBinding excBinding= uncaughtExceptions[i];
String varName= "e"; //$NON-NLS-1$
String imp= proposal.addImport(excBinding);
Name name= ASTNodeFactory.newName(ast, imp);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName(varName));
var.setType(ast.newSimpleType(name));
CatchClause newClause= ast.newCatchClause();
newClause.setException(var);
String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), varName, String.valueOf('\n'));
if (catchBody != null) {
ASTNode node= rewrite.createPlaceholder(catchBody, ASTRewrite.STATEMENT);
newClause.getBody().statements().add(node);
}
rewrite.markAsInserted(newClause);
catchClauses.add(newClause);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
rewrite.markAsInserted(name);
exceptions.add(name);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemove(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static boolean canRemove(ITypeBinding curr, ITypeBinding[] addedExceptions) {
while (curr != null) {
for (int i= 0; i < addedExceptions.length; i++) {
if (curr == addedExceptions[i]) {
return true;
}
}
curr= curr.getSuperclass();
}
return false;
}
public static void addUnreachableCatchProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) {
CatchClause clause= (CatchClause) selectedNode.getParent();
TryStatement tryStatement= (TryStatement) clause.getParent();
ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent());
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(clause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.collapseNodes(statements, 0, statements.size());
rewrite.markAsReplaced(tryStatement, rewrite.createCopy(placeholder));
} else {
rewrite.markAsRemoved(tryStatement);
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
if (! NLSRefactoring.isAvailable(cu)){
return;
}
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= NLSRefactoring.create(cu, JavaPreferencesSettings.getCodeGenerationSettings());
if (refactoring == null)
return;
ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$
new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, true);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
};
proposals.add(proposal);
TextEdit edit= NLSUtil.createNLSEdit(cu, context.getOffset());
if (edit != null) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image);
nlsProposal.getRootTextEdit().add(edit);
proposals.add(nlsProposal);
}
}
/**
* A static field or method is accessed using a non-static reference. E.g.
* <pre>
* File f = new File();
* f.pathSeparator;
* </pre>
* This correction changes <code>f</code> above to <code>File</code>.
*
* @param context
* @param proposals
*/
public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
Expression qualifier= null;
IBinding accessBinding= null;
if (selectedNode instanceof QualifiedName) {
QualifiedName name= (QualifiedName) selectedNode;
qualifier= name.getQualifier();
accessBinding= name.resolveBinding();
} else if (selectedNode instanceof SimpleName) {
ASTNode parent= selectedNode.getParent();
if (parent instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) parent;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
} else if (selectedNode instanceof MethodInvocation) {
MethodInvocation methodInvocation= (MethodInvocation) selectedNode;
qualifier= methodInvocation.getExpression();
accessBinding= methodInvocation.getName().resolveBinding();
} else if (selectedNode instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) selectedNode;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
ITypeBinding declaringTypeBinding= null;
if (accessBinding != null) {
if (accessBinding instanceof IMethodBinding) {
declaringTypeBinding= ((IMethodBinding) accessBinding).getDeclaringClass();
} else if (accessBinding instanceof IVariableBinding) {
declaringTypeBinding= ((IVariableBinding) accessBinding).getDeclaringClass();
}
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(declaringTypeBinding.getName()));
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(declaringTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (qualifier != null) {
ITypeBinding instanceTypeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(instanceTypeBinding.getName()));
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.addImport(instanceTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC);
}
public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
ASTNode typeNode= null;
if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) {
typeNode= selectedNode.getParent();
} else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
typeNode= creation.getAnonymousClassDeclaration();
}
if (typeNode != null) {
UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10);
proposals.add(proposal);
}
if (typeNode instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration);
proposals.add(proposal);
}
}
public static void addUninitializedLocalVariableProposal(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (!(selectedNode instanceof Name)) {
return;
}
Name name= (Name) selectedNode;
IBinding binding= name.resolveBinding();
if (!(binding instanceof IVariableBinding)) {
return;
}
IVariableBinding varBinding= (IVariableBinding) binding;
CompilationUnit astRoot= context.getASTRoot();
ASTNode node= astRoot.findDeclaringNode(binding);
if (node instanceof VariableDeclarationFragment) {
ASTRewrite rewrite= new ASTRewrite(node.getParent());
VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
if (fragment.getInitializer() != null) {
return;
}
Expression expression= ASTResolving.getInitExpression(astRoot.getAST(), varBinding.getType());
if (expression == null) {
return;
}
fragment.setInitializer(expression);
rewrite.markAsInserted(expression);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addConstructorFromSuperclassProposal(ICorrectionContext context, List proposals) {
ASTNode selectedNode= context.getCoveringNode();
if (!(selectedNode instanceof Name && selectedNode.getParent() instanceof TypeDeclaration)) {
return;
}
TypeDeclaration typeDeclaration= (TypeDeclaration) selectedNode.getParent();
ITypeBinding binding= typeDeclaration.resolveBinding();
if (binding == null || binding.getSuperclass() == null) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
IMethodBinding[] methods= binding.getSuperclass().getDeclaredMethods();
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) {
proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 2));
}
}
}
public static void addUnusedMemberProposal(ICorrectionContext context, List proposals) throws CoreException {
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode);
if (declaration != null) {
String label;
ASTNode nodeToRemove= declaration;
if (declaration.getNodeType() == ASTNode.FIELD_DECLARATION) {
label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removeunusedfield.description"); //$NON-NLS-1$
List fragments= ((FieldDeclaration) declaration).fragments();
if (fragments.size() > 1) {
for (int i= 0; i < fragments.size(); i++) {
VariableDeclarationFragment node= (VariableDeclarationFragment) fragments.get(i);
if (ASTNodes.isParent(selectedNode, node)) {
nodeToRemove= node;
break;
}
}
}
} else if (declaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
if (((MethodDeclaration) declaration).isConstructor()) {
label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removeunusedconstructor.description"); //$NON-NLS-1$
} else {
label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removeunusedmethod.description"); //$NON-NLS-1$
}
} else if (declaration.getNodeType() == ASTNode.TYPE_DECLARATION) {
label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removeunusedtype.description"); //$NON-NLS-1$
} else {
return;
}
ASTRewrite rewrite= new ASTRewrite(nodeToRemove.getParent());
rewrite.markAsRemoved(nodeToRemove);
Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
|
36,481 |
Bug 36481 Quickfix (create method) generates wrong parameter type if same name exists in other package [quick fix]
|
given two types with same name, package a; public class A { } package b; public class A { public void doSomething(a.A obj) { newMethod(obj); // this should be quickfixed } } the generated method has the signature private void newMethod(A obj), but should have private void newMethod(a.A obj). I admit this to be not the classic style, we experience this behaviour, because we are generating lots of code and all the generated code goes to one directory, making calls to handwritten code with the same type name (by convention) in other packages.
|
resolved fixed
|
678e41d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T20:47:40Z | 2003-04-15T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.NamingConventions;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class NewMethodCompletionProposal extends ASTRewriteCorrectionProposal {
private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation
private List fArguments;
private ITypeBinding fSenderBinding;
private boolean fIsInDifferentCU;
public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) {
super(label, targetCU, null, relevance, image);
fNode= invocationNode;
fArguments= arguments;
fSenderBinding= binding;
}
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding);
ASTNode newTypeDecl= null;
if (typeDecl != null) {
fIsInDifferentCU= false;
newTypeDecl= typeDecl;
} else {
fIsInDifferentCU= true;
CompilationUnit newRoot= AST.parseCompilationUnit(getCompilationUnit(), true);
newTypeDecl= newRoot.findDeclaringNode(fSenderBinding.getKey());
}
if (newTypeDecl != null) {
ASTRewrite rewrite= new ASTRewrite(newTypeDecl);
List methods;
if (fSenderBinding.isAnonymous()) {
methods= ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations();
} else {
methods= ((TypeDeclaration) newTypeDecl).bodyDeclarations();
}
MethodDeclaration newStub= getStub(rewrite, newTypeDecl);
if (!fIsInDifferentCU) {
methods.add(findInsertIndex(methods, fNode.getStartPosition()), newStub);
} else if (isConstructor()) {
methods.add(0, newStub);
} else {
methods.add(newStub);
}
if (fIsInDifferentCU) { // if in different, select method
rewrite.markAsInserted(newStub, SELECTION_GROUP_DESC);
} else {
rewrite.markAsInserted(newStub);
}
return rewrite;
}
return null;
}
private boolean isConstructor() {
return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION;
}
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
AST ast= targetTypeDecl.getAST();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setConstructor(isConstructor());
decl.setModifiers(evaluateModifiers(targetTypeDecl));
decl.setName(ast.newSimpleName(getMethodName()));
List arguments= fArguments;
List params= decl.parameters();
int nArguments= arguments.size();
ArrayList names= new ArrayList(nArguments);
for (int i= 0; i < arguments.size(); i++) {
Expression elem= (Expression) arguments.get(i);
SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
Type type= getParameterType(ast, elem);
param.setType(type);
param.setName(ast.newSimpleName(getParameterName(names, elem, type)));
params.add(param);
}
Block body= null;
String bodyStatement= ""; //$NON-NLS-1$
if (!isConstructor()) {
Type returnType= evaluateMethodType(ast);
if (returnType == null) {
decl.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID));
} else {
decl.setReturnType(returnType);
}
if (!fSenderBinding.isInterface() && returnType != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(ASTResolving.getInitExpression(returnType, 0));
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'));
}
}
if (!fSenderBinding.isInterface()) {
body= ast.newBlock();
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), getMethodName(), isConstructor(), bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT);
body.statements().add(todoNode);
}
}
decl.setBody(body);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (settings.createComments && !fSenderBinding.isAnonymous()) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private String getParameterName(ArrayList takenNames, Expression argNode, Type type) {
if (argNode instanceof SimpleName) {
String name= ((SimpleName) argNode).getIdentifier();
while (takenNames.contains(name)) {
name += '1';
}
takenNames.add(name);
return name;
}
int dim= 0;
if (type.isArrayType()) {
ArrayType arrayType= (ArrayType) type;
dim= arrayType.getDimensions();
type= arrayType.getElementType();
}
String typeName= ASTNodes.asString(type);
String packName= Signature.getQualifier(typeName);
IJavaProject project= getCompilationUnit().getJavaProject();
String[] excludedNames= (String[]) takenNames.toArray(new String[takenNames.size()]);
String[] names= NamingConventions.suggestArgumentNames(project, packName, typeName, dim, excludedNames);
takenNames.add(names[0]);
return names[0];
}
private int findInsertIndex(List decls, int currPos) {
int nDecls= decls.size();
for (int i= 0; i < nDecls; i++) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) {
return i + 1;
}
}
return nDecls;
}
private String getMethodName() {
if (fNode instanceof MethodInvocation) {
return ((MethodInvocation)fNode).getName().getIdentifier();
} else if (fNode instanceof SuperMethodInvocation) {
return ((SuperMethodInvocation)fNode).getName().getIdentifier();
} else {
return fSenderBinding.getName(); // name of the class
}
}
private int evaluateModifiers(ASTNode targetTypeDecl) {
if (fSenderBinding.isInterface()) {
// for interface members copy the modifiers from an existing field
MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods();
if (methodDecls.length > 0) {
return methodDecls[0].getModifiers();
}
return 0;
}
if (fNode instanceof MethodInvocation) {
int modifiers= 0;
Expression expression= ((MethodInvocation)fNode).getExpression();
if (expression != null) {
if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
modifiers |= Modifier.STATIC;
}
} else if (ASTResolving.isInStaticContext(fNode)) {
modifiers |= Modifier.STATIC;
}
ASTNode node= ASTResolving.findParentType(fNode);
if (targetTypeDecl.equals(node)) {
modifiers |= Modifier.PRIVATE;
} else if (node instanceof AnonymousClassDeclaration) {
modifiers |= Modifier.PROTECTED;
} else {
modifiers |= Modifier.PUBLIC;
}
return modifiers;
}
return Modifier.PUBLIC;
}
private Type evaluateMethodType(AST ast) throws CoreException {
ITypeBinding binding= ASTResolving.guessBindingForReference(fNode);
if (binding != null) {
addImport(binding);
return ASTResolving.getTypeFromTypeBinding(ast, binding);
}
return null;
}
private Type getParameterType(AST ast, Expression elem) throws CoreException {
ITypeBinding binding= ASTResolving.normalizeTypeBinding(elem.resolveTypeBinding());
if (binding != null) {
addImport(binding);
return ASTResolving.getTypeFromTypeBinding(ast, binding);
}
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
}
|
36,481 |
Bug 36481 Quickfix (create method) generates wrong parameter type if same name exists in other package [quick fix]
|
given two types with same name, package a; public class A { } package b; public class A { public void doSomething(a.A obj) { newMethod(obj); // this should be quickfixed } } the generated method has the signature private void newMethod(A obj), but should have private void newMethod(a.A obj). I admit this to be not the classic style, we experience this behaviour, because we are generating lots of code and all the generated code goes to one directory, making calls to handwritten code with the same type name (by convention) in other packages.
|
resolved fixed
|
678e41d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T20:47:40Z | 2003-04-15T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewVariableCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
public class NewVariableCompletionProposal extends ASTRewriteCorrectionProposal {
public static final int LOCAL= 1;
public static final int FIELD= 2;
public static final int PARAM= 3;
private int fVariableKind;
private SimpleName fOriginalNode;
private ITypeBinding fSenderBinding;
private boolean fIsInDifferentCU;
public NewVariableCompletionProposal(String label, ICompilationUnit cu, int variableKind, SimpleName node, ITypeBinding senderBinding, int relevance, Image image) {
super(label, cu, null, relevance, image);
fVariableKind= variableKind;
fOriginalNode= node;
fSenderBinding= senderBinding;
fIsInDifferentCU= false;
}
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit cu= ASTResolving.findParentCompilationUnit(fOriginalNode);
if (fVariableKind == PARAM) {
return doAddParam(cu);
} else if (fVariableKind == FIELD) {
return doAddField(cu);
} else { // LOCAL
return doAddLocal(cu);
}
}
private ASTRewrite doAddParam(CompilationUnit cu) throws CoreException {
AST ast= cu.getAST();
SimpleName node= fOriginalNode;
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(decl);
SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration();
newDecl.setType(evaluateVariableType(ast));
newDecl.setName(ast.newSimpleName(node.getIdentifier()));
rewrite.markAsInserted(newDecl);
((MethodDeclaration)decl).parameters().add(newDecl);
return rewrite;
}
return null;
}
private ASTRewrite doAddLocal(CompilationUnit cu) throws CoreException {
AST ast= cu.getAST();
SimpleName node= fOriginalNode;
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
if (decl instanceof MethodDeclaration || decl instanceof Initializer) {
ASTRewrite rewrite= new ASTRewrite(decl);
VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
VariableDeclarationStatement newDecl= ast.newVariableDeclarationStatement(newDeclFrag);
Type type= evaluateVariableType(ast);
newDecl.setType(type);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
newDeclFrag.setInitializer(ASTResolving.getInitExpression(type, 0));
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment= (Assignment) parent;
if (node.equals(assignment.getLeftHandSide())) {
int parentParentKind= parent.getParent().getNodeType();
if (parentParentKind == ASTNode.EXPRESSION_STATEMENT) {
Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide());
newDeclFrag.setInitializer(placeholder);
rewrite.markAsReplaced(assignment.getParent(), newDecl);
return rewrite;
} else if (parentParentKind == ASTNode.FOR_STATEMENT) {
ForStatement forStatement= (ForStatement) parent.getParent();
if (forStatement.initializers().size() == 1 && assignment.equals(forStatement.initializers().get(0))) {
VariableDeclarationFragment frag= ast.newVariableDeclarationFragment();
VariableDeclarationExpression expression= ast.newVariableDeclarationExpression(frag);
frag.setName(ast.newSimpleName(node.getIdentifier()));
Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide());
frag.setInitializer(placeholder);
expression.setType(evaluateVariableType(ast));
rewrite.markAsReplaced(assignment, expression);
return rewrite;
}
}
}
} else if (parent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
rewrite.markAsReplaced(parent, newDecl);
return rewrite;
}
Statement statement= ASTResolving.findParentStatement(node);
if (statement != null && statement.getParent() instanceof Block) {
Block block= (Block) statement.getParent();
List statements= block.statements();
statements.add(0, newDecl);
rewrite.markAsInserted(newDecl);
return rewrite;
}
}
return null;
}
private ASTRewrite doAddField(CompilationUnit astRoot) throws CoreException {
SimpleName node= fOriginalNode;
ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
if (newTypeDecl != null) {
} else {
astRoot= AST.parseCompilationUnit(getCompilationUnit(), true);
newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
fIsInDifferentCU= true;
}
if (newTypeDecl != null) {
ASTRewrite rewrite= new ASTRewrite(newTypeDecl);
AST ast= newTypeDecl.getAST();
VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
fragment.setName(ast.newSimpleName(node.getIdentifier()));
Type type= evaluateVariableType(ast);
FieldDeclaration newDecl= ast.newFieldDeclaration(fragment);
newDecl.setType(type);
newDecl.setModifiers(evaluateFieldModifiers(newTypeDecl));
if (fSenderBinding.isInterface()) {
fragment.setInitializer(ASTResolving.getInitExpression(type, 0));
}
boolean isAnonymous= newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
List decls= isAnonymous ? ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations() : ((TypeDeclaration) newTypeDecl).bodyDeclarations();
decls.add(findInsertIndex(decls, node.getStartPosition()), newDecl);
if (fIsInDifferentCU) {
rewrite.markAsInserted(newDecl, SELECTION_GROUP_DESC);
} else {
rewrite.markAsInserted(newDecl);
}
return rewrite;
}
return null;
}
private int findInsertIndex(List decls, int currPos) {
for (int i= 0; i < decls.size(); i++) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof FieldDeclaration) {
if (currPos > curr.getStartPosition() + curr.getLength()) {
return i;
} else {
return 0;
}
}
}
return 0;
}
private Type evaluateVariableType(AST ast) throws CoreException {
ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode);
if (binding != null) {
addImport(binding);
return ASTResolving.getTypeFromTypeBinding(ast, binding);
}
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
private int evaluateFieldModifiers(ASTNode newTypeDecl) {
if (fSenderBinding.isInterface()) {
// for interface members copy the modifiers from an existing field
FieldDeclaration[] fieldDecls= ((TypeDeclaration) newTypeDecl).getFields();
if (fieldDecls.length > 0) {
return fieldDecls[0].getModifiers();
}
return 0;
}
int modifiers= 0;
ASTNode node= ASTResolving.findParentType(fOriginalNode);
if (newTypeDecl.equals(node)) {
modifiers |= Modifier.PRIVATE;
if (ASTResolving.isInStaticContext(fOriginalNode)) {
modifiers |= Modifier.STATIC;
}
} else if (node instanceof AnonymousClassDeclaration) {
modifiers |= Modifier.PROTECTED;
} else {
modifiers |= Modifier.PUBLIC;
ASTNode parent= fOriginalNode.getParent();
if (parent instanceof QualifiedName) {
Name qualifier= ((QualifiedName)parent).getQualifier();
if (qualifier.resolveBinding().getKind() == IBinding.TYPE) {
modifiers |= Modifier.STATIC;
}
}
}
return modifiers;
}
/**
* Returns the variable kind.
* @return int
*/
public int getVariableKind() {
return fVariableKind;
}
}
|
36,481 |
Bug 36481 Quickfix (create method) generates wrong parameter type if same name exists in other package [quick fix]
|
given two types with same name, package a; public class A { } package b; public class A { public void doSomething(a.A obj) { newMethod(obj); // this should be quickfixed } } the generated method has the signature private void newMethod(A obj), but should have private void newMethod(a.A obj). I admit this to be not the classic style, we experience this behaviour, because we are generating lots of code and all the generated code goes to one directory, making calls to handwritten code with the same type name (by convention) in other packages.
|
resolved fixed
|
678e41d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T20:47:40Z | 2003-04-15T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReturnTypeSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
*/
public class ReturnTypeSubProcessor {
private static class ReturnStatementCollector extends ASTVisitor {
private ArrayList fResult= new ArrayList();
public Iterator returnStatements() {
return fResult.iterator();
}
public ITypeBinding getTypeBinding(AST ast) {
boolean couldBeObject= false;
for (int i= 0; i < fResult.size(); i++) {
ReturnStatement node= (ReturnStatement) fResult.get(i);
Expression expr= node.getExpression();
if (expr != null) {
ITypeBinding binding= ASTResolving.normalizeTypeBinding(expr.resolveTypeBinding());
if (binding != null) {
return binding;
} else {
couldBeObject= true;
}
} else {
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
}
if (couldBeObject) {
return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
public boolean visit(ReturnStatement node) {
fResult.add(node);
return false;
}
public boolean visit(AnonymousClassDeclaration node) {
return false;
}
public boolean visit(TypeDeclaration node) {
return false;
}
}
public static void addMethodWithConstrNameProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode instanceof MethodDeclaration) {
MethodDeclaration declaration= (MethodDeclaration) selectedNode;
ASTRewrite rewrite= new ASTRewrite(declaration);
rewrite.markAsRemoved(declaration.getReturnType());
String label= CorrectionMessages.getString("ReturnTypeSubProcessor.constrnamemethod.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addVoidMethodReturnsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration && selectedNode.getNodeType() == ASTNode.RETURN_STATEMENT) {
ReturnStatement returnStatement= (ReturnStatement) selectedNode;
Expression expr= returnStatement.getExpression();
if (expr != null) {
ITypeBinding binding= ASTResolving.normalizeTypeBinding(expr.resolveTypeBinding());
if (binding == null) {
binding= selectedNode.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding);
if (methodDeclaration.isConstructor()) {
MethodDeclaration modifiedNode= astRoot.getAST().newMethodDeclaration();
modifiedNode.setModifiers(methodDeclaration.getModifiers()); // no changes
modifiedNode.setExtraDimensions(methodDeclaration.getExtraDimensions()); // no changes
modifiedNode.setConstructor(false);
rewrite.markAsModified(methodDeclaration, modifiedNode);
methodDeclaration.setReturnType(newReturnType);
rewrite.markAsInserted(newReturnType);
} else {
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
}
String label= CorrectionMessages.getFormattedString("ReturnTypeSubProcessor.voidmethodreturns.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(binding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
ASTRewrite rewrite= new ASTRewrite(decl);
rewrite.markAsRemoved(returnStatement);
String label= CorrectionMessages.getString("ReturnTypeSubProcessor.removereturn.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addMissingReturnTypeProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ReturnStatementCollector eval= new ReturnStatementCollector();
decl.accept(eval);
ITypeBinding typeBinding= eval.getTypeBinding(decl.getAST());
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
AST ast= astRoot.getAST();
Type type;
String typeName;
if (typeBinding != null) {
type= ASTResolving.getTypeFromTypeBinding(ast, typeBinding);
typeName= typeBinding.getName();
} else {
type= ast.newPrimitiveType(PrimitiveType.VOID);
typeName= "void"; //$NON-NLS-1$
}
String label= CorrectionMessages.getFormattedString("ReturnTypeSubProcessor.missingreturntype.description", typeName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
if (typeBinding != null) {
proposal.addImport(typeBinding);
}
rewrite.markAsInserted(type);
methodDeclaration.setReturnType(type);
MethodDeclaration modifiedNode= ast.newMethodDeclaration();
modifiedNode.setModifiers(methodDeclaration.getModifiers()); // no changes
modifiedNode.setExtraDimensions(methodDeclaration.getExtraDimensions()); // no changes
modifiedNode.setConstructor(false);
rewrite.markAsModified(methodDeclaration, modifiedNode);
proposal.ensureNoModifications();
proposals.add(proposal);
// change to constructor
ASTNode parentType= ASTResolving.findParentType(decl);
if (parentType instanceof TypeDeclaration) {
String constructorName= ((TypeDeclaration) parentType).getName().getIdentifier();
ASTNode nameNode= methodDeclaration.getName();
label= CorrectionMessages.getFormattedString("ReturnTypeSubProcessor.wrongconstructorname.description", constructorName); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, 1));
}
}
}
/**
* Method addMissingReturnStatementProposals.
* @param context
* @param proposals
*/
public static void addMissingReturnStatementProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDecl= (MethodDeclaration) decl;
if (selectedNode instanceof ReturnStatement) {
ReturnStatement returnStatement= (ReturnStatement) selectedNode;
if (returnStatement.getExpression() == null) {
ASTRewrite rewrite= new ASTRewrite(methodDecl);
Expression expression= ASTResolving.getInitExpression(methodDecl.getReturnType(), methodDecl.getExtraDimensions());
if (expression != null) {
returnStatement.setExpression(expression);
rewrite.markAsInserted(expression);
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
String label= CorrectionMessages.getString("ReturnTypeSubProcessor.changereturnstatement.description"); //$NON-NLS-1$
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 3, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
} else {
Block block= methodDecl.getBody();
if (block == null) {
return;
}
AST ast= methodDecl.getAST();
ASTRewrite rewrite= new ASTRewrite(methodDecl);
List statements= block.statements();
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(ASTResolving.getInitExpression(methodDecl.getReturnType(), methodDecl.getExtraDimensions()));
statements.add(returnStatement);
rewrite.markAsInserted(returnStatement);
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
String label= CorrectionMessages.getString("ReturnTypeSubProcessor.addreturnstatement.description"); //$NON-NLS-1$
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 3, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
}
|
36,481 |
Bug 36481 Quickfix (create method) generates wrong parameter type if same name exists in other package [quick fix]
|
given two types with same name, package a; public class A { } package b; public class A { public void doSomething(a.A obj) { newMethod(obj); // this should be quickfixed } } the generated method has the signature private void newMethod(A obj), but should have private void newMethod(a.A obj). I admit this to be not the classic style, we experience this behaviour, because we are generating lots of code and all the generated code goes to one directory, making calls to handwritten code with the same type name (by convention) in other packages.
|
resolved fixed
|
678e41d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T20:47:40Z | 2003-04-15T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnimplementedMethodsCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.Javadoc;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class UnimplementedMethodsCompletionProposal extends ASTRewriteCorrectionProposal {
private ASTNode fTypeNode;
public UnimplementedMethodsCompletionProposal(ICompilationUnit cu, ASTNode typeNode, int relevance) {
super(null, cu, null, relevance, null);
setDisplayName(CorrectionMessages.getString("UnimplementedMethodsCompletionProposal.description"));//$NON-NLS-1$
setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
fTypeNode= typeNode;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
*/
protected ASTRewrite getRewrite() throws CoreException {
ITypeBinding binding;
List bodyDecls;
if (fTypeNode instanceof AnonymousClassDeclaration) {
AnonymousClassDeclaration decl= (AnonymousClassDeclaration) fTypeNode;
binding= decl.resolveBinding();
bodyDecls= decl.bodyDeclarations();
} else {
TypeDeclaration decl= (TypeDeclaration) fTypeNode;
binding= decl.resolveBinding();
bodyDecls= decl.bodyDeclarations();
}
IMethodBinding[] methods= evalUnimplementedMethods(binding);
ASTRewrite rewrite= new ASTRewrite(fTypeNode);
AST ast= fTypeNode.getAST();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (!settings.createComments || binding.isAnonymous()) {
settings= null;
}
for (int i= 0; i < methods.length; i++) {
MethodDeclaration newMethodDecl= createNewMethodDeclaration(ast, methods[i], rewrite, binding.getName(), settings);
rewrite.markAsInserted(newMethodDecl);
bodyDecls.add(newMethodDecl);
}
return rewrite;
}
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, String typeName, CodeGenerationSettings commentSettings) throws CoreException {
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setModifiers(binding.getModifiers() & ~Modifier.ABSTRACT);
decl.setName(ast.newSimpleName(binding.getName()));
decl.setConstructor(false);
ITypeBinding returnTypeBinding= binding.getReturnType();
addImport(returnTypeBinding);
decl.setReturnType(ASTResolving.getTypeFromTypeBinding(ast, returnTypeBinding));
List parameters= decl.parameters();
ITypeBinding[] params= binding.getParameterTypes();
String[] paramNames= getArgumentNames(binding);
for (int i= 0; i < params.length; i++) {
ITypeBinding curr= params[i];
addImport(curr);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setType(ASTResolving.getTypeFromTypeBinding(ast, curr));
var.setName(ast.newSimpleName(paramNames[i]));
parameters.add(var);
}
List thrownExceptions= decl.thrownExceptions();
ITypeBinding[] excTypes= binding.getExceptionTypes();
for (int i= 0; i < excTypes.length; i++) {
ITypeBinding curr= excTypes[i];
addImport(curr);
thrownExceptions.add(ast.newSimpleName(curr.getName())); // can only be singe type, no array
}
Block body= ast.newBlock();
decl.setBody(body);
String bodyStatement= ""; //$NON-NLS-1$
Expression expression= ASTResolving.getInitExpression(decl.getReturnType(), decl.getExtraDimensions());
if (expression != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(expression);
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'));
}
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), typeName, binding.getName(), false, bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT);
body.statements().add(todoNode);
}
if (commentSettings != null) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), typeName, decl, binding, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private String[] getArgumentNames(IMethodBinding binding) {
int nParams= binding.getParameterTypes().length;
if (nParams > 0) {
try {
IMethod method= Bindings.findMethod(binding, getCompilationUnit().getJavaProject());
if (method != null) {
return method.getParameterNames();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
String[] names= new String[nParams];
for (int i= 0; i < names.length; i++) {
names[i]= "arg" + i; //$NON-NLS-1$
}
return names;
}
private void findUnimplementedInterfaceMethods(ITypeBinding typeBinding, HashSet visited, ArrayList allMethods, ArrayList toImplement) {
if (visited.add(typeBinding)) {
IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods();
for (int i= 0; i < typeMethods.length; i++) {
IMethodBinding curr= typeMethods[i];
IMethodBinding impl= findMethod(curr, allMethods);
if (impl == null || ((curr.getExceptionTypes().length < impl.getExceptionTypes().length) && !Modifier.isFinal(impl.getModifiers()))) {
if (impl != null) {
allMethods.remove(impl);
}
// implement an interface method when it does not exist in the hierarchy
// or when it throws less exceptions that the implemented
toImplement.add(curr);
allMethods.add(curr);
}
}
ITypeBinding[] superInterfaces= typeBinding.getInterfaces();
for (int i= 0; i < superInterfaces.length; i++) {
findUnimplementedInterfaceMethods(superInterfaces[i], visited, allMethods, toImplement);
}
}
}
private IMethodBinding[] evalUnimplementedMethods(ITypeBinding typeBinding) {
ArrayList allMethods= new ArrayList();
ArrayList toImplement= new ArrayList();
IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods();
for (int i= 0; i < typeMethods.length; i++) {
IMethodBinding curr= typeMethods[i];
int modifiers= curr.getModifiers();
if (!curr.isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
allMethods.add(curr);
}
}
ITypeBinding superClass= typeBinding.getSuperclass();
while (superClass != null) {
typeMethods= superClass.getDeclaredMethods();
for (int i= 0; i < typeMethods.length; i++) {
IMethodBinding curr= typeMethods[i];
int modifiers= curr.getModifiers();
if (!curr.isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
if (findMethod(curr, allMethods) == null) {
allMethods.add(curr);
}
}
}
superClass= superClass.getSuperclass();
}
for (int i= 0; i < allMethods.size(); i++) {
IMethodBinding curr= (IMethodBinding) allMethods.get(i);
int modifiers= curr.getModifiers();
if ((Modifier.isAbstract(modifiers) || curr.getDeclaringClass().isInterface()) && (typeBinding != curr.getDeclaringClass())) {
// implement all abstract methods
toImplement.add(curr);
}
}
HashSet visited= new HashSet();
ITypeBinding curr= typeBinding;
while (curr != null) {
ITypeBinding[] superInterfaces= curr.getInterfaces();
for (int i= 0; i < superInterfaces.length; i++) {
findUnimplementedInterfaceMethods(superInterfaces[i], visited, allMethods, toImplement);
}
curr= curr.getSuperclass();
}
return (IMethodBinding[]) toImplement.toArray(new IMethodBinding[toImplement.size()]);
}
private IMethodBinding findMethod(IMethodBinding method, ArrayList allMethods) {
for (int i= 0; i < allMethods.size(); i++) {
IMethodBinding curr= (IMethodBinding) allMethods.get(i);
if (Bindings.isEqualMethod(method, curr.getName(), curr.getParameterTypes())) {
return curr;
}
}
return null;
}
}
|
36,456 |
Bug 36456 Type heirarchy show final class icon only on double click [type hierarchy]
|
When opening a type heirarchy, the icons for the heirarchy do not show final classes (ie. the little 'F' in the icon). When the icon is double clicked to open the class, the icon changes.
|
resolved fixed
|
c192b95
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T21:07:03Z | 2003-04-14T14:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.ITypeHierarchyViewPart;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* view showing the supertypes/subtypes of its input.
*/
public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider {
public static final int VIEW_ID_TYPE= 2;
public static final int VIEW_ID_SUPER= 0;
public static final int VIEW_ID_SUB= 1;
public static final int VIEW_ORIENTATION_VERTICAL= 0;
public static final int VIEW_ORIENTATION_HORIZONTAL= 1;
public static final int VIEW_ORIENTATION_SINGLE= 2;
private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$
private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String TAG_INPUT= "input"; //$NON-NLS-1$
private static final String TAG_VIEW= "view"; //$NON-NLS-1$
private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$
private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$
private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$
// the selected type in the hierarchy view
private IType fSelectedType;
// input element or null
private IJavaElement fInputElement;
// history of input elements. No duplicates
private ArrayList fInputHistory;
private IMemento fMemento;
private IDialogSettings fDialogSettings;
private TypeHierarchyLifeCycle fHierarchyLifeCycle;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
private IPropertyChangeListener fPropertyChangeListener;
private SelectionProviderMediator fSelectionProviderMediator;
private ISelectionChangedListener fSelectionChangedListener;
private IPartListener2 fPartListener;
private int fCurrentOrientation;
private boolean fLinkingEnabled;
private boolean fIsVisible;
private boolean fNeedRefresh;
private boolean fIsEnableMemberFilter;
private boolean fIsRefreshRunnablePosted;
private int fCurrentViewerIndex;
private TypeHierarchyViewer[] fAllViewers;
private MethodsViewer fMethodsViewer;
private SashForm fTypeMethodsSplitter;
private PageBook fViewerbook;
private PageBook fPagebook;
private Label fNoHierarchyShownLabel;
private Label fEmptyTypesViewer;
private ViewForm fTypeViewerViewForm;
private ViewForm fMethodViewerViewForm;
private CLabel fMethodViewerPaneLabel;
private JavaUILabelProvider fPaneLabelProvider;
private ToggleViewAction[] fViewActions;
private ToggleLinkingAction fToggleLinkingAction;
private HistoryDropDownAction fHistoryDropDownAction;
private ToggleOrientationAction[] fToggleOrientationActions;
private EnableMemberFilterAction fEnableMemberFilterAction;
private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction;
private AddMethodStubAction fAddStubAction;
private FocusOnTypeAction fFocusOnTypeAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private SelectAllAction fSelectAllAction;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
fIsVisible= false;
fIsRefreshRunnablePosted= false;
boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fHierarchyLifeCycle.setReconciled(isReconciled);
fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) {
doTypeHierarchyChanged(typeHierarchy, changedTypes);
}
};
fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
fIsEnableMemberFilter= false;
fInputHistory= new ArrayList();
fAllViewers= null;
fViewActions= new ToggleViewAction[] {
new ToggleViewAction(this, VIEW_ID_TYPE),
new ToggleViewAction(this, VIEW_ID_SUPER),
new ToggleViewAction(this, VIEW_ID_SUB)
};
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
fHistoryDropDownAction= new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions= new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fEnableMemberFilterAction= new EnableMemberFilterAction(this, false);
fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false);
fFocusOnTypeAction= new FocusOnTypeAction(this);
fPaneLabelProvider= new JavaUILabelProvider();
fAddStubAction= new AddMethodStubAction();
fFocusOnSelectionAction= new FocusOnSelectionAction(this);
fPartListener= new IPartListener2() {
public void partVisible(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part == TypeHierarchyViewPart.this) {
visibilityChanged(true);
}
}
public void partHidden(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part == TypeHierarchyViewPart.this) {
visibilityChanged(false);
}
}
public void partActivated(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partInputChanged(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
};
public void partBroughtToTop(IWorkbenchPartReference ref) {}
public void partClosed(IWorkbenchPartReference ref) {}
public void partDeactivated(IWorkbenchPartReference ref) {}
public void partOpened(IWorkbenchPartReference ref) {}
};
fSelectionChangedListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR);
}
/**
* Method doPropertyChange.
* @param event
*/
protected void doPropertyChange(PropertyChangeEvent event) {
if (fMethodsViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fMethodsViewer.refresh();
}
}
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
fInputHistory.remove(entry);
}
fInputHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(true);
}
private void updateHistoryEntries() {
for (int i= fInputHistory.size() - 1; i >= 0; i--) {
IJavaElement type= (IJavaElement) fInputHistory.get(i);
if (!type.exists()) {
fInputHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
updateInput(entry);
}
}
/**
* Gets all history entries.
*/
public IJavaElement[] getHistoryEntries() {
if (fInputHistory.size() > 0) {
updateHistoryEntries();
}
return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]);
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IJavaElement[] elems) {
fInputHistory.clear();
for (int i= 0; i < elems.length; i++) {
fInputHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Selects an member in the methods list or in the current hierarchy.
*/
public void selectMember(IMember member) {
if (member.getElementType() != IJavaElement.TYPE) {
// methods are working copies
if (fHierarchyLifeCycle.isReconciled()) {
member= JavaModelUtil.toWorkingCopy(member);
}
Control methodControl= fMethodsViewer.getControl();
if (methodControl != null && !methodControl.isDisposed()) {
methodControl.setFocus();
}
fMethodsViewer.setSelection(new StructuredSelection(member), true);
} else {
Control viewerControl= getCurrentViewer().getControl();
if (viewerControl != null && !viewerControl.isDisposed()) {
viewerControl.setFocus();
}
// types are originals
member= JavaModelUtil.toOriginal(member);
if (!member.equals(fSelectedType)) {
getCurrentViewer().setSelection(new StructuredSelection(member), true);
}
}
}
/**
* @deprecated
*/
public IType getInput() {
if (fInputElement instanceof IType) {
return (IType) fInputElement;
}
return null;
}
/**
* Sets the input to a new type
* @deprecated
*/
public void setInput(IType type) {
setInputElement(type);
}
/**
* Returns the input element of the type hierarchy.
* Can be of type <code>IType</code> or <code>IPackageFragment</code>
*/
public IJavaElement getInputElement() {
return fInputElement;
}
/**
* Sets the input to a new element.
*/
public void setInputElement(IJavaElement element) {
if (element != null) {
if (element instanceof IMember) {
if (element.getElementType() != IJavaElement.TYPE) {
element= ((IMember) element).getDeclaringType();
}
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(element);
if (!element.exists()) {
MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
}
} else {
int kind= element.getElementType();
if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) {
element= null;
JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$
}
}
}
if (element != null && !element.equals(fInputElement)) {
addHistoryEntry(element);
}
updateInput(element);
}
/**
* Changes the input to a new type
*/
private void updateInput(IJavaElement inputElement) {
IJavaElement prevInput= fInputElement;
// Make sure the UI got repainted before we execute a long running
// operation. This can be removed if we refresh the hierarchy in a
// separate thread.
// Work-araound for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881
processOutstandingEvents();
if (inputElement == null) {
clearInput();
} else {
fInputElement= inputElement;
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, JavaPlugin.getActiveWorkbenchWindow());
// fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, getSite().getWorkbenchWindow());
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$
clearInput();
return;
} catch (InterruptedException e) {
return;
}
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!inputElement.equals(prevInput)) {
updateHierarchyViewer(true);
}
IType root= getSelectableType(inputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
fPagebook.showPage(fTypeMethodsSplitter);
}
}
private void processOutstandingEvents() {
Display display= getDisplay();
if (display != null && !display.isDisposed())
display.update();
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer(false);
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
fMethodsViewer.dispose();
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.dispose();
super.dispose();
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
private Control createTypeViewerControl(Composite parent) {
fViewerbook= new PageBook(parent, SWT.NULL);
KeyListener keyListener= createKeyListener();
// Create the viewers
TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW);
TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW);
TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW);
fAllViewers= new TypeHierarchyViewer[3];
fAllViewers[VIEW_ID_SUPER]= superTypesViewer;
fAllViewers[VIEW_ID_SUB]= subTypesViewer;
fAllViewers[VIEW_ID_TYPE]= vajViewer;
int currViewerIndex;
try {
currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW);
if (currViewerIndex < 0 || currViewerIndex > 2) {
currViewerIndex= VIEW_ID_TYPE;
}
} catch (NumberFormatException e) {
currViewerIndex= VIEW_ID_TYPE;
}
fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setInput(fAllViewers[i]);
}
// force the update
fCurrentViewerIndex= -1;
setView(currViewerIndex);
return fViewerbook;
}
private KeyListener createKeyListener() {
return new KeyAdapter() {
public void keyReleased(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
updateHierarchyViewer(false);
return;
} else if (event.character == SWT.DEL){
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
}
};
}
private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) {
typesViewer.getControl().setVisible(false);
typesViewer.getControl().addKeyListener(keyListener);
typesViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillTypesViewerContextMenu(typesViewer, menu);
}
}, cotextHelpId, getSite());
typesViewer.addSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
}
private Control createMethodViewerControl(Composite parent) {
fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this);
fMethodsViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillMethodsViewerContextMenu(menu);
}
}, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite());
fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
return control;
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
for (int i= 0; i < fAllViewers.length; i++) {
addDragAdapters(fAllViewers[i], ops, transfers);
addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers);
}
addDragAdapters(fMethodsViewer, ops, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0]));
}
private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new TypeHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) {
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// page 1 of pagebook (viewers)
fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL);
fTypeMethodsSplitter.setVisible(false);
fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm);
fTypeViewerViewForm.setContent(typeViewerControl);
fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
fTypeMethodsSplitter.setWeights(new int[] {35, 65});
Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm);
fMethodViewerViewForm.setContent(methodViewerPart);
fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE);
fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel);
ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP);
fMethodViewerViewForm.setTopCenter(methodViewerToolBar);
// page 2 of pagebook (no hierarchy label)
fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$
MenuManager menu= new MenuManager();
menu.add(fFocusOnTypeAction);
fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel));
fPagebook.showPage(fNoHierarchyShownLabel);
int orientation;
try {
orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if (orientation < 0 || orientation > 2) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation= -1;
// will fill the main tool bar
setOrientation(orientation);
if (fMemento != null) { // restore state before creating action
restoreLinkingEnabled(fMemento);
}
fToggleLinkingAction= new ToggleLinkingAction(this);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fViewActions.length; i++) {
viewMenu.add(fViewActions[i]);
}
viewMenu.add(new Separator());
for (int i= 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
viewMenu.add(fShowQualifiedTypeNamesAction);
viewMenu.add(fToggleLinkingAction);
// fill the method viewer toolbar
ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar);
lowertbmanager.add(fEnableMemberFilterAction);
lowertbmanager.add(new Separator());
fMethodsViewer.contributeToToolBar(lowertbmanager);
lowertbmanager.update(true);
// selection provider
int nHierarchyViewers= fAllViewers.length;
Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1];
for (int i= 0; i < nHierarchyViewers; i++) {
trackedViewers[i]= fAllViewers[i];
}
trackedViewers[nHierarchyViewers]= fMethodsViewer;
fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
getSite().getPage().addPartListener(fPartListener);
// see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33657
IJavaElement input= null; //determineInputElement();
if (fMemento != null) {
restoreState(fMemento, input);
} else if (input != null) {
setInputElement(input);
} else {
setViewerVisibility(false);
}
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new NewWizardsActionGroup(this.getSite()),
new OpenEditorActionGroup(this),
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
initDragAndDrop();
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
public void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
boolean methodViewerNeedsUpdate= false;
if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed()
&& fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(false);
enableMemberFilter(false);
updateMethodViewer(null);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(true);
methodViewerNeedsUpdate= true;
}
boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL;
fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
}
updateMainToolbar(orientation);
fTypeMethodsSplitter.layout();
}
for (int i= 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation= orientation;
if (methodViewerNeedsUpdate) {
updateMethodViewer(fSelectedType);
}
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
private void updateMainToolbar(int orientation) {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager tbmanager= actionBars.getToolBarManager();
if (orientation == VIEW_ORIENTATION_HORIZONTAL) {
clearMainToolBar(tbmanager);
ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP);
fillMainToolBar(new ToolBarManager(typeViewerToolBar));
fTypeViewerViewForm.setTopLeft(typeViewerToolBar);
} else {
fTypeViewerViewForm.setTopLeft(null);
fillMainToolBar(tbmanager);
}
}
private void fillMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.add(fHistoryDropDownAction);
for (int i= 0; i < fViewActions.length; i++) {
tbmanager.add(fViewActions[i]);
}
tbmanager.update(false);
}
private void clearMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.update(false);
}
/**
* Creates the context menu for the hierarchy viewers
*/
private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
// viewer entries
viewer.contributeToContextMenu(menu);
if (fFocusOnSelectionAction.canActionBeAdded())
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction);
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Creates the context menu for the method viewer
*/
private void fillMethodsViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
fMethodsViewer.contributeToContextMenu(menu);
if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction);
}
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Toggles between the empty viewer page and the hierarchy
*/
private void setViewerVisibility(boolean showHierarchy) {
if (showHierarchy) {
fViewerbook.showPage(getCurrentViewer().getControl());
} else {
fViewerbook.showPage(fEmptyTypesViewer);
}
}
/**
* Sets the member filter. <code>null</code> disables member filtering.
*/
private void setMemberFilter(IMember[] memberFilter) {
Assert.isNotNull(fAllViewers);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setMemberFilter(memberFilter);
}
}
private IType getSelectableType(IJavaElement elem) {
if (elem.getElementType() != IJavaElement.TYPE) {
return null; //(IType) getCurrentViewer().getTreeRootType();
} else {
return (IType) elem;
}
}
private void internalSelectType(IMember elem, boolean reveal) {
TypeHierarchyViewer viewer= getCurrentViewer();
viewer.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addSelectionChangedListener(fSelectionChangedListener);
}
/**
* When the input changed or the hierarchy pane becomes visible,
* <code>updateHierarchyViewer<code> brings up the correct view and refreshes
* the current tree
*/
private void updateHierarchyViewer(final boolean doExpand) {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent(doExpand); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) {
setViewerVisibility(true);
}
} else {
fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$
setViewerVisibility(false);
}
}
}
private void updateMethodViewer(final IType input) {
if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) {
if (input == fMethodsViewer.getInput()) {
if (input != null) {
Runnable runnable= new Runnable() {
public void run() {
fMethodsViewer.refresh(); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
}
} else {
if (input != null) {
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input));
} else {
fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$
fMethodViewerPaneLabel.setImage(null);
}
Runnable runnable= new Runnable() {
public void run() {
fMethodsViewer.setInput(input); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fMethodsViewer) {
methodSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(true);
} else {
typeSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(false);
}
}
private void methodSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (fIsEnableMemberFilter) {
IMember[] memberFilter= null;
if (nSelected > 0) {
memberFilter= new IMember[nSelected];
selected.toArray(memberFilter);
}
setMemberFilter(memberFilter);
updateHierarchyViewer(true);
updateTitle();
internalSelectType(fSelectedType, true);
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), fMethodsViewer);
}
}
}
private void typeSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (nSelected != 0) {
List types= new ArrayList(nSelected);
for (int i= nSelected-1; i >= 0; i--) {
Object elem= selected.get(i);
if (elem instanceof IType && !types.contains(elem)) {
types.add(elem);
}
}
if (types.size() == 1) {
fSelectedType= (IType) types.get(0);
updateMethodViewer(fSelectedType);
} else if (types.size() == 0) {
// method selected, no change
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), getCurrentViewer());
}
} else {
fSelectedType= null;
updateMethodViewer(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
IEditorPart editorPart= EditorUtility.isOpenInEditor(elem);
if (editorPart != null && (elem instanceof IJavaElement)) {
getSite().getPage().removePartListener(fPartListener);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
}
}
private Display getDisplay() {
if (fPagebook != null && !fPagebook.isDisposed()) {
return fPagebook.getDisplay();
}
return null;
}
private boolean isChildVisible(Composite pb, Control child) {
Control[] children= pb.getChildren();
for (int i= 0; i < children.length; i++) {
if (children[i] == child && children[i].isVisible())
return true;
}
return false;
}
private void updateTitle() {
String viewerTitle= getCurrentViewer().getTitle();
String tooltip;
String title;
if (fInputElement != null) {
String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) };
title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$
tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$
} else {
title= viewerTitle;
tooltip= viewerTitle;
}
setTitle(title);
setTitleToolTip(tooltip);
}
private void updateToolbarButtons() {
boolean isType= fInputElement instanceof IType;
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
if (action.getViewerIndex() == VIEW_ID_TYPE) {
action.setEnabled(fInputElement != null);
} else {
action.setEnabled(isType);
}
}
}
/**
* Sets the current view (see view id)
* called from ToggleViewAction. Must be called after creation of the viewpart.
*/
public void setView(int viewerIndex) {
Assert.isNotNull(fAllViewers);
if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) {
fCurrentViewerIndex= viewerIndex;
updateHierarchyViewer(true);
if (fInputElement != null) {
ISelection currSelection= getCurrentViewer().getSelection();
if (currSelection == null || currSelection.isEmpty()) {
internalSelectType(getSelectableType(fInputElement), false);
currSelection= getCurrentViewer().getSelection();
}
if (!fIsEnableMemberFilter) {
typeSelectionChanged(currSelection);
}
}
updateTitle();
fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex);
getCurrentViewer().getTree().setFocus();
}
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
action.setChecked(fCurrentViewerIndex == action.getViewerIndex());
}
}
/**
* Gets the curret active view index.
*/
public int getViewIndex() {
return fCurrentViewerIndex;
}
private TypeHierarchyViewer getCurrentViewer() {
return fAllViewers[fCurrentViewerIndex];
}
/**
* called from EnableMemberFilterAction.
* Must be called after creation of the viewpart.
*/
public void enableMemberFilter(boolean on) {
if (on != fIsEnableMemberFilter) {
fIsEnableMemberFilter= on;
if (!on) {
IType methodViewerInput= (IType) fMethodsViewer.getInput();
setMemberFilter(null);
updateHierarchyViewer(true);
updateTitle();
if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) {
// avoid that the method view changes content by selecting the previous input
internalSelectType(methodViewerInput, true);
} else if (fSelectedType != null) {
// choose a input that exists
internalSelectType(fSelectedType, true);
updateMethodViewer(fSelectedType);
}
} else {
methodSelectionChanged(fMethodsViewer.getSelection());
}
}
fEnableMemberFilterAction.setChecked(on);
}
/**
* called from ShowQualifiedTypeNamesAction. Must be called after creation
* of the viewpart.
*/
public void showQualifiedTypeNames(boolean on) {
if (fAllViewers == null) {
return;
}
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setQualifiedTypeName(on);
}
}
private boolean isShowQualifiedTypeNames() {
return fShowQualifiedTypeNamesAction.isChecked();
}
/**
* Called from ITypeHierarchyLifeCycleListener.
* Can be called from any thread
*/
protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
if (!fIsVisible) {
fNeedRefresh= true;
return;
}
if (fIsRefreshRunnablePosted) {
return;
}
Display display= getDisplay();
if (display != null) {
fIsRefreshRunnablePosted= true;
display.asyncExec(new Runnable() {
public void run() {
try {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
} finally {
fIsRefreshRunnablePosted= false;
}
}
});
}
}
protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
if (changedTypes == null) {
// hierarchy change
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, getSite().getWorkbenchWindow());
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$
clearInput();
return;
} catch (InterruptedException e) {
return;
}
fMethodsViewer.refresh();
updateHierarchyViewer(false);
} else {
// elements in hierarchy modified
fMethodsViewer.refresh();
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer(false);
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
}
/*
* @see IViewPart#init
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* @see ViewPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
if (fInputElement != null) {
String handleIndentifier= fInputElement.getHandleIdentifier();
if (fInputElement instanceof IType) {
ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) {
// for startup performance reasons do not try to recover huge hierarchies
handleIndentifier= null;
}
}
memento.putString(TAG_INPUT, handleIndentifier);
}
memento.putInteger(TAG_VIEW, getViewIndex());
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int weigths[]= fTypeMethodsSplitter.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putInteger(TAG_VERTICAL_SCROLL, position);
IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement();
if (selection != null) {
memento.putString(TAG_SELECTION, selection.getHandleIdentifier());
}
fMethodsViewer.saveState(memento);
saveLinkingEnabled(memento);
}
private void saveLinkingEnabled(IMemento memento) {
memento.putInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, fLinkingEnabled ? 1 : 0);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
input= null;
}
if (!AllTypesCache.isIndexUpToDate()) {
input= null;
}
}
setInputElement(input);
Integer viewerIndex= memento.getInteger(TAG_VIEW);
if (viewerIndex != null) {
setView(viewerIndex.intValue());
}
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null) {
fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
}
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
//String selectionId= memento.getString(TAG_SELECTION);
// do not restore type hierarchy contents
// if (selectionId != null) {
// IJavaElement elem= JavaCore.create(selectionId);
// if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) {
// internalSelectType((IMember)elem, false);
// }
// }
fMethodsViewer.restoreState(memento);
}
private void restoreLinkingEnabled(IMemento memento) {
Integer val= memento.getInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR);
if (val != null) {
fLinkingEnabled= val.intValue() != 0;
}
}
/**
* view part becomes visible
*/
protected void visibilityChanged(boolean isVisible) {
fIsVisible= isVisible;
if (isVisible && fNeedRefresh) {
doTypeHierarchyChanged(fHierarchyLifeCycle, null);
}
fNeedRefresh= false;
}
/**
* Link selection to active editor.
*/
protected void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled()) {
return;
}
if (fInputElement == null) {
// no type hierarchy shown
return;
}
IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class);
try {
TypeHierarchyViewer currentViewer= getCurrentViewer();
if (elem instanceof IClassFile) {
IType type= ((IClassFile)elem).getType();
if (currentViewer.isElementShown(type)) {
internalSelectType(type, true);
updateMethodViewer(type);
}
} else if (elem instanceof ICompilationUnit) {
IType[] allTypes= ((ICompilationUnit)elem).getAllTypes();
for (int i= 0; i < allTypes.length; i++) {
if (currentViewer.isElementShown(allTypes[i])) {
internalSelectType(allTypes[i], true);
updateMethodViewer(allTypes[i]);
return;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return fInputElement;
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
boolean isLinkingEnabled() {
return fLinkingEnabled;
}
public void setLinkingEnabled(boolean enabled) {
fLinkingEnabled= enabled;
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, enabled);
if (enabled) {
IEditorPart editor = getSite().getPage().getActiveEditor();
if (editor != null) {
editorActivated(editor);
}
}
}
}
|
36,342 |
Bug 36342 Please Imporve "Generate Get and Set "
|
the "generate get" of "private String bankName;" result in public setBankName(String string) { bankName = string; } but I think public setBankName(String bankName) { this.bankName = bankName; } is much better
|
closed fixed
|
eebf753
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T21:40:11Z | 2003-04-10T13:06:40Z |
org.eclipse.jdt.ui/core
| |
36,342 |
Bug 36342 Please Imporve "Generate Get and Set "
|
the "generate get" of "private String bankName;" result in public setBankName(String string) { bankName = string; } but I think public setBankName(String bankName) { this.bankName = bankName; } is much better
|
closed fixed
|
eebf753
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-04-30T21:40:11Z | 2003-04-10T13:06:40Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddGetterSetterOperation.java
| |
37,149 |
Bug 37149 SocketUtil.findUnusedLocalPort bug [JUnit]
| null |
resolved fixed
|
febf2ce
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-02T16:04:31Z | 2003-05-01T20:13:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/JUnitBaseLaunchConfiguration.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.launcher;
import java.io.File;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.junit.ui.JUnitMessages;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
import org.eclipse.jdt.internal.junit.util.SocketUtil;
import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
import org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate;
import org.eclipse.jdt.launching.ExecutionArguments;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMRunner;
import org.eclipse.jdt.launching.VMRunnerConfiguration;
/**
* Abstract launch configuration delegate for a JUnit test.
*/
public abstract class JUnitBaseLaunchConfiguration extends AbstractJavaLaunchConfigurationDelegate {
public static final String PORT_ATTR= JUnitPlugin.PLUGIN_ID+".PORT"; //$NON-NLS-1$
public static final String TESTTYPE_ATTR= JUnitPlugin.PLUGIN_ID+".TESTTYPE"; //$NON-NLS-1$
public static final String TESTNAME_ATTR= JUnitPlugin.PLUGIN_ID+".TESTNAME"; //$NON-NLS-1$
public static final String ATTR_KEEPRUNNING = JUnitPlugin.PLUGIN_ID+ ".KEEPRUNNING_ATTR"; //$NON-NLS-1$
public static final String LAUNCH_CONTAINER_ATTR= JUnitPlugin.PLUGIN_ID+".CONTAINER"; //$NON-NLS-1$
/**
* @see ILaunchConfigurationDelegate#launch(ILaunchConfiguration, String)
*/
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor pm) throws CoreException {
IJavaProject javaProject= getJavaProject(configuration);
if ((javaProject == null) || !javaProject.exists()) {
abort(JUnitMessages.getString("JUnitBaseLaunchConfiguration.error.invalidproject"), null, IJavaLaunchConfigurationConstants.ERR_NOT_A_JAVA_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$
}
IType[] testTypes = getTestTypes(configuration, javaProject, pm);
if (testTypes.length == 0) {
abort(JUnitMessages.getString("JUnitBaseLaunchConfiguration.error.notests"), null, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
IVMInstall install= getVMInstall(configuration);
IVMRunner runner = install.getVMRunner(mode);
if (runner == null) {
abort(MessageFormat.format(JUnitMessages.getString("JUnitBaseLaunchConfiguration.error.novmrunner"), new String[]{install.getId()}), null, IJavaLaunchConfigurationConstants.ERR_VM_RUNNER_DOES_NOT_EXIST); //$NON-NLS-1$
}
int port= SocketUtil.findUnusedLocalPort("", 5000, 15000); //$NON-NLS-1$
VMRunnerConfiguration runConfig= launchTypes(configuration, mode, testTypes, port);
setDefaultSourceLocator(launch, configuration);
launch.setAttribute(PORT_ATTR, Integer.toString(port));
launch.setAttribute(TESTTYPE_ATTR, testTypes[0].getHandleIdentifier());
runner.run(runConfig, launch, pm);
}
protected VMRunnerConfiguration launchTypes(ILaunchConfiguration configuration,
String mode, IType[] tests, int port) throws CoreException {
File workingDir = verifyWorkingDirectory(configuration);
String workingDirName = null;
if (workingDir != null)
workingDirName = workingDir.getAbsolutePath();
// Program & VM args
String vmArgs= getVMArguments(configuration);
ExecutionArguments execArgs = new ExecutionArguments(vmArgs, ""); //$NON-NLS-1$
VMRunnerConfiguration runConfig= createVMRunner(configuration, tests, port, mode);
runConfig.setVMArguments(execArgs.getVMArgumentsArray());
runConfig.setWorkingDirectory(workingDirName);
String[] bootpath = getBootpath(configuration);
runConfig.setBootClassPath(bootpath);
return runConfig;
}
public IType[] getTestTypes(ILaunchConfiguration configuration, IJavaProject javaProject, IProgressMonitor pm) throws CoreException {
String testTypeName = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String)null);
if (pm == null)
pm= new NullProgressMonitor();
// if ((testTypeName == null) || (testTypeName.trim().length() < 1)) {
// abort("No test type specified", null, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
// }
String containerHandle = configuration.getAttribute(LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
if (containerHandle.length() == 0) {
return findSingleTest(javaProject, testTypeName);
}
else
return findTestsInContainer(javaProject, containerHandle, pm);
}
/**
* @inheritdoc
* @param javaProject
* @param containerHandle
* @param pm
* @return
*/
private IType[] findTestsInContainer(IJavaProject javaProject, String containerHandle, IProgressMonitor pm) {
IJavaElement container= JavaCore.create(containerHandle);
Set result= new HashSet();
try {
TestSearchEngine.doFindTests(new Object[]{container}, result, pm);
} catch (InterruptedException e) {
}
return (IType[]) result.toArray(new IType[result.size()]) ;
}
public IType[] findSingleTest(IJavaProject javaProject, String testName) throws CoreException {
IType type = null;
try {
type = findType(javaProject, testName);
} catch (JavaModelException jme) {
abort("Test type does not exist", null, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
if (type == null) {
abort("Test type does not exist", null, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
return new IType[]{type};
}
/**
* Throws a core exception with the given message and optional
* exception. The exception's status code will indicate an error.
*
* @param message error message
* @param exception cause of the error, or <code>null</code>
* @exception CoreException with the given message and underlying
* exception
*/
protected void abort(String message, Throwable exception, int code) throws CoreException {
throw new CoreException(new Status(IStatus.ERROR, JUnitPlugin.PLUGIN_ID, code, message, exception));
}
/**
* Find the specified (fully-qualified) type name in the specified java project.
*/
private IType findType(IJavaProject javaProject, String mainTypeName) throws JavaModelException {
return javaProject.findType(mainTypeName);
}
/**
* Override to create a custom VMRunnerConfiguration for a launch configuration.
*/
protected abstract VMRunnerConfiguration createVMRunner(ILaunchConfiguration configuration, IType[] testTypes, int port, String runMode) throws CoreException;
protected boolean keepAlive(ILaunchConfiguration config) {
try {
return config.getAttribute(ATTR_KEEPRUNNING, false);
} catch(CoreException e) {
}
return false;
}
}
|
37,149 |
Bug 37149 SocketUtil.findUnusedLocalPort bug [JUnit]
| null |
resolved fixed
|
febf2ce
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-02T16:04:31Z | 2003-05-01T20:13:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/util/SocketUtil.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.util;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Random;
/**
* Socket utilities.
*/
public class SocketUtil {
private static final Random fgRandom= new Random(System.currentTimeMillis());
/**
* Method that looks for an unused local port
*
* @param searchFrom lower limit of port range
* @param searchTo upper limit of port range
*/
public static int findUnusedLocalPort(String host, int searchFrom, int searchTo) {
for (int i= 0; i < 10; i++) {
int port= getRandomPort(searchFrom, searchTo);
try {
new Socket(host, port);
} catch (SocketException e) {
return port;
} catch (IOException e) {
}
}
return -1;
}
private static int getRandomPort(int low, int high) {
return (int)(fgRandom.nextFloat()*(high-low))+low;
}
}
|
13,884 |
Bug 13884 NLS tool - not optimized for self hosting [refactoring]
|
The key names generated are not matching our conventions. They should be at least an option to generate key names, which are similar to our conventions to reduce editing of them. - no use of '_' but use capitalization ('fooBar' instead of 'foo_bar') - use numbers as postfix only if ambiguous
|
resolved fixed
|
3710cca
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-05T14:12:12Z | 2002-04-16T15:13:20Z |
org.eclipse.jdt.ui/core
| |
13,884 |
Bug 13884 NLS tool - not optimized for self hosting [refactoring]
|
The key names generated are not matching our conventions. They should be at least an option to generate key names, which are similar to our conventions to reduce editing of them. - no use of '_' but use capitalization ('fooBar' instead of 'foo_bar') - use numbers as postfix only if ambiguous
|
resolved fixed
|
3710cca
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-05T14:12:12Z | 2002-04-16T15:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSHolder.java
| |
37,215 |
Bug 37215 createExecutableExtension does not catch missing super class
|
Build R2.0 We have code that creates classes declared in the plugin.xml with the following API: IConfigurationElement.createExecutableExtension(String) We handle the cases where - there's a CoreException - there's a ClassCastException Given the API comment: * @exception CoreException if an instance of the executable extension * could not be created for any reason. we assumed that this also catches the case where the super class is missing, however this is not the case as can be seen in the following log: !ENTRY org.eclipse.jdt.ui 4 10001 Mai 05, 2003 16:19:07.813 !MESSAGE org.eclipse.jdt.internal.ui.filters.Non !STACK 0 java.lang.NoClassDefFoundError: org.eclipse.jdt.internal.ui.filters.Non at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:75) at java.lang.NoClassDefFoundError.<init>(NoClassDefFoundError.java:51) at java.lang.ClassLoader.defineClassImpl(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java) at java.net.URLClassLoader.defineClass(URLClassLoader.java) at java.net.URLClassLoader.access$400(URLClassLoader.java) at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java) at java.security.AccessController.doPrivileged(AccessController.java:218) at java.net.URLClassLoader.findClass(URLClassLoader.java) at org.eclipse.core.internal.boot.DelegatingURLClassLoader.findClass(DelegatingURLClassLoader.java:922) at org.eclipse.core.internal.plugins.PluginClassLoader.internalFindClassParentsSelf(PluginClassLoader.java) at org.eclipse.core.internal.boot.DelegatingURLClassLoader.findClassParentsSelf(DelegatingURLClassLoader.java) at org.eclipse.core.internal.boot.DelegatingURLClassLoader.loadClass(DelegatingURLClassLoader.java) at org.eclipse.core.internal.boot.DelegatingURLClassLoader.loadClass(DelegatingURLClassLoader.java) at java.lang.ClassLoader.loadClass(ClassLoader.java) at org.eclipse.core.internal.plugins.PluginDescriptor.createExecutableExtension(PluginDescriptor.java:130) at org.eclipse.core.internal.plugins.PluginDescriptor.createExecutableExtension(PluginDescriptor.java:167) at org.eclipse.core.internal.plugins.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:103) at org.eclipse.jdt.internal.ui.filters.FilterDescriptor.createViewerFilter(FilterDescriptor.java:118) at org.eclipse.jdt.ui.actions.CustomFiltersActionGroup.updateBuiltInFilters(CustomFiltersActionGroup.java:223) at org.eclipse.jdt.ui.actions.CustomFiltersActionGroup.updateViewerFilters(CustomFiltersActionGroup.java:193) at org.eclipse.jdt.ui.actions.CustomFiltersActionGroup.openDialog(CustomFiltersActionGroup.java:429) at org.eclipse.jdt.ui.actions.CustomFiltersActionGroup.access$0(CustomFiltersActionGroup.java:414) at org.eclipse.jdt.ui.actions.CustomFiltersActionGroup$ShowFilterDialogAction.run(CustomFiltersActionGroup.java:60) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:526) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:480) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:452) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1402) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1385) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:61) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:40) at java.lang.reflect.Method.invoke(Method.java:335) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
9f27bf9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-05T14:34:45Z | 2003-05-05T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/FilterDescriptor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.filters;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IPluginRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
/**
* Represents a custom filter which is provided by the
* "org.eclipse.jdt.ui.javaElementFilters" extension point.
*
* since 2.0
*/
public class FilterDescriptor implements Comparable {
private static String PATTERN_FILTER_ID_PREFIX= "_patternFilterId_"; //$NON-NLS-1$
private static final String EXTENSION_POINT_NAME= "javaElementFilters"; //$NON-NLS-1$
private static final String FILTER_TAG= "filter"; //$NON-NLS-1$
private static final String PATTERN_ATTRIBUTE= "pattern"; //$NON-NLS-1$
private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$
private static final String VIEW_ID_ATTRIBUTE= "viewId"; //$NON-NLS-1$
private static final String CLASS_ATTRIBUTE= "class"; //$NON-NLS-1$
private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$
private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
/**
* @deprecated use "enabled" instead
*/
private static final String SELECTED_ATTRIBUTE= "selected"; //$NON-NLS-1$
private static FilterDescriptor[] fgFilterDescriptors;
private IConfigurationElement fElement;
/**
* Returns all contributed Java element filters.
*/
public static FilterDescriptor[] getFilterDescriptors() {
if (fgFilterDescriptors == null) {
IPluginRegistry registry= Platform.getPluginRegistry();
IConfigurationElement[] elements= registry.getConfigurationElementsFor(JavaUI.ID_PLUGIN, EXTENSION_POINT_NAME);
fgFilterDescriptors= createFilterDescriptors(elements);
}
return fgFilterDescriptors;
}
/**
* Returns all Java element filters which
* are contributed to the given view.
*/
public static FilterDescriptor[] getFilterDescriptors(String viewId) {
FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors();
List result= new ArrayList(filterDescs.length);
for (int i= 0; i < filterDescs.length; i++) {
String vid= filterDescs[i].getViewId();
if (vid == null || vid.equals(viewId))
result.add(filterDescs[i]);
}
return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]);
}
/**
* Creates a new filter descriptor for the given configuration element.
*/
private FilterDescriptor(IConfigurationElement element) {
fElement= element;
// it is either a pattern filter or a custom filter
Assert.isTrue(isPatternFilter() ^ isCustomFilter());
Assert.isNotNull(getId());
Assert.isNotNull(getName());
}
/**
* Creates a new <code>ViewerFilter</code>.
* This method is only valid for viewer filters.
*
* @throws AssertionFailedException if this is a pattern filter
*
*/
public ViewerFilter createViewerFilter() {
Assert.isTrue(isCustomFilter());
ViewerFilter result= null;
try {
result= (ViewerFilter)fElement.createExecutableExtension(CLASS_ATTRIBUTE);
} catch (CoreException ex) {
handleError(ex.getStatus());
} catch (ClassCastException ex) {
handleError(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IJavaStatusConstants.INTERNAL_ERROR, ex.getLocalizedMessage(), ex));
return null;
}
return result;
}
private void handleError(IStatus status) {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell != null) {
String title= FilterMessages.getString("FilterDescriptor.filterCreationError.title"); //$NON-NLS-1$
String message= FilterMessages.getFormattedString("FilterDescriptor.filterCreationError.message", getId()); //$NON-NLS-1$
ErrorDialog.openError(shell, title, message, status);
}
JavaPlugin.log(status);
}
//---- XML Attribute accessors ---------------------------------------------
/**
* Returns the filter's id.
* <p>
* This attribute is mandatory for custom filters.
* The ID for pattern filters is
* PATTERN_FILTER_ID_PREFIX plus the pattern itself.
* </p>
*/
public String getId() {
if (isPatternFilter()) {
String viewId= getViewId();
if (viewId == null)
return PATTERN_FILTER_ID_PREFIX + getPattern();
else
return viewId + PATTERN_FILTER_ID_PREFIX + getPattern();
} else
return fElement.getAttribute(ID_ATTRIBUTE);
}
/**
* Returns the filter's name.
* <p>
* If the name of a pattern filter is missing
* then the pattern is used as its name.
* </p>
*/
public String getName() {
String name= fElement.getAttribute(NAME_ATTRIBUTE);
if (name == null && isPatternFilter())
name= getPattern();
return name;
}
/**
* Returns the filter's pattern.
*
* @return the pattern string or <code>null</code> if it's not a pattern filter
*/
public String getPattern() {
return fElement.getAttribute(PATTERN_ATTRIBUTE);
}
/**
* Returns the filter's viewId.
*
* @return the view ID or <code>null</code> if the filter is for all views
*/
public String getViewId() {
return fElement.getAttribute(VIEW_ID_ATTRIBUTE);
}
/**
* Returns the filter's description.
*
* @return the description or <code>null</code> if no description is provided
*/
public String getDescription() {
String description= fElement.getAttribute(DESCRIPTION_ATTRIBUTE);
if (description == null)
description= ""; //$NON-NLS-1$
return description;
}
/**
* @return <code>true</code> if this filter is a custom filter.
*/
public boolean isPatternFilter() {
return getPattern() != null;
}
/**
* @return <code>true</code> if this filter is a pattern filter.
*/
public boolean isCustomFilter() {
return fElement.getAttribute(CLASS_ATTRIBUTE) != null;
}
/**
* Returns <code>true</code> if the filter
* is initially enabled.
*
* This attribute is optional and defaults to <code>true</code>.
*/
public boolean isEnabled() {
String strVal= fElement.getAttribute(ENABLED_ATTRIBUTE);
if (strVal == null)
// backward compatibility
strVal= fElement.getAttribute(SELECTED_ATTRIBUTE);
return strVal == null || Boolean.valueOf(strVal).booleanValue();
}
/*
* Implements a method from IComparable
*/
public int compareTo(Object o) {
if (o instanceof FilterDescriptor)
return Collator.getInstance().compare(getName(), ((FilterDescriptor)o).getName());
else
return Integer.MIN_VALUE;
}
//---- initialization ---------------------------------------------------
/**
* Creates the filter descriptors.
*/
private static FilterDescriptor[] createFilterDescriptors(IConfigurationElement[] elements) {
List result= new ArrayList(5);
Set descIds= new HashSet(5);
for (int i= 0; i < elements.length; i++) {
IConfigurationElement element= elements[i];
if (FILTER_TAG.equals(element.getName())) {
FilterDescriptor desc= new FilterDescriptor(element);
if (!descIds.contains(desc.getId())) {
result.add(desc);
descIds.add(desc.getId());
}
}
}
Collections.sort(result);
return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]);
}
}
|
37,214 |
Bug 37214 quick fix "add unimplemented methods" failes for anonymous type decl. [quick fix]
|
build 200304291456 1. in a Java editor, create the following class: import java.util.Collections; import java.util.List; public class Main { private void foo() { Collections.sort(new List() { <--- cursor }); } } 2. the anonymous class gets the error and quick fix markers 3. application of the quick fix "add unimplemented methods" failes with an uncaught ClassCastException: java.lang.ClassCastException at org.eclipse.jdt.internal.corext.dom.ASTNodeFactory.newType (ASTNodeFactory.java:74) at org.eclipse.jdt.internal.ui.text.correction.UnimplementedMethodsCompletionPropos al.createNewMethodDeclaration(UnimplementedMethodsCompletionProposal.java:99) at org.eclipse.jdt.internal.ui.text.correction.UnimplementedMethodsCompletionPropos al.getRewrite(UnimplementedMethodsCompletionProposal.java:85) at org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal.createC ompilationUnitChange(ASTRewriteCorrectionProposal.java:52) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getChange (CUCorrectionProposal.java:85) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getCompilationU nitChange(CUCorrectionProposal.java:225) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getAdditionalPr oposalInfo(CUCorrectionProposal.java:101) at org.eclipse.jface.text.contentassist.AdditionalInfoController.computeInformation (AdditionalInfoController.java:207) at org.eclipse.jface.text.AbstractInformationControlManager.doShowInformation (AbstractInformationControlManager.java:605) at org.eclipse.jface.text.AbstractInformationControlManager.showInformation (AbstractInformationControlManager.java:595) at org.eclipse.jface.text.contentassist.AdditionalInfoController$1.run (AdditionalInfoController.java:164) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:98) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1910) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1644) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1402) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1385) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
12131fb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-05T16:32:11Z | 2003-05-05T13:06:40Z |
org.eclipse.jdt.ui/core
| |
37,214 |
Bug 37214 quick fix "add unimplemented methods" failes for anonymous type decl. [quick fix]
|
build 200304291456 1. in a Java editor, create the following class: import java.util.Collections; import java.util.List; public class Main { private void foo() { Collections.sort(new List() { <--- cursor }); } } 2. the anonymous class gets the error and quick fix markers 3. application of the quick fix "add unimplemented methods" failes with an uncaught ClassCastException: java.lang.ClassCastException at org.eclipse.jdt.internal.corext.dom.ASTNodeFactory.newType (ASTNodeFactory.java:74) at org.eclipse.jdt.internal.ui.text.correction.UnimplementedMethodsCompletionPropos al.createNewMethodDeclaration(UnimplementedMethodsCompletionProposal.java:99) at org.eclipse.jdt.internal.ui.text.correction.UnimplementedMethodsCompletionPropos al.getRewrite(UnimplementedMethodsCompletionProposal.java:85) at org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal.createC ompilationUnitChange(ASTRewriteCorrectionProposal.java:52) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getChange (CUCorrectionProposal.java:85) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getCompilationU nitChange(CUCorrectionProposal.java:225) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getAdditionalPr oposalInfo(CUCorrectionProposal.java:101) at org.eclipse.jface.text.contentassist.AdditionalInfoController.computeInformation (AdditionalInfoController.java:207) at org.eclipse.jface.text.AbstractInformationControlManager.doShowInformation (AbstractInformationControlManager.java:605) at org.eclipse.jface.text.AbstractInformationControlManager.showInformation (AbstractInformationControlManager.java:595) at org.eclipse.jface.text.contentassist.AdditionalInfoController$1.run (AdditionalInfoController.java:164) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:98) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1910) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1644) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1402) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1385) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
12131fb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-05T16:32:11Z | 2003-05-05T13:06:40Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.java
| |
27,762 |
Bug 27762 Enhancment of "Add return statement" quickfix
|
It would be nice if "Add return statement" would insert/suggest the best matched variable that should be returned. e.g. public Dimension getPreferredSize() { Dimension dim = inlined.getPreferredSize(); Dimension myDim = new Dimension(); myDim.setSize(inlined.getWidth()*1.5, inlined.getHeight()*1.5); } Here the last line the Quick Fix "Add return statement" is possible - but it inserts "return null;" at the end. It could just as well insert "return myDim;" Maybe has it as an second quick fix, so the quick fix options would be: Add return null statement Add return myDim statement
|
resolved fixed
|
a681a86
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T08:32:09Z | 2002-12-05T14:53:20Z |
org.eclipse.jdt.ui/core
| |
27,762 |
Bug 27762 Enhancment of "Add return statement" quickfix
|
It would be nice if "Add return statement" would insert/suggest the best matched variable that should be returned. e.g. public Dimension getPreferredSize() { Dimension dim = inlined.getPreferredSize(); Dimension myDim = new Dimension(); myDim.setSize(inlined.getWidth()*1.5, inlined.getHeight()*1.5); } Here the last line the Quick Fix "Add return statement" is possible - but it inserts "return null;" at the end. It could just as well insert "return myDim;" Maybe has it as an second quick fix, so the quick fix options would be: Add return null statement Add return myDim statement
|
resolved fixed
|
a681a86
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T08:32:09Z | 2002-12-05T14:53:20Z |
extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java
| |
27,762 |
Bug 27762 Enhancment of "Add return statement" quickfix
|
It would be nice if "Add return statement" would insert/suggest the best matched variable that should be returned. e.g. public Dimension getPreferredSize() { Dimension dim = inlined.getPreferredSize(); Dimension myDim = new Dimension(); myDim.setSize(inlined.getWidth()*1.5, inlined.getHeight()*1.5); } Here the last line the Quick Fix "Add return statement" is possible - but it inserts "return null;" at the end. It could just as well insert "return myDim;" Maybe has it as an second quick fix, so the quick fix options would be: Add return null statement Add return myDim statement
|
resolved fixed
|
a681a86
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T08:32:09Z | 2002-12-05T14:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/MissingReturnTypeCorrectionProposal.java
| |
27,762 |
Bug 27762 Enhancment of "Add return statement" quickfix
|
It would be nice if "Add return statement" would insert/suggest the best matched variable that should be returned. e.g. public Dimension getPreferredSize() { Dimension dim = inlined.getPreferredSize(); Dimension myDim = new Dimension(); myDim.setSize(inlined.getWidth()*1.5, inlined.getHeight()*1.5); } Here the last line the Quick Fix "Add return statement" is possible - but it inserts "return null;" at the end. It could just as well insert "return myDim;" Maybe has it as an second quick fix, so the quick fix options would be: Add return null statement Add return myDim statement
|
resolved fixed
|
a681a86
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T08:32:09Z | 2002-12-05T14:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReturnTypeSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
*/
public class ReturnTypeSubProcessor {
private static class ReturnStatementCollector extends ASTVisitor {
private ArrayList fResult= new ArrayList();
public Iterator returnStatements() {
return fResult.iterator();
}
public ITypeBinding getTypeBinding(AST ast) {
boolean couldBeObject= false;
for (int i= 0; i < fResult.size(); i++) {
ReturnStatement node= (ReturnStatement) fResult.get(i);
Expression expr= node.getExpression();
if (expr != null) {
ITypeBinding binding= ASTResolving.normalizeTypeBinding(expr.resolveTypeBinding());
if (binding != null) {
return binding;
} else {
couldBeObject= true;
}
} else {
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
}
if (couldBeObject) {
return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
public boolean visit(ReturnStatement node) {
fResult.add(node);
return false;
}
public boolean visit(AnonymousClassDeclaration node) {
return false;
}
public boolean visit(TypeDeclaration node) {
return false;
}
}
public static void addMethodWithConstrNameProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode instanceof MethodDeclaration) {
MethodDeclaration declaration= (MethodDeclaration) selectedNode;
ASTRewrite rewrite= new ASTRewrite(declaration);
rewrite.markAsRemoved(declaration.getReturnType());
String label= CorrectionMessages.getString("ReturnTypeSubProcessor.constrnamemethod.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addVoidMethodReturnsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration && selectedNode.getNodeType() == ASTNode.RETURN_STATEMENT) {
ReturnStatement returnStatement= (ReturnStatement) selectedNode;
Expression expr= returnStatement.getExpression();
if (expr != null) {
ITypeBinding binding= ASTResolving.normalizeTypeBinding(expr.resolveTypeBinding());
if (binding == null) {
binding= selectedNode.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
String label= CorrectionMessages.getFormattedString("ReturnTypeSubProcessor.voidmethodreturns.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
String returnTypeName= proposal.addImport(binding);
Type newReturnType= ASTNodeFactory.newType(astRoot.getAST(), returnTypeName);
if (methodDeclaration.isConstructor()) {
MethodDeclaration modifiedNode= astRoot.getAST().newMethodDeclaration();
modifiedNode.setModifiers(methodDeclaration.getModifiers()); // no changes
modifiedNode.setExtraDimensions(methodDeclaration.getExtraDimensions()); // no changes
modifiedNode.setConstructor(false);
rewrite.markAsModified(methodDeclaration, modifiedNode);
methodDeclaration.setReturnType(newReturnType);
rewrite.markAsInserted(newReturnType);
} else {
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
ASTRewrite rewrite= new ASTRewrite(decl);
rewrite.markAsRemoved(returnStatement);
String label= CorrectionMessages.getString("ReturnTypeSubProcessor.removereturn.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addMissingReturnTypeProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ReturnStatementCollector eval= new ReturnStatementCollector();
decl.accept(eval);
ITypeBinding typeBinding= eval.getTypeBinding(decl.getAST());
typeBinding= ASTResolving.normalizeTypeBinding(typeBinding);
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
AST ast= astRoot.getAST();
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 2, image); //$NON-NLS-1$
Type type;
String typeName;
if (typeBinding != null) {
typeName= proposal.addImport(typeBinding);
type= ASTNodeFactory.newType(ast, typeName);
} else {
typeName= "void"; //$NON-NLS-1$
type= ast.newPrimitiveType(PrimitiveType.VOID);
}
proposal.setDisplayName(CorrectionMessages.getFormattedString("ReturnTypeSubProcessor.missingreturntype.description", typeName)); //$NON-NLS-1$
rewrite.markAsInserted(type);
methodDeclaration.setReturnType(type);
MethodDeclaration modifiedNode= ast.newMethodDeclaration();
modifiedNode.setModifiers(methodDeclaration.getModifiers()); // no changes
modifiedNode.setExtraDimensions(methodDeclaration.getExtraDimensions()); // no changes
modifiedNode.setConstructor(false);
rewrite.markAsModified(methodDeclaration, modifiedNode);
proposal.ensureNoModifications();
proposals.add(proposal);
// change to constructor
ASTNode parentType= ASTResolving.findParentType(decl);
if (parentType instanceof TypeDeclaration) {
String constructorName= ((TypeDeclaration) parentType).getName().getIdentifier();
ASTNode nameNode= methodDeclaration.getName();
String label= CorrectionMessages.getFormattedString("ReturnTypeSubProcessor.wrongconstructorname.description", constructorName); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, 1));
}
}
}
/**
* Method addMissingReturnStatementProposals.
* @param context
* @param proposals
*/
public static void addMissingReturnStatementProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
AST ast= selectedNode.getAST();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDecl= (MethodDeclaration) decl;
if (selectedNode instanceof ReturnStatement) {
ReturnStatement returnStatement= (ReturnStatement) selectedNode;
if (returnStatement.getExpression() == null) {
ASTRewrite rewrite= new ASTRewrite(methodDecl);
Expression expression= ASTNodeFactory.newDefaultExpression(ast, methodDecl.getReturnType(), methodDecl.getExtraDimensions());
if (expression != null) {
returnStatement.setExpression(expression);
rewrite.markAsInserted(expression);
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
String label= CorrectionMessages.getString("ReturnTypeSubProcessor.changereturnstatement.description"); //$NON-NLS-1$
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 3, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
} else {
Block block= methodDecl.getBody();
if (block == null) {
return;
}
ASTRewrite rewrite= new ASTRewrite(methodDecl);
List statements= block.statements();
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, methodDecl.getReturnType(), methodDecl.getExtraDimensions()));
statements.add(returnStatement);
rewrite.markAsInserted(returnStatement);
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
String label= CorrectionMessages.getString("ReturnTypeSubProcessor.addreturnstatement.description"); //$NON-NLS-1$
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 3, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
}
|
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
org.eclipse.jdt.ui/core
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddGetterSetterOperation.java
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
org.eclipse.jdt.ui/ui
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeSignatureInputPage.java
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
org.eclipse.jdt.ui/ui
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ConvertAnonymousToNestedInputPage.java
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
org.eclipse.jdt.ui/ui
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/IVisibilityChangeListener.java
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
org.eclipse.jdt.ui/ui
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/PromoteTempInputPage.java
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
org.eclipse.jdt.ui/ui
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/VisibilityControlUtil.java
| |
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/SelectionConverter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.actions;
import java.util.Iterator;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class SelectionConverter {
private static final IJavaElement[] EMPTY_RESULT= new IJavaElement[0];
private SelectionConverter() {
// no instance
}
/**
* Converts the selection provided by the given part into a structured selection.
* The following conversion rules are used:
* <ul>
* <li><code>part instanceof JavaEditor</code>: returns a structured selection
* using code resolve to convert the editor's text selection.</li>
* <li><code>part instanceof IWorkbenchPart</code>: returns the part's selection
* if it is a structured selection.</li>
* <li><code>default</code>: returns an empty structured selection.</li>
* </ul>
*/
public static IStructuredSelection getStructuredSelection(IWorkbenchPart part) throws JavaModelException {
if (part instanceof JavaEditor)
return new StructuredSelection(codeResolve((JavaEditor)part));
ISelectionProvider provider= part.getSite().getSelectionProvider();
if (provider != null) {
ISelection selection= provider.getSelection();
if (selection instanceof IStructuredSelection)
return (IStructuredSelection)selection;
}
return StructuredSelection.EMPTY;
}
/**
* Converts the given structured selection into an array of Java elements.
* An empty array is returned if one of the elements stored in the structured
* selection is not of tupe <code>IJavaElement</code>
*/
public static IJavaElement[] getElements(IStructuredSelection selection) {
if (!selection.isEmpty()) {
IJavaElement[] result= new IJavaElement[selection.size()];
int i= 0;
for (Iterator iter= selection.iterator(); iter.hasNext(); i++) {
Object element= (Object) iter.next();
if (!(element instanceof IJavaElement))
return EMPTY_RESULT;
result[i]= (IJavaElement)element;
}
return result;
}
return EMPTY_RESULT;
}
public static boolean canOperateOn(JavaEditor editor) {
if (editor == null)
return false;
return getInput(editor) != null;
}
/**
* Converts the text selection provided by the given editor into an array of
* Java elements. If the selection doesn't cover a Java element and the selection's
* length is greater than 0 the methods returns the editor's input element.
*/
public static IJavaElement[] codeResolveOrInput(JavaEditor editor) throws JavaModelException {
IJavaElement input= getInput(editor);
ITextSelection selection= (ITextSelection)editor.getSelectionProvider().getSelection();
IJavaElement[] result= codeResolve(input, selection);
if (result.length == 0) {
result= new IJavaElement[] {input};
}
return result;
}
public static IJavaElement[] codeResolveOrInputHandled(JavaEditor editor, Shell shell, String title) {
try {
return codeResolveOrInput(editor);
} catch(JavaModelException e) {
ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$
}
return null;
}
/**
* Converts the text selection provided by the given editor a Java element by
* asking the user if code reolve returned more than one result. If the selection
* doesn't cover a Java element and the selection's length is greater than 0 the
* methods returns the editor's input element.
*/
public static IJavaElement codeResolveOrInput(JavaEditor editor, Shell shell, String title, String message) throws JavaModelException {
IJavaElement[] elements= codeResolveOrInput(editor);
if (elements == null || elements.length == 0)
return null;
IJavaElement candidate= elements[0];
if (elements.length > 1) {
candidate= OpenActionUtil.selectJavaElement(elements, shell, title, message);
}
return candidate;
}
public static IJavaElement codeResolveOrInputHandled(JavaEditor editor, Shell shell, String title, String message) {
try {
return codeResolveOrInput(editor, shell, title, message);
} catch (JavaModelException e) {
ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolveOrInput_failed")); //$NON-NLS-1$
}
return null;
}
public static IJavaElement[] codeResolve(JavaEditor editor) throws JavaModelException {
return codeResolve(getInput(editor), (ITextSelection)editor.getSelectionProvider().getSelection());
}
/**
* Converts the text selection provided by the given editor a Java element by
* asking the user if code reolve returned more than one result. If the selection
* doesn't cover a Java element <code>null</code> is returned.
*/
public static IJavaElement codeResolve(JavaEditor editor, Shell shell, String title, String message) throws JavaModelException {
IJavaElement[] elements= codeResolve(editor);
if (elements == null || elements.length == 0)
return null;
IJavaElement candidate= elements[0];
if (elements.length > 1) {
candidate= OpenActionUtil.selectJavaElement(elements, shell, title, message);
}
return candidate;
}
public static IJavaElement[] codeResolveHandled(JavaEditor editor, Shell shell, String title) {
try {
return codeResolve(editor);
} catch (JavaModelException e) {
ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$
}
return null;
}
public static IJavaElement getElementAtOffset(JavaEditor editor) throws JavaModelException {
return getElementAtOffset(getInput(editor), (ITextSelection)editor.getSelectionProvider().getSelection());
}
public static IType getTypeAtOffset(JavaEditor editor) throws JavaModelException {
IJavaElement element= SelectionConverter.getElementAtOffset(editor);
IType type= (IType)element.getAncestor(IJavaElement.TYPE);
if (type == null) {
ICompilationUnit unit= SelectionConverter.getInputAsCompilationUnit(editor);
if (unit != null)
type= unit.findPrimaryType();
}
return type;
}
public static IJavaElement getInput(JavaEditor editor) {
if (editor == null)
return null;
IEditorInput input= editor.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(input);
}
public static ICompilationUnit getInputAsCompilationUnit(JavaEditor editor) {
Object editorInput= SelectionConverter.getInput(editor);
if (editorInput instanceof ICompilationUnit)
return (ICompilationUnit)editorInput;
else
return null;
}
private static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection) throws JavaModelException {
if (input instanceof ICodeAssist) {
IJavaElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset(), selection.getLength());
if (elements != null && elements.length > 0)
return elements;
}
return EMPTY_RESULT;
}
private static IJavaElement getElementAtOffset(IJavaElement input, ITextSelection selection) throws JavaModelException {
if (input instanceof ICompilationUnit) {
ICompilationUnit cunit= (ICompilationUnit)input;
if (cunit.isWorkingCopy()) {
synchronized (cunit) {
cunit.reconcile();
}
}
IJavaElement ref= cunit.getElementAt(selection.getOffset());
if (ref == null)
return input;
else
return ref;
} else if (input instanceof IClassFile) {
IJavaElement ref= ((IClassFile)input).getElementAt(selection.getOffset());
if (ref == null)
return input;
else
return ref;
}
return null;
}
}
|
4,793 |
Bug 4793 Canvas.scroll not working when source y around 65536 (1GIXDPD)
|
Run the code below and press a key. You will see one pixel line of cheese at the top or bottom depending on which sourceY is used. To make this more obvious divide height by 2. This works fine on NT. import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class PR_1GIXDPD { static boolean scrolled = false; public static void main(String[] args) { final Shell shell = new Shell(); shell.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { Rectangle clientArea = shell.getClientArea(); int height = clientArea.height; int sourceY = 65536 - (height - 3); // int sourceY = 65536 + (height - 1); // does not work if 65536 - (height - 2) < sourceY < 65536 + height shell.scroll(0, 0, 0, sourceY, clientArea.width, clientArea.height, true); scrolled = true; System.out.println(clientArea); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { int lineHeight = 15; if (scrolled == false) { for (int i = 0; i < event.y + event.height; i += lineHeight) { event.gc.drawText("Line " + i, 0, i); } } } }); shell.open(); Display display = shell.getDisplay (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } } NOTES:
|
resolved wontfix
|
5b88062
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-06T16:02:34Z | 2001-10-11T17:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddGetterSetterAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Creates getter and setter methods for a type's fields. Opens a dialog
* with a list of fields for which a setter or getter can be generated.
* User is able to check or uncheck items before setters or getters
* are generated.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IField</code> or <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddGetterSetterAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private static final String dialogTitle= ActionMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$
/**
* Creates a new <code>AddGetterSetterAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public AddGetterSetterAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddGetterSetterAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddGetterSetterAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddGetterSetterAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GETTERSETTER_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public AddGetterSetterAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null);
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(canEnable(selection));
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
setEnabled(false);
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
try {
IField[] selectedFields= getSelectedFields(selection);
if (canEnableOn(selectedFields)){
run(selectedFields[0].getDeclaringType(), selectedFields, false);
return;
}
Object firstElement= selection.getFirstElement();
if (firstElement instanceof IType)
run((IType)firstElement, new IField[0], false);
else if (firstElement instanceof ICompilationUnit)
run(((ICompilationUnit) firstElement).findPrimaryType(), new IField[0], false);
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
}
}
private boolean canEnable(IStructuredSelection selection) throws JavaModelException{
if (canEnableOn(getSelectedFields(selection)))
return true;
if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType))
return canEnableOn((IType)selection.getFirstElement());
if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
return canEnableOn(((ICompilationUnit)selection.getFirstElement()).findPrimaryType());
return false;
}
private static boolean canEnableOn(IType type) throws JavaModelException {
if (type == null)
return false;
if (type.getFields().length == 0)
return false;
if (type.getCompilationUnit() == null)
return false;
return true;
}
private static boolean canEnableOn(IField[] fields) throws JavaModelException {
return fields != null && fields.length > 0;
}
private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
if (!ElementValidator.check(type, getShell(), dialogTitle, editor))
return;
if (!ActionUtil.isProcessable(getShell(), type))
return;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ILabelProvider lp= new AddGetterSetterLabelProvider();
Map entries= createGetterSetterMapping(type, settings);
if (entries.isEmpty()){
MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGettSetterAction.typeContainsNoFields.message")); //$NON-NLS-1$
return;
}
ITreeContentProvider cp= new AddGetterSetterContentProvider(entries);
CheckedTreeSelectionDialog dialog= new CheckedTreeSelectionDialog(getShell(), lp, cp);
dialog.setSorter(new JavaElementSorter());
dialog.setTitle(dialogTitle);
String message= ActionMessages.getString("AddGetterSetterAction.dialog.title");//$NON-NLS-1$
dialog.setMessage(message);
dialog.setValidator(createValidator());
dialog.setContainerMode(true);
dialog.setSize(60, 18);
dialog.setInput(type);
dialog.setExpandedElements(type.getFields());
dialog.setInitialSelections(preselected);
dialog.open();
Object[] result= dialog.getResult();
if (result == null)
return;
IField[] getterFields= getGetterFields(result);
IField[] setterFields= getSetterFields(result);
generate(getterFields, setterFields);
}
private static ISelectionStatusValidator createValidator() {
return new ISelectionStatusValidator(){
public IStatus validate(Object[] selection) {
int count= countSelectedMethods(selection);
if (count == 0)
return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
if (count == 1)
return new StatusInfo(IStatus.INFO, ActionMessages.getString("AddGetterSetterAction.one_selected")); //$NON-NLS-1$
String message= ActionMessages.getFormattedString("AddGetterSetterAction.methods_selected", String.valueOf(count));//$NON-NLS-1$
return new StatusInfo(IStatus.INFO, message);
}
private int countSelectedMethods(Object[] selection){
int count= 0;
for (int i = 0; i < selection.length; i++) {
if (selection[i] instanceof GetterSetterEntry)
count++;
}
return count;
}
};
}
private static IField[] getGetterFields(Object[] result){
Collection list= new ArrayList(0);
for (int i = 0; i < result.length; i++) {
Object each= result[i];
if ((each instanceof GetterSetterEntry)){
GetterSetterEntry entry= (GetterSetterEntry)each;
if (entry.isGetterEntry)
list.add(entry.field);
}
}
return (IField[]) list.toArray(new IField[list.size()]);
}
private static IField[] getSetterFields(Object[] result){
Collection list= new ArrayList(0);
for (int i = 0; i < result.length; i++) {
Object each= result[i];
if ((each instanceof GetterSetterEntry)){
GetterSetterEntry entry= (GetterSetterEntry)each;
if (! entry.isGetterEntry)
list.add(entry.field);
}
}
return (IField[]) list.toArray(new IField[list.size()]);
}
private void generate(IField[] getterFields, IField[] setterFields) throws CoreException{
if (getterFields.length == 0 && setterFields.length == 0)
return;
ICompilationUnit cu= null;
if (getterFields.length != 0)
cu= getterFields[0].getCompilationUnit();
else
cu= setterFields[0].getCompilationUnit();
//open the editor, forces the creation of a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
IField[] workingCopyGetterFields= getWorkingCopyFields(getterFields);
IField[] workingCopySetterFields= getWorkingCopyFields(setterFields);
if (workingCopyGetterFields != null && workingCopySetterFields != null)
run(workingCopyGetterFields, workingCopySetterFields, editor);
}
private IField[] getWorkingCopyFields(IField[] fields) throws CoreException{
if (fields.length == 0)
return new IField[0];
ICompilationUnit cu= fields[0].getCompilationUnit();
ICompilationUnit workingCopyCU;
IField[] workingCopyFields;
if (cu.isWorkingCopy()) {
workingCopyCU= cu;
workingCopyFields= fields;
} else {
workingCopyCU= EditorUtility.getWorkingCopy(cu);
if (workingCopyCU == null) {
showError(ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
return null;
}
workingCopyFields= new IField[fields.length];
for (int i= 0; i < fields.length; i++) {
IField field= fields[i];
IField workingCopyField= (IField) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, field);
if (workingCopyField == null) {
showError(ActionMessages.getFormattedString("AddGetterSetterAction.error.fieldNotExisting", field.getElementName())); //$NON-NLS-1$
return null;
}
workingCopyFields[i]= workingCopyField;
}
}
return workingCopyFields;
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
try {
IJavaElement input= SelectionConverter.getInput(fEditor);
if (!ActionUtil.isProcessable(getShell(), input))
return;
IJavaElement[] elements= SelectionConverter.codeResolve(fEditor);
if (elements.length == 1 && (elements[0] instanceof IField)) {
IField field= (IField)elements[0];
run(field.getDeclaringType(), new IField[] {field}, true);
return;
}
IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
if (element != null){
IType type= (IType)element.getAncestor(IJavaElement.TYPE);
if (type != null){
if (type.getFields().length > 0){
run(type, new IField[0], true);
return;
}
}
}
MessageDialog.openInformation(getShell(), dialogTitle,
ActionMessages.getString("AddGetterSetterAction.not_applicable")); //$NON-NLS-1$
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
}
}
//---- Helpers -------------------------------------------------------------------
private void run(IField[] getterFields, IField[] setterFields, IEditorPart editor) {
IRewriteTarget target= (IRewriteTarget) editor.getAdapter(IRewriteTarget.class);
if (target != null) {
target.beginCompoundChange();
}
try {
AddGetterSetterOperation op= createAddGetterSetterOperation(getterFields, setterFields);
new ProgressMonitorDialog(getShell()).run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] createdMethods= op.getCreatedAccessors();
if (createdMethods.length > 0) {
EditorUtility.revealInEditor(editor, createdMethods[0]);
}
} catch (InvocationTargetException e) {
String message= ActionMessages.getString("AddGetterSetterAction.error.actionfailed"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), dialogTitle, message);
} catch (InterruptedException e) {
// operation cancelled
} finally {
if (target != null) {
target.endCompoundChange();
}
}
}
private AddGetterSetterOperation createAddGetterSetterOperation(IField[] getterFields, IField[] setterFields) {
IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery();
IRequestQuery skipReplaceQuery= skipReplaceQuery();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
return new AddGetterSetterOperation(getterFields, setterFields, settings, skipSetterForFinalQuery, skipReplaceQuery);
}
private IRequestQuery skipSetterForFinalQuery() {
return new IRequestQuery() {
public int doQuery(IMember field) {
// Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19367
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.YES_ALL, IRequestQuery.NO, IRequestQuery.CANCEL};
String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL};
String fieldName= JavaElementLabels.getElementLabel(field, 0);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipSetterForFinalDialog.message", fieldName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private IRequestQuery skipReplaceQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
String skipLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skip.label"); //$NON-NLS-1$
String replaceLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.replace.label"); //$NON-NLS-1$
String skipAllLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skipAll.label"); //$NON-NLS-1$
String[] options= { skipLabel, replaceLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipExistingDialog.message", methodName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private int showQueryDialog(final String message, final String[] buttonLabels, int[] returnCodes) {
final Shell shell= getShell();
if (shell == null) {
JavaPlugin.logErrorMessage("AddGetterSetterAction.showQueryDialog: No active shell found"); //$NON-NLS-1$
return IRequestQuery.CANCEL;
}
final int[] result= { MessageDialog.CANCEL };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= ActionMessages.getString("AddGetterSetterAction.QueryDialog.title"); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, buttonLabels, 0);
result[0]= dialog.open();
}
});
int returnVal= result[0];
return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
}
private void showError(String message) {
MessageDialog.openError(getShell(), dialogTitle, message);
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields(IStructuredSelection selection) {
List elements= selection.toList();
int nElements= elements.size();
if (nElements > 0) {
IField[] res= new IField[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IField) {
IField fld= (IField)curr;
if (i == 0) {
// remember the cu of the first element
cu= fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no setters/getters for interfaces
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i]= fld;
} else {
return null;
}
}
return res;
}
return null;
}
private static class GetterSetterEntry {
public final IField field;
public final boolean isGetterEntry;
GetterSetterEntry(IField field, boolean isGetterEntry){
this.field= field;
this.isGetterEntry= isGetterEntry;
}
}
private static class AddGetterSetterLabelProvider extends JavaElementLabelProvider {
AddGetterSetterLabelProvider() {
}
/*
* @see ILabelProvider#getText(Object)
*/
public String getText(Object element) {
if (element instanceof GetterSetterEntry) {
GetterSetterEntry entry= (GetterSetterEntry) element;
try {
if (entry.isGetterEntry) {
return GetterSetterUtil.getGetterName(entry.field, null) + "()"; //$NON-NLS-1$
} else {
return GetterSetterUtil.getSetterName(entry.field, null) + '(' + Signature.getSimpleName(Signature.toString(entry.field.getTypeSignature())) + ')';
}
} catch (JavaModelException e) {
return ""; //$NON-NLS-1$
}
}
return super.getText(element);
}
/*
* @see ILabelProvider#getImage(Object)
*/
public Image getImage(Object element) {
if (element instanceof GetterSetterEntry) {
int flags= 0;
try {
flags= ((GetterSetterEntry) element).field.getFlags();
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
int adornmentFlags= Flags.isStatic(flags) ? JavaElementImageDescriptor.STATIC : 0;
desc= new JavaElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE);
return JavaPlugin.getImageDescriptorRegistry().get(desc);
}
return super.getImage(element);
}
}
/**
* @return map IField -> GetterSetterEntry[]
*/
private static Map createGetterSetterMapping(IType type, CodeGenerationSettings settings) throws JavaModelException{
IField[] fields= type.getFields();
Map result= new HashMap();
for (int i= 0; i < fields.length; i++) {
List l= new ArrayList(2);
if (GetterSetterUtil.getGetter(fields[i]) == null)
l.add(new GetterSetterEntry(fields[i], true));
if (GetterSetterUtil.getSetter(fields[i]) == null)
l.add(new GetterSetterEntry(fields[i], false));
if (! l.isEmpty())
result.put(fields[i], (GetterSetterEntry[]) l.toArray(new GetterSetterEntry[l.size()]));
}
return result;
}
private static class AddGetterSetterContentProvider implements ITreeContentProvider{
private static final Object[] EMPTY= new Object[0];
private Map fGetterSetterEntries;
public AddGetterSetterContentProvider(Map entries) throws JavaModelException {
fGetterSetterEntries= entries;
}
/*
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IField)
return (Object[])fGetterSetterEntries.get(parentElement);
return EMPTY;
}
/*
* @see ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
if (element instanceof IMember)
return ((IMember)element).getDeclaringType();
if (element instanceof GetterSetterEntry)
return ((GetterSetterEntry)element).field;
return null;
}
/*
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return fGetterSetterEntries.keySet().toArray();
}
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
fGetterSetterEntries.clear();
fGetterSetterEntries= null;
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
}
|
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
org.eclipse.jdt.ui/core
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/CalleeAnalyzerVisitor.java
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
org.eclipse.jdt.ui/core
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/CalleeMethodWrapper.java
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
org.eclipse.jdt.ui/core
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/CallerMethodWrapper.java
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
org.eclipse.jdt.ui/core
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/MethodReferencesSearchCollector.java
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
org.eclipse.jdt.ui/core
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/MethodWrapper.java
| |
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyContentProvider.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
public class CallHierarchyContentProvider implements ITreeContentProvider {
private final static Object[] EMPTY_ARRAY = new Object[0];
private TreeViewer fViewer;
public CallHierarchyContentProvider() {
super();
}
/**
* @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
*/
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof TreeRoot) {
TreeRoot dummyRoot = (TreeRoot) parentElement;
return new Object[] { dummyRoot.getRoot() };
} else if (parentElement instanceof MethodWrapper) {
MethodWrapper methodWrapper = ((MethodWrapper) parentElement);
if (shouldStopTraversion(methodWrapper)) {
return EMPTY_ARRAY;
} else {
return methodWrapper.getCalls();
}
}
return EMPTY_ARRAY;
}
private boolean shouldStopTraversion(MethodWrapper methodWrapper) {
return (methodWrapper.getLevel() > CallHierarchyUI.getDefault().getMaxCallDepth()) || methodWrapper.isRecursive();
}
/**
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
/**
* @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
*/
public Object getParent(Object element) {
if (element instanceof MethodWrapper) {
return ((MethodWrapper) element).getParent();
}
return null;
}
/**
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {}
/**
* @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
*/
public boolean hasChildren(Object element) {
if (element == TreeRoot.EMPTY_ROOT) {
return false;
}
// Only methods can have subelements, so there's no need to fool the user into believing that there is more
if (element instanceof MethodWrapper) {
MethodWrapper methodWrapper= (MethodWrapper) element;
if (methodWrapper.getMember().getElementType() != IJavaElement.METHOD) {
return false;
}
if (shouldStopTraversion(methodWrapper)) {
return false;
}
}
return true;
}
/**
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.fViewer = (TreeViewer) viewer;
}
}
|
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.corext.callhierarchy.CallHierarchy;
import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
/**
* This is the main view for the callers plugin. It builds a tree of callers/callees
* and allows the user to double click an entry to go to the selected method.
*
*/
public class CallHierarchyViewPart extends ViewPart implements ICallHierarchyViewPart, IDoubleClickListener,
ISelectionChangedListener {
private CallHierarchyViewSiteAdapter fViewSiteAdapter;
private CallHierarchyViewAdapter fViewAdapter;
private static final String DIALOGSTORE_VIEWORIENTATION = "CallHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String DIALOGSTORE_CALL_MODE = "CallHierarchyViewPart.call_mode"; //$NON-NLS-1$
private static final String TAG_ORIENTATION = "orientation"; //$NON-NLS-1$
private static final String TAG_CALL_MODE = "call_mode"; //$NON-NLS-1$
private static final String TAG_IMPLEMENTORS_MODE = "implementors_mode"; //$NON-NLS-1$
private static final String TAG_RATIO = "ratio"; //$NON-NLS-1$
static final int VIEW_ORIENTATION_VERTICAL = 0;
static final int VIEW_ORIENTATION_HORIZONTAL = 1;
static final int VIEW_ORIENTATION_SINGLE = 2;
static final int CALL_MODE_CALLERS = 0;
static final int CALL_MODE_CALLEES = 1;
static final int IMPLEMENTORS_ENABLED = 0;
static final int IMPLEMENTORS_DISABLED = 1;
static final String GROUP_SEARCH_SCOPE = "MENU_SEARCH_SCOPE"; //$NON-NLS-1$
static final String ID_CALL_HIERARCHY = "org.eclipse.jdt.callhierarchy.view"; //$NON-NLS-1$
private static final String GROUP_FOCUS = "group.focus"; //$NON-NLS-1$
private static final int PAGE_EMPTY = 0;
private static final int PAGE_VIEWER = 1;
private Label fNoHierarchyShownLabel;
private PageBook fPagebook;
private IDialogSettings fDialogSettings;
private int fCurrentOrientation;
private int fCurrentCallMode;
private int fCurrentImplementorsMode;
private MethodWrapper fCalleeRoot;
private MethodWrapper fCallerRoot;
private IMemento fMemento;
private IMethod fShownMethod;
private SelectionProviderMediator fSelectionProviderMediator;
private List fMethodHistory;
private TableViewer fLocationViewer;
private Menu fLocationContextMenu;
private SashForm fHierarchyLocationSplitter;
private Clipboard fClipboard;
private SearchScopeActionGroup fSearchScopeActions;
private ToggleOrientationAction[] fToggleOrientationActions;
private ToggleCallModeAction[] fToggleCallModeActions;
private ToggleImplementorsAction[] fToggleImplementorsActions;
private CallHierarchyFiltersActionGroup fFiltersActionGroup;
private HistoryDropDownAction fHistoryDropDownAction;
private RefreshAction fRefreshAction;
private OpenLocationAction fOpenLocationAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private CopyCallHierarchyAction fCopyAction;
private CompositeActionGroup fActionGroups;
private CallHierarchyViewer fCallHierarchyViewer;
private boolean fShowCallDetails;
public CallHierarchyViewPart() {
super();
fDialogSettings = JavaPlugin.getDefault().getDialogSettings();
fMethodHistory = new ArrayList();
}
public void setFocus() {
fPagebook.setFocus();
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IMethod[] elems) {
fMethodHistory.clear();
for (int i = 0; i < elems.length; i++) {
fMethodHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Gets all history entries.
*/
public IMethod[] getHistoryEntries() {
if (fMethodHistory.size() > 0) {
updateHistoryEntries();
}
return (IMethod[]) fMethodHistory.toArray(new IMethod[fMethodHistory.size()]);
}
/**
* Method setMethod.
* @param method
*/
public void setMethod(IMethod method) {
if (method == null) {
showPage(PAGE_EMPTY);
return;
}
if ((method != null) && !method.equals(fShownMethod)) {
addHistoryEntry(method);
}
this.fShownMethod = method;
refresh();
}
public IMethod getMethod() {
return fShownMethod;
}
public MethodWrapper getCurrentMethodWrapper() {
if (fCurrentCallMode == CALL_MODE_CALLERS) {
return fCallerRoot;
} else {
return fCalleeRoot;
}
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
if ((fLocationViewer != null) && !fLocationViewer.getControl().isDisposed() &&
(fHierarchyLocationSplitter != null) &&
!fHierarchyLocationSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
setShowCallDetails(false);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
setShowCallDetails(true);
}
boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL;
fHierarchyLocationSplitter.setOrientation(horizontal ? SWT.HORIZONTAL
: SWT.VERTICAL);
}
fHierarchyLocationSplitter.layout();
}
for (int i = 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation = orientation;
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
/**
* called from ToggleCallModeAction.
* @param orientation CALL_MODE_CALLERS or CALL_MODE_CALLEES
*/
void setCallMode(int mode) {
if (fCurrentCallMode != mode) {
for (int i = 0; i < fToggleCallModeActions.length; i++) {
fToggleCallModeActions[i].setChecked(mode == fToggleCallModeActions[i].getMode());
}
fCurrentCallMode = mode;
fDialogSettings.put(DIALOGSTORE_CALL_MODE, mode);
updateView();
}
}
/**
* called from ToggleImplementorsAction.
* @param implementorsMode IMPLEMENTORS_USED or IMPLEMENTORS_NOT_USED
*/
void setImplementorsMode(int implementorsMode) {
if (fCurrentImplementorsMode != implementorsMode) {
for (int i = 0; i < fToggleImplementorsActions.length; i++) {
fToggleImplementorsActions[i].setChecked(implementorsMode == fToggleImplementorsActions[i].getImplementorsMode());
}
fCurrentImplementorsMode = implementorsMode;
CallHierarchy.getDefault().setSearchUsingImplementorsEnabled(implementorsMode == IMPLEMENTORS_ENABLED);
updateView();
}
}
public IJavaSearchScope getSearchScope() {
return fSearchScopeActions.getSearchScope();
}
public void setShowCallDetails(boolean show) {
fShowCallDetails = show;
showOrHideCallDetailsView();
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
addDragAdapters(fCallHierarchyViewer, ops, transfers);
addDropAdapters(fCallHierarchyViewer, ops | DND.DROP_DEFAULT, transfers);
addDropAdapters(fLocationViewer, ops | DND.DROP_DEFAULT, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new CallHierarchyTransferDropAdapter(this, fCallHierarchyViewer));
}
private void addDropAdapters(StructuredViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new CallHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) {
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(new SelectionProviderAdapter(viewer))
};
viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
}
public void createPartControl(Composite parent) {
fPagebook = new PageBook(parent, SWT.NONE);
// Page 1: Viewers
createHierarchyLocationSplitter(fPagebook);
createCallHierarchyViewer(fHierarchyLocationSplitter);
createLocationViewer(fHierarchyLocationSplitter);
// Page 2: Nothing selected
fNoHierarchyShownLabel = new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(CallHierarchyMessages.getString(
"CallHierarchyViewPart.empty")); //$NON-NLS-1$
showPage(PAGE_EMPTY);
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fSelectionProviderMediator = new SelectionProviderMediator(new Viewer[] {
fCallHierarchyViewer, fLocationViewer
});
IStatusLineManager slManager = getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(
slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
fClipboard= new Clipboard(parent.getDisplay());
makeActions();
fillViewMenu();
fillActionBars();
initOrientation();
initCallMode();
initImplementorsMode();
if (fMemento != null) {
restoreState(fMemento);
}
initDragAndDrop();
}
/**
* @param PAGE_EMPTY
*/
private void showPage(int page) {
if (page == PAGE_EMPTY) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
fPagebook.showPage(fHierarchyLocationSplitter);
}
enableActions(page != PAGE_EMPTY);
}
/**
* @param b
*/
private void enableActions(boolean enabled) {
fLocationContextMenu.setEnabled(enabled);
// TODO: Is it possible to disable the actions on the toolbar and on the view menu?
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento) {
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer callMode= memento.getInteger(TAG_CALL_MODE);
if (callMode != null) {
setCallMode(callMode.intValue());
}
Integer implementorsMode= memento.getInteger(TAG_IMPLEMENTORS_MODE);
if (implementorsMode != null) {
setImplementorsMode(implementorsMode.intValue());
}
Integer ratio = memento.getInteger(TAG_RATIO);
if (ratio != null) {
fHierarchyLocationSplitter.setWeights(new int[] {
ratio.intValue(), 1000 - ratio.intValue()
});
}
fSearchScopeActions.restoreState(memento);
}
private void initCallMode() {
int mode;
try {
mode = fDialogSettings.getInt(DIALOGSTORE_CALL_MODE);
if ((mode < 0) || (mode > 1)) {
mode = CALL_MODE_CALLERS;
}
} catch (NumberFormatException e) {
mode = CALL_MODE_CALLERS;
}
// force the update
fCurrentCallMode = -1;
// will fill the main tool bar
setCallMode(mode);
}
private void initImplementorsMode() {
int mode;
mode= CallHierarchy.getDefault().isSearchUsingImplementorsEnabled() ? IMPLEMENTORS_ENABLED : IMPLEMENTORS_DISABLED;
fCurrentImplementorsMode= -1;
// will fill the main tool bar
setImplementorsMode(mode);
}
private void initOrientation() {
int orientation;
try {
orientation = fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if ((orientation < 0) || (orientation > 2)) {
orientation = VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation = VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation = -1;
// will fill the main tool bar
setOrientation(orientation);
}
private void fillViewMenu() {
IActionBars actionBars = getViewSite().getActionBars();
IMenuManager viewMenu = actionBars.getMenuManager();
viewMenu.add(new Separator());
for (int i = 0; i < fToggleCallModeActions.length; i++) {
viewMenu.add(fToggleCallModeActions[i]);
}
viewMenu.add(new Separator());
// TODO: Should be reenabled if this toggle should actually be used
// for (int i = 0; i < fToggleImplementorsActions.length; i++) {
// viewMenu.add(fToggleImplementorsActions[i]);
// }
//
// viewMenu.add(new Separator());
for (int i = 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
}
/**
*
*/
public void dispose() {
disposeMenu(fLocationContextMenu);
if (fActionGroups != null)
fActionGroups.dispose();
if (fClipboard != null)
fClipboard.dispose();
super.dispose();
}
/**
* Double click listener which jumps to the method in the source code.
*
* @return IDoubleClickListener
*/
public void doubleClick(DoubleClickEvent event) {
jumpToSelection(event.getSelection());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IMethod entry) {
if (fMethodHistory.contains(entry)) {
setMethod(entry);
}
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento)
throws PartInitException {
super.init(site, memento);
fMemento = memento;
}
public void jumpToDeclarationOfSelection() {
ISelection selection = null;
selection = getSelection();
if ((selection != null) && selection instanceof IStructuredSelection) {
Object structuredSelection = ((IStructuredSelection) selection).getFirstElement();
if (structuredSelection instanceof IMember) {
CallHierarchyUI.jumpToMember((IMember) structuredSelection);
} else if (structuredSelection instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) structuredSelection;
CallHierarchyUI.jumpToMember(methodWrapper.getMember());
} else if (structuredSelection instanceof CallLocation) {
CallHierarchyUI.jumpToMember(((CallLocation) structuredSelection).getCalledMember());
}
}
}
public void jumpToSelection(ISelection selection) {
if ((selection != null) && selection instanceof IStructuredSelection) {
Object structuredSelection = ((IStructuredSelection) selection).getFirstElement();
if (structuredSelection instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) structuredSelection;
CallLocation firstCall = methodWrapper.getMethodCall()
.getFirstCallLocation();
if (firstCall != null) {
CallHierarchyUI.jumpToLocation(firstCall);
} else {
CallHierarchyUI.jumpToMember(methodWrapper.getMember());
}
} else if (structuredSelection instanceof CallLocation) {
CallHierarchyUI.jumpToLocation((CallLocation) structuredSelection);
}
}
}
/**
*
*/
public void refresh() {
setCalleeRoot(null);
setCallerRoot(null);
updateView();
}
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
memento.putInteger(TAG_CALL_MODE, fCurrentCallMode);
memento.putInteger(TAG_IMPLEMENTORS_MODE, fCurrentImplementorsMode);
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int[] weigths = fHierarchyLocationSplitter.getWeights();
int ratio = (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
fSearchScopeActions.saveState(memento);
}
/**
* @return ISelectionChangedListener
*/
public void selectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fCallHierarchyViewer) {
methodSelectionChanged(e.getSelection());
}
}
/**
* @param selection
*/
private void methodSelectionChanged(ISelection selection) {
if (selection instanceof IStructuredSelection) {
Object selectedElement = ((IStructuredSelection) selection).getFirstElement();
if (selectedElement instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) selectedElement;
revealElementInEditor(methodWrapper, fCallHierarchyViewer);
updateLocationsView(methodWrapper);
} else {
updateLocationsView(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
if (elem instanceof MethodWrapper) {
CallLocation callLocation = CallHierarchy.getCallLocation(elem);
if (callLocation != null) {
IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(callLocation);
if (editorPart != null) {
getSite().getPage().bringToTop(editorPart);
if (editorPart instanceof ITextEditor) {
ITextEditor editor = (ITextEditor) editorPart;
editor.selectAndReveal(callLocation.getStart(),
(callLocation.getEnd() - callLocation.getStart()));
}
}
} else {
IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(elem);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart,
((MethodWrapper) elem).getMember());
}
} else if (elem instanceof IJavaElement) {
IEditorPart editorPart = EditorUtility.isOpenInEditor(elem);
if (editorPart != null) {
// getSite().getPage().removePartListener(fPartListener);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
// getSite().getPage().addPartListener(fPartListener);
}
}
}
/**
* Returns the current selection.
*/
protected ISelection getSelection() {
return getSite().getSelectionProvider().getSelection();
}
protected void fillContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
}
protected void handleKeyEvent(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
if ((fRefreshAction != null) && fRefreshAction.isEnabled()) {
fRefreshAction.run();
return;
}
}
}
}
private IActionBars getActionBars() {
return getViewSite().getActionBars();
}
private void setCalleeRoot(MethodWrapper calleeRoot) {
this.fCalleeRoot = calleeRoot;
}
private MethodWrapper getCalleeRoot() {
if (fCalleeRoot == null) {
fCalleeRoot = (MethodWrapper) CallHierarchy.getDefault().getCalleeRoot(fShownMethod);
}
return fCalleeRoot;
}
private void setCallerRoot(MethodWrapper callerRoot) {
this.fCallerRoot = callerRoot;
}
private MethodWrapper getCallerRoot() {
if (fCallerRoot == null) {
fCallerRoot = (MethodWrapper) CallHierarchy.getDefault().getCallerRoot(fShownMethod);
}
return fCallerRoot;
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fMethodHistory.contains(entry)) {
fMethodHistory.remove(entry);
}
fMethodHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
}
/**
* @param parent
*/
private void createLocationViewer(Composite parent) {
fLocationViewer = new TableViewer(parent, SWT.NONE);
fLocationViewer.setContentProvider(new ArrayContentProvider());
fLocationViewer.setLabelProvider(new LocationLabelProvider());
fLocationViewer.setInput(new ArrayList());
fLocationViewer.getControl().addKeyListener(createKeyListener());
JavaUIHelp.setHelp(fLocationViewer, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fOpenLocationAction = new OpenLocationAction(getSite());
fLocationViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fOpenLocationAction.run();
}
});
// fListViewer.addDoubleClickListener(this);
MenuManager menuMgr = new MenuManager(); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
/* (non-Javadoc)
* @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
public void menuAboutToShow(IMenuManager manager) {
fillContextMenu(manager);
}
});
fLocationContextMenu = menuMgr.createContextMenu(fLocationViewer.getControl());
fLocationViewer.getControl().setMenu(fLocationContextMenu);
// Register viewer with site. This must be done before making the actions.
getSite().registerContextMenu(menuMgr, fLocationViewer);
}
private void createHierarchyLocationSplitter(Composite parent) {
fHierarchyLocationSplitter = new SashForm(parent, SWT.NONE);
fHierarchyLocationSplitter.addKeyListener(createKeyListener());
}
private void createCallHierarchyViewer(Composite parent) {
fCallHierarchyViewer = new CallHierarchyViewer(parent, this);
fCallHierarchyViewer.addKeyListener(createKeyListener());
fCallHierarchyViewer.addSelectionChangedListener(this);
fCallHierarchyViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillCallHierarchyViewerContextMenu(menu);
}
}, ID_CALL_HIERARCHY, getSite());
}
/**
* @param fCallHierarchyViewer
* @param menu
*/
protected void fillCallHierarchyViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
if (fFocusOnSelectionAction.canActionBeAdded()) {
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
}
menu.appendToGroup(GROUP_FOCUS, fCopyAction);
fActionGroups.setContext(new ActionContext(getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
private void disposeMenu(Menu contextMenu) {
if ((contextMenu != null) && !contextMenu.isDisposed()) {
contextMenu.dispose();
}
}
private void fillActionBars() {
IActionBars actionBars = getActionBars();
IToolBarManager toolBar = actionBars.getToolBarManager();
fActionGroups.fillActionBars(actionBars);
toolBar.add(fHistoryDropDownAction);
for (int i = 0; i < fToggleCallModeActions.length; i++) {
toolBar.add(fToggleCallModeActions[i]);
}
}
private KeyListener createKeyListener() {
KeyListener keyListener = new KeyAdapter() {
public void keyReleased(KeyEvent event) {
handleKeyEvent(event);
}
};
return keyListener;
}
/**
*
*/
private void makeActions() {
fRefreshAction = new RefreshAction(this);
fFocusOnSelectionAction = new FocusOnSelectionAction(this);
fCopyAction= new CopyCallHierarchyAction(this, fClipboard, fCallHierarchyViewer);
fSearchScopeActions = new SearchScopeActionGroup(this, fDialogSettings);
fFiltersActionGroup = new CallHierarchyFiltersActionGroup(this,
fCallHierarchyViewer);
fHistoryDropDownAction = new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions = new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fToggleCallModeActions = new ToggleCallModeAction[] {
new ToggleCallModeAction(this, CALL_MODE_CALLERS),
new ToggleCallModeAction(this, CALL_MODE_CALLEES)
};
fToggleImplementorsActions = new ToggleImplementorsAction[] {
new ToggleImplementorsAction(this, IMPLEMENTORS_ENABLED),
new ToggleImplementorsAction(this, IMPLEMENTORS_DISABLED)
};
fActionGroups = new CompositeActionGroup(new ActionGroup[] {
new OpenEditorActionGroup(getViewAdapter()),
new OpenViewActionGroup(getViewAdapter()),
new CCPActionGroup(getViewAdapter()),
new GenerateActionGroup(getViewAdapter()),
new RefactorActionGroup(getViewAdapter()),
new JavaSearchActionGroup(getViewAdapter()),
fSearchScopeActions, fFiltersActionGroup
});
}
private CallHierarchyViewAdapter getViewAdapter() {
if (fViewAdapter == null) {
fViewAdapter= new CallHierarchyViewAdapter(getViewSiteAdapter());
}
return fViewAdapter;
}
private CallHierarchyViewSiteAdapter getViewSiteAdapter() {
if (fViewSiteAdapter == null) {
fViewSiteAdapter= new CallHierarchyViewSiteAdapter(this.getViewSite());
}
return fViewSiteAdapter;
}
private void showOrHideCallDetailsView() {
if (fShowCallDetails) {
fHierarchyLocationSplitter.setMaximizedControl(null);
} else {
fHierarchyLocationSplitter.setMaximizedControl(fCallHierarchyViewer.getControl());
}
}
private void updateLocationsView(MethodWrapper methodWrapper) {
if (methodWrapper != null) {
fLocationViewer.setInput(methodWrapper.getMethodCall().getCallLocations());
} else {
fLocationViewer.setInput(""); //$NON-NLS-1$
}
}
private void updateHistoryEntries() {
for (int i = fMethodHistory.size() - 1; i >= 0; i--) {
IMethod method = (IMethod) fMethodHistory.get(i);
if (!method.exists()) {
fMethodHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
}
/**
* Method updateView.
*/
private void updateView() {
if ((fShownMethod != null)) {
showPage(PAGE_VIEWER);
CallHierarchy.getDefault().setSearchScope(getSearchScope());
if (fCurrentCallMode == CALL_MODE_CALLERS) {
setTitle(CallHierarchyMessages.getString("CallHierarchyViewPart.callsToMethod")); //$NON-NLS-1$
fCallHierarchyViewer.setMethodWrapper(getCallerRoot());
} else {
setTitle(CallHierarchyMessages.getString("CallHierarchyViewPart.callsFromMethod")); //$NON-NLS-1$
fCallHierarchyViewer.setMethodWrapper(getCalleeRoot());
}
updateLocationsView(null);
}
}
static CallHierarchyViewPart findAndShowCallersView(IWorkbenchPartSite site) {
IWorkbenchPage workbenchPage = site.getPage();
CallHierarchyViewPart callersView = null;
try {
callersView = (CallHierarchyViewPart) workbenchPage.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
return callersView;
}
}
|
36,672 |
Bug 36672 call hierarchy: Should show a progress bar
|
The Call Hierarchy view should show a progress bar when searching for callers/callees, allowing the user to abort the search.
|
resolved fixed
|
2086784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T09:50:12Z | 2003-04-19T16:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyViewer.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
class CallHierarchyViewer extends TreeViewer {
private CallHierarchyViewPart fPart;
private OpenLocationAction fOpen;
/**
* @param parent
*/
CallHierarchyViewer(Composite parent, CallHierarchyViewPart part) {
super(new Tree(parent, SWT.SINGLE));
fPart = part;
getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
setUseHashlookup(true);
setAutoExpandLevel(2);
setContentProvider(new CallHierarchyContentProvider());
setLabelProvider(new CallHierarchyLabelProvider());
JavaUIHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fOpen= new OpenLocationAction(part.getSite());
addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fOpen.run();
}
});
setInput(TreeRoot.EMPTY_TREE);
}
/**
* @param wrapper
*/
void setMethodWrapper(MethodWrapper wrapper) {
setInput(getTreeRoot(wrapper));
getTree().setFocus();
getTree().setSelection(new TreeItem[] { getTree().getItems()[0] });
}
CallHierarchyViewPart getPart() {
return fPart;
}
/**
*
*/
void setFocus() {
getControl().setFocus();
}
boolean isInFocus() {
return getControl().isFocusControl();
}
/**
* @param keyListener
*/
void addKeyListener(KeyListener keyListener) {
getControl().addKeyListener(keyListener);
}
/**
* Wraps the root of a MethodWrapper tree in a dummy root in order to show
* it in the tree.
*
* @param root The root of the MethodWrapper tree.
* @return A new MethodWrapper which is a dummy root above the specified root.
*/
private TreeRoot getTreeRoot(MethodWrapper root) {
TreeRoot dummyRoot = new TreeRoot(root);
return dummyRoot;
}
/**
* Attaches a contextmenu listener to the tree
*/
void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(menuListener);
Menu menu= menuMgr.createContextMenu(getTree());
getTree().setMenu(menu);
viewSite.registerContextMenu(popupId, menuMgr, this);
}
}
|
37,286 |
Bug 37286 SourceReferenceAction.isDeletedFromEditor fails on initializer from class file [ccp] [dnd]
| null |
resolved fixed
|
4a735ac
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-07T13:32:05Z | 2003-05-06T16:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/SourceReferenceAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.reorg;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.corext.SourceRange;
import org.eclipse.jdt.internal.corext.refactoring.reorg.SourceReferenceUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.WorkingCopyUtil;
public abstract class SourceReferenceAction extends SelectionDispatchAction {
//workaround for bug 18311
private static final ISourceRange fgUnknownRange= new SourceRange(-1, 0);
protected SourceReferenceAction(IWorkbenchSite site) {
super(site);
}
protected ISourceReference[] getElementsToProcess(IStructuredSelection selection) {
return SourceReferenceUtil.removeAllWithParentsSelected(getSelectedElements(selection));
}
/*
* @see SelectionDispatchAction#run(IStructuredSelection)
*/
public final void run(final IStructuredSelection selection) {
BusyIndicator.showWhile(JavaPlugin.getActiveWorkbenchShell().getDisplay(), new Runnable() {
public void run() {
try {
perform(selection);
} catch (CoreException e) {
ExceptionHandler.handle(e, getText(), ReorgMessages.getString("SourceReferenceAction.exception")); //$NON-NLS-1$
}
}
});
}
protected abstract void perform(IStructuredSelection selection) throws CoreException;
private boolean canOperateOn(IStructuredSelection selection) {
try{
if (selection.isEmpty())
return false;
Object[] elems= selection.toArray();
for (int i= 0; i < elems.length; i++) {
Object elem= elems[i];
if (! canWorkOn(elem))
return false;
}
return true;
} catch (JavaModelException e){
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
return false;
}
}
private ISourceReference[] getSelectedElements(IStructuredSelection selection){
return getWorkingCopyElements(selection.toList());
}
protected boolean canWorkOn(Object elem) throws JavaModelException{
if (elem == null)
return false;
if (! (elem instanceof ISourceReference))
return false;
if (! (elem instanceof IJavaElement))
return false;
if (elem instanceof IClassFile)
return false;
if (elem instanceof ICompilationUnit)
return false;
if (elem instanceof IMember){
IMember member= (IMember)elem;
if (member.isBinary() && (member.getSourceRange() == null || fgUnknownRange.equals(member.getSourceRange())))
return false;
}
if (isDeletedFromEditor((ISourceReference)elem))
return false;
if (elem instanceof IMember) //binary excluded before
return true;
if (elem instanceof IImportContainer)
return true;
if (elem instanceof IImportDeclaration)
return true;
if (elem instanceof IPackageDeclaration)
return true;
//we never get here normally
return false;
}
private static boolean isDeletedFromEditor(ISourceReference elem) throws JavaModelException{
if (elem instanceof IMember && ((IMember)elem).isBinary())
return false;
ICompilationUnit cu= SourceReferenceUtil.getCompilationUnit(elem);
ICompilationUnit wc= WorkingCopyUtil.getWorkingCopyIfExists(cu);
if (wc.equals(cu))
return false;
IJavaElement element= (IJavaElement)elem;
IJavaElement wcElement= JavaModelUtil.findInCompilationUnit(wc, element);
return wcElement == null || ! wcElement.exists();
}
private static ISourceReference[] getWorkingCopyElements(List l) {
List wcList= new ArrayList(l.size());
for (Iterator iter= l.iterator(); iter.hasNext();) {
ISourceReference element= (ISourceReference) iter.next();
if (! (element instanceof IJavaElement)) //can this happen ?
wcList.add(element);
ICompilationUnit cu= SourceReferenceUtil.getCompilationUnit(element);
if (cu == null){
wcList.add(element);
} else if (cu.isWorkingCopy()){
wcList.add(element);
} else {
ICompilationUnit wc= WorkingCopyUtil.getWorkingCopyIfExists(cu);
try {
IJavaElement wcElement= JavaModelUtil.findInCompilationUnit(wc, (IJavaElement)element);
if (wcElement != null && wcElement.exists())
wcList.add(wcElement);
} catch(JavaModelException e) {
JavaPlugin.log(e); //cannot show dialog here
//do nothing - do not add to selection (?)
}
}
}
return (ISourceReference[]) wcList.toArray(new ISourceReference[wcList.size()]);
}
/*
* @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(canOperateOn(selection));
}
}
|
36,978 |
Bug 36978 org.eclipse.jdt.internal.corext.dom.ASTFlattener / for statements ...
|
There is a bug in "public boolean visit(ForStatement node)" You should first do node.getExpression() and then node.getUpdates(). The current code will print the loop "for(int i=0;i<100;i++);" as "for(int i=0;i++;i<100);" A corrected version of the "visit(ForStatement node)" function should look like this: public boolean visit(ForStatement node) { fResult.append("for (");//$NON-NLS-1$ for (Iterator it = node.initializers().iterator(); it.hasNext(); ) { Expression e = (Expression) it.next(); e.accept(this); } fResult.append("; ");//$NON-NLS-1$ if (node.getExpression() != null) { node.getExpression().accept(this); } fResult.append("; ");//$NON-NLS-1$ for (Iterator it = node.updaters().iterator(); it.hasNext(); ) { Expression e = (Expression) it.next(); e.accept(this); } fResult.append(") ");//$NON-NLS-1$ node.getBody().accept(this); return false; }
|
resolved fixed
|
4b0c7c8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-08T10:49:57Z | 2003-04-27T07:53:20Z |
org.eclipse.jdt.ui/core
| |
36,978 |
Bug 36978 org.eclipse.jdt.internal.corext.dom.ASTFlattener / for statements ...
|
There is a bug in "public boolean visit(ForStatement node)" You should first do node.getExpression() and then node.getUpdates(). The current code will print the loop "for(int i=0;i<100;i++);" as "for(int i=0;i++;i<100);" A corrected version of the "visit(ForStatement node)" function should look like this: public boolean visit(ForStatement node) { fResult.append("for (");//$NON-NLS-1$ for (Iterator it = node.initializers().iterator(); it.hasNext(); ) { Expression e = (Expression) it.next(); e.accept(this); } fResult.append("; ");//$NON-NLS-1$ if (node.getExpression() != null) { node.getExpression().accept(this); } fResult.append("; ");//$NON-NLS-1$ for (Iterator it = node.updaters().iterator(); it.hasNext(); ) { Expression e = (Expression) it.next(); e.accept(this); } fResult.append(") ");//$NON-NLS-1$ node.getBody().accept(this); return false; }
|
resolved fixed
|
4b0c7c8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-08T10:49:57Z | 2003-04-27T07:53:20Z |
extension/org/eclipse/jdt/internal/corext/dom/ASTFlattener.java
| |
37,381 |
Bug 37381 AST: Wrong source ranges on VariableDeclExpression
|
20030508 In the code snipped of UnresolvedMethodsQuickFixTest.testMethodInForInit for (int i= 0, j= goo(3); i < 0; i++) { } the VariableDeclationExpression ('int i= 0, j= goo(3)') has only length 8 (should be 19)
|
verified fixed
|
4a5b04e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-08T12:56:50Z | 2003-05-08T13:20:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedMethodsQuickFixTest.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.ASTResolving;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.correction.NewMethodCompletionProposal;
public class UnresolvedMethodsQuickFixTest extends QuickFixTest {
private static final Class THIS= UnresolvedMethodsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public UnresolvedMethodsQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new UnresolvedMethodsQuickFixTest("testParameterMismatchMoreArguments3"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT, JavaCore.IGNORE);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testMethodInSameType() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing0EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing1EmptyLine() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing2EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingComment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingNonJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInSameTypeUsingThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentClass() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(1, 2.1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("\n");
buf.append(" public boolean goo(int i, double d) {\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentInterface() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(getClass());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("\n");
buf.append(" boolean goo(Class class1);\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testParameterMismatchCast() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo((int) (x + 1));\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(long l) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(long l) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchCast2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((float) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((int) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(float f, E e) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(float f, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(null, x, null);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(null);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(0, null);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(Object object) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, 1, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, int j, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(int i, int j, X x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(String s, int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int x2) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(Collections.EMPTY_SET, 1, 2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(Set set, int i, int k) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(Set set, int i, int j) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchSwap() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(i - 1, new Object[] { o });\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(Object[] objects, int i) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o, int i) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E(int i) {\n");
buf.append(" super(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testClassInstanceCreation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testConstructorInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperMethodInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" super.foo(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public void foo(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCanAssign() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Collection;\n");
buf.append("import java.io.Serializable;\n");
buf.append("public class E {\n");
buf.append(" boolean bool;\n");
buf.append(" char c;\n");
buf.append(" byte b;\n");
buf.append(" short s;\n");
buf.append(" int i;\n");
buf.append(" long l;\n");
buf.append(" float f;\n");
buf.append(" double d;\n");
buf.append(" Object object;\n");
buf.append(" Vector vector;\n");
buf.append(" Cloneable cloneable;\n");
buf.append(" Collection collection;\n");
buf.append(" Serializable serializable;\n");
buf.append(" Object[] objectArr;\n");
buf.append(" int[] int_arr;\n");
buf.append(" long[] long_arr;\n");
buf.append(" Vector[] vector_arr;\n");
buf.append(" Collection[] collection_arr;\n");
buf.append(" Object[][] objectArrArr;\n");
buf.append(" Collection[][] collection_arrarr;\n");
buf.append(" Vector[][] vector_arrarr;\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
VariableDeclarationFragment bool= findFieldDeclaration(type, "bool");
VariableDeclarationFragment c= findFieldDeclaration(type, "c");
VariableDeclarationFragment b= findFieldDeclaration(type, "b");
VariableDeclarationFragment s= findFieldDeclaration(type, "s");
VariableDeclarationFragment i= findFieldDeclaration(type, "i");
VariableDeclarationFragment l= findFieldDeclaration(type, "l");
VariableDeclarationFragment f= findFieldDeclaration(type, "f");
VariableDeclarationFragment d= findFieldDeclaration(type, "d");
VariableDeclarationFragment object= findFieldDeclaration(type, "object");
VariableDeclarationFragment vector= findFieldDeclaration(type, "vector");
VariableDeclarationFragment cloneable= findFieldDeclaration(type, "cloneable");
VariableDeclarationFragment collection= findFieldDeclaration(type, "collection");
VariableDeclarationFragment serializable= findFieldDeclaration(type, "serializable");
VariableDeclarationFragment objectArr= findFieldDeclaration(type, "objectArr");
VariableDeclarationFragment int_arr= findFieldDeclaration(type, "int_arr");
VariableDeclarationFragment long_arr= findFieldDeclaration(type, "long_arr");
VariableDeclarationFragment vector_arr= findFieldDeclaration(type, "vector_arr");
VariableDeclarationFragment collection_arr= findFieldDeclaration(type, "collection_arr");
VariableDeclarationFragment objectArrArr= findFieldDeclaration(type, "objectArrArr");
VariableDeclarationFragment collection_arrarr= findFieldDeclaration(type, "collection_arrarr");
VariableDeclarationFragment vector_arrarr= findFieldDeclaration(type, "vector_arrarr");
VariableDeclarationFragment[] targets= new VariableDeclarationFragment[] {
bool, c, b, s, i, l, f, d, object, vector, cloneable, serializable, collection, objectArr, int_arr, long_arr,
vector_arr, collection_arr, objectArrArr, collection_arrarr, vector_arrarr
};
for (int k= 0; k < targets.length; k++) {
for (int n= 0; n < targets.length; n++) {
VariableDeclarationFragment f1= targets[k];
VariableDeclarationFragment f2= targets[n];
String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F extends E {\n");
buf.append(" void foo() {\n");
buf.append(" ").append(line).append(";\n");
buf.append(" }\n");
buf.append("}\n");
char[] content= buf.toString().toCharArray();
astRoot= AST.parseCompilationUnit(content, "F.java", cu1.getJavaProject());
problems= astRoot.getProblems();
ITypeBinding b1= f1.resolveBinding().getType();
assertNotNull(b1);
ITypeBinding b2= f2.resolveBinding().getType();
assertNotNull(b2);
boolean res= ASTResolving.canAssign(b1, b2.getQualifiedName());
assertEquals(line, problems.length == 0, res);
boolean res2= ASTResolving.canAssign(b1, b2);
assertEquals(line, problems.length == 0, res2);
}
}
}
}
|
37,345 |
Bug 37345 javaElementFilters extension point isn't robust against errors in the plugin.xml
|
1) create a javaElementFilters extension, but leave the markup in the plugin.xml incomplete 2) start-up the workbench -> the package explorer doesn't come up The reason is that the javaElementFilters extension point implementation fires an assertion when the xml isn't complete. This is not correct since this isn't a programming error. In addition, an error in the plugin.xml shouldn't never block the workbench from properly coming up.
|
resolved fixed
|
7515914
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-08T16:14:05Z | 2003-05-07T17:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/FilterDescriptor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.filters;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IPluginRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
/**
* Represents a custom filter which is provided by the
* "org.eclipse.jdt.ui.javaElementFilters" extension point.
*
* since 2.0
*/
public class FilterDescriptor implements Comparable {
private static String PATTERN_FILTER_ID_PREFIX= "_patternFilterId_"; //$NON-NLS-1$
private static final String EXTENSION_POINT_NAME= "javaElementFilters"; //$NON-NLS-1$
private static final String FILTER_TAG= "filter"; //$NON-NLS-1$
private static final String PATTERN_ATTRIBUTE= "pattern"; //$NON-NLS-1$
private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$
private static final String VIEW_ID_ATTRIBUTE= "viewId"; //$NON-NLS-1$
private static final String CLASS_ATTRIBUTE= "class"; //$NON-NLS-1$
private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$
private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
/**
* @deprecated use "enabled" instead
*/
private static final String SELECTED_ATTRIBUTE= "selected"; //$NON-NLS-1$
private static FilterDescriptor[] fgFilterDescriptors;
private IConfigurationElement fElement;
/**
* Returns all contributed Java element filters.
*/
public static FilterDescriptor[] getFilterDescriptors() {
if (fgFilterDescriptors == null) {
IPluginRegistry registry= Platform.getPluginRegistry();
IConfigurationElement[] elements= registry.getConfigurationElementsFor(JavaUI.ID_PLUGIN, EXTENSION_POINT_NAME);
fgFilterDescriptors= createFilterDescriptors(elements);
}
return fgFilterDescriptors;
}
/**
* Returns all Java element filters which
* are contributed to the given view.
*/
public static FilterDescriptor[] getFilterDescriptors(String viewId) {
FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors();
List result= new ArrayList(filterDescs.length);
for (int i= 0; i < filterDescs.length; i++) {
String vid= filterDescs[i].getViewId();
if (vid == null || vid.equals(viewId))
result.add(filterDescs[i]);
}
return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]);
}
/**
* Creates a new filter descriptor for the given configuration element.
*/
private FilterDescriptor(IConfigurationElement element) {
fElement= element;
// it is either a pattern filter or a custom filter
Assert.isTrue(isPatternFilter() ^ isCustomFilter());
Assert.isNotNull(getId());
Assert.isNotNull(getName());
}
/**
* Creates a new <code>ViewerFilter</code>.
* This method is only valid for viewer filters.
*
* @throws AssertionFailedException if this is a pattern filter
*
*/
public ViewerFilter createViewerFilter() {
Assert.isTrue(isCustomFilter());
ViewerFilter result= null;
try {
result= (ViewerFilter)fElement.createExecutableExtension(CLASS_ATTRIBUTE);
} catch (CoreException ex) {
handleError(ex.getStatus());
} catch (ClassCastException ex) {
handleError(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IJavaStatusConstants.INTERNAL_ERROR, ex.getLocalizedMessage(), ex));
// Workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=37215
} catch (NoClassDefFoundError ex) {
handleError(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IJavaStatusConstants.INTERNAL_ERROR, ex.getLocalizedMessage(), ex));
}
return result;
}
private void handleError(IStatus status) {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell != null) {
String title= FilterMessages.getString("FilterDescriptor.filterCreationError.title"); //$NON-NLS-1$
String message= FilterMessages.getFormattedString("FilterDescriptor.filterCreationError.message", getId()); //$NON-NLS-1$
ErrorDialog.openError(shell, title, message, status);
}
JavaPlugin.log(status);
}
//---- XML Attribute accessors ---------------------------------------------
/**
* Returns the filter's id.
* <p>
* This attribute is mandatory for custom filters.
* The ID for pattern filters is
* PATTERN_FILTER_ID_PREFIX plus the pattern itself.
* </p>
*/
public String getId() {
if (isPatternFilter()) {
String viewId= getViewId();
if (viewId == null)
return PATTERN_FILTER_ID_PREFIX + getPattern();
else
return viewId + PATTERN_FILTER_ID_PREFIX + getPattern();
} else
return fElement.getAttribute(ID_ATTRIBUTE);
}
/**
* Returns the filter's name.
* <p>
* If the name of a pattern filter is missing
* then the pattern is used as its name.
* </p>
*/
public String getName() {
String name= fElement.getAttribute(NAME_ATTRIBUTE);
if (name == null && isPatternFilter())
name= getPattern();
return name;
}
/**
* Returns the filter's pattern.
*
* @return the pattern string or <code>null</code> if it's not a pattern filter
*/
public String getPattern() {
return fElement.getAttribute(PATTERN_ATTRIBUTE);
}
/**
* Returns the filter's viewId.
*
* @return the view ID or <code>null</code> if the filter is for all views
*/
public String getViewId() {
return fElement.getAttribute(VIEW_ID_ATTRIBUTE);
}
/**
* Returns the filter's description.
*
* @return the description or <code>null</code> if no description is provided
*/
public String getDescription() {
String description= fElement.getAttribute(DESCRIPTION_ATTRIBUTE);
if (description == null)
description= ""; //$NON-NLS-1$
return description;
}
/**
* @return <code>true</code> if this filter is a custom filter.
*/
public boolean isPatternFilter() {
return getPattern() != null;
}
/**
* @return <code>true</code> if this filter is a pattern filter.
*/
public boolean isCustomFilter() {
return fElement.getAttribute(CLASS_ATTRIBUTE) != null;
}
/**
* Returns <code>true</code> if the filter
* is initially enabled.
*
* This attribute is optional and defaults to <code>true</code>.
*/
public boolean isEnabled() {
String strVal= fElement.getAttribute(ENABLED_ATTRIBUTE);
if (strVal == null)
// backward compatibility
strVal= fElement.getAttribute(SELECTED_ATTRIBUTE);
return strVal == null || Boolean.valueOf(strVal).booleanValue();
}
/*
* Implements a method from IComparable
*/
public int compareTo(Object o) {
if (o instanceof FilterDescriptor)
return Collator.getInstance().compare(getName(), ((FilterDescriptor)o).getName());
else
return Integer.MIN_VALUE;
}
//---- initialization ---------------------------------------------------
/**
* Creates the filter descriptors.
*/
private static FilterDescriptor[] createFilterDescriptors(IConfigurationElement[] elements) {
List result= new ArrayList(5);
Set descIds= new HashSet(5);
for (int i= 0; i < elements.length; i++) {
IConfigurationElement element= elements[i];
if (FILTER_TAG.equals(element.getName())) {
FilterDescriptor desc= new FilterDescriptor(element);
if (!descIds.contains(desc.getId())) {
result.add(desc);
descIds.add(desc.getId());
}
}
}
Collections.sort(result);
return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]);
}
}
|
37,197 |
Bug 37197 Basepath for relative pathes in JAR-exporter
|
The basepath for the JAR-exporter is the eclipse-install-directory. I prefer it to be the root of the project (the description is saved in), so that relative pathes end inside the project. Now: <jardesc> <jar path="workspace/projectdir/jar.jar"/> Desired: <jardesc> <jar path="jar.jar"/> Reason: To make the jardesc-files portable for shared projects
|
resolved fixed
|
2e55236
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-08T17:06:58Z | 2003-05-03T22:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import java.util.zip.ZipException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
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.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static class MessageMultiStatus extends MultiStatus {
MessageMultiStatus(String pluginId, int code, String message, Throwable exception) {
super(pluginId, code, message, exception);
}
/*
* allows to change the message
*/
protected void setMessage(String message) {
super.setMessage(message);
}
}
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MessageMultiStatus fStatus;
private StandardJavaElementContentProvider fJavaElementContentProvider;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param jarPackages an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fStatus= new MessageMultiStatus(JavaPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
fJavaElementContentProvider= new StandardJavaElementContentProvider();
}
protected void addToStatus(CoreException ex) {
IStatus status= ex.getStatus();
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
message= JarPackagerMessages.getString("JarFileExportOperation.coreErrorDuringExport"); //$NON-NLS-1$
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
}
fStatus.add(status);
}
/**
* Adds a new info to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addInfo(String message, Throwable error) {
fStatus.add(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
continue;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
int type= je.getElementType();
if (type != IJavaElement.CLASS_FILE && type != IJavaElement.COMPILATION_UNIT) {
exportJavaElement(progressMonitor, je);
return;
}
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= findPackageFragmentRoot(jProject, resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
boolean isOnBuildPath;
isOnBuildPath= jProject.isOnClasspath(resource);
if (!isOnBuildPath || (mustUseSourceFolderHierarchy() && !pkgRoot.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportJavaElement(IProgressMonitor progressMonitor, IJavaElement je) throws java.lang.InterruptedException {
if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && ((IPackageFragmentRoot)je).isArchive())
return;
Object[] children= fJavaElementContentProvider.getChildren(je);
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
if (jProject == null || path == null || path.segmentCount() <= 0)
return null;
IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
if (pkgRoot != null)
return pkgRoot;
else
return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
// Handle case where META-INF/MANIFEST.MF is part of the exported files
if (fJarPackage.areClassFilesExported() && destinationPath.toString().equals("META-INF/MANIFEST.MF")) {//$NON-NLS-1$
if (fJarPackage.isManifestGenerated())
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.didNotAddManifestToJar", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == IPackageFragmentRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (CoreException ex) {
Throwable realEx= ex.getStatus().getException();
if (realEx instanceof ZipException && realEx.getMessage() != null && realEx.getMessage().startsWith("duplicate entry:")) //$NON-NLS-1$
addWarning(ex.getMessage(), realEx);
else
addToStatus(ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
if (!jProject.isOnClasspath(resource))
return;
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, pkgRoot, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
* @deprecated As of 2.1 use the method with additional IPackageFragmentRoot paramter
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
return filesOnClasspath(file, pathInJar, javaProject, null, progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @param pkgRoot the package fragment root that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IPackageFragmentRoot pkgRoot, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= null;
if (pkgRoot != null) {
IClasspathEntry cpEntry= pkgRoot.getRawClasspathEntry();
if (cpEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE)
outputPath= cpEntry.getOutputLocation();
}
if (outputPath == null)
// Use default output location
outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
IPath location= classContainer.getLocation();
String containerName= ""; //$NON-NLS-1$
if (location != null)
containerName= location.toFile().toString();
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", containerName); //$NON-NLS-1$
addInfo(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader= null;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
IPath location= classFile.getLocation();
if (location != null) {
File file= location.toFile();
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(location.toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", file), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", file), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", file), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* The result is a status object containing individual
* status objects.
*
* @return the status of this operation
*/
public IStatus getStatus() {
String message= null;
switch (fStatus.getSeverity()) {
case IStatus.OK:
message= ""; //$NON-NLS-1$
break;
case IStatus.INFO:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithInfo"); //$NON-NLS-1$
break;
case IStatus.WARNING:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"); //$NON-NLS-1$
break;
case IStatus.ERROR:
if (fJarPackages.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
break;
default:
// defensive code in case new severity is defined
message= ""; //$NON-NLS-1$
break;
}
fStatus.setMessage(message);
return fStatus;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded() && fJarPackage.areClassFilesExported()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (CoreException ex) {
addToStatus(ex);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (CoreException ex) {
addToStatus(ex);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
File targetFile= fJarPackage.getJarLocation().toFile();
if (targetFile.exists() && !targetFile.canWrite()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.jarFileExistsAndNotWritable"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
if (fParentShell == null)
// no checking if shell is null
return true;
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles() {
IEditorPart[] dirtyEditors= getDirtyEditors(fParentShell);
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (JarPackagerUtil.contains(selection, dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= getDirtyEditors(fParentShell);
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.areClassFilesExported() && fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
private IEditorPart[] getDirtyEditors(Shell parent) {
Display display= parent.getDisplay();
final Object[] result= new Object[1];
display.syncExec(
new Runnable() {
public void run() {
result[0]= JavaPlugin.getDirtyEditors();
}
}
);
return (IEditorPart[])result[0];
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString()))
descriptionFile.setContents(fileInput, true, true, null);
} else
descriptionFile.create(fileInput, true, null);
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString()))
manifestFile.setContents(fileInput, true, true, null);
} else
manifestFile.create(fileInput, true, null);
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(JavaCore.COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
private boolean mustUseSourceFolderHierarchy() {
return fJarPackage.useSourceFolderHierarchy() && fJarPackage.areJavaFilesExported() && !fJarPackage.areClassFilesExported();
}
}
|
37,197 |
Bug 37197 Basepath for relative pathes in JAR-exporter
|
The basepath for the JAR-exporter is the eclipse-install-directory. I prefer it to be the root of the project (the description is saved in), so that relative pathes end inside the project. Now: <jardesc> <jar path="workspace/projectdir/jar.jar"/> Desired: <jardesc> <jar path="jar.jar"/> Reason: To make the jardesc-files portable for shared projects
|
resolved fixed
|
2e55236
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-08T17:06:58Z | 2003-05-03T22:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackageWizardPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.WizardExportResourcesPage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.filters.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
/**
* Page 1 of the JAR Package wizard
*/
class JarPackageWizardPage extends WizardExportResourcesPage implements IJarPackageWizardPage {
private JarPackageData fJarPackage;
private IStructuredSelection fInitialSelection;
private CheckboxTreeAndListGroup fInputGroup;
// widgets
private Text fSourceNameField;
private Button fExportClassFilesCheckbox;
private Button fExportJavaFilesCheckbox;
private Combo fDestinationNamesCombo;
private Button fDestinationBrowseButton;
private Button fCompressCheckbox;
private Button fOverwriteCheckbox;
private Text fDescriptionFileText;
// dialog store id constants
private final static String PAGE_NAME= "JarPackageWizardPage"; //$NON-NLS-1$
private final static String STORE_EXPORT_CLASS_FILES= PAGE_NAME + ".EXPORT_CLASS_FILES"; //$NON-NLS-1$
private final static String STORE_EXPORT_JAVA_FILES= PAGE_NAME + ".EXPORT_JAVA_FILES"; //$NON-NLS-1$
private final static String STORE_DESTINATION_NAMES= PAGE_NAME + ".DESTINATION_NAMES_ID"; //$NON-NLS-1$
private final static String STORE_COMPRESS= PAGE_NAME + ".COMPRESS"; //$NON-NLS-1$
private final static String STORE_OVERWRITE= PAGE_NAME + ".OVERWRITE"; //$NON-NLS-1$
// other constants
private final static int SIZING_SELECTION_WIDGET_WIDTH= 480;
private final static int SIZING_SELECTION_WIDGET_HEIGHT= 150;
/**
* Create an instance of this class
*/
public JarPackageWizardPage(JarPackageData jarPackage, IStructuredSelection selection) {
super(PAGE_NAME, selection);
setTitle(JarPackagerMessages.getString("JarPackageWizardPage.title")); //$NON-NLS-1$
setDescription(JarPackagerMessages.getString("JarPackageWizardPage.description")); //$NON-NLS-1$
fJarPackage= jarPackage;
fInitialSelection= selection;
}
/*
* Method declared on IDialogPage.
*/
public void createControl(final Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout());
composite.setLayoutData(
new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whatToExport.label")); //$NON-NLS-1$
createInputGroup(composite);
createExportTypeGroup(composite);
new Label(composite, SWT.NONE); // vertical spacer
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whereToExport.label")); //$NON-NLS-1$
createDestinationGroup(composite);
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.options.label")); //$NON-NLS-1$
createOptionsGroup(composite);
restoreResourceSpecificationWidgetValues(); // superclass API defines this hook
restoreWidgetValues();
if (fInitialSelection != null)
BusyIndicator.showWhile(parent.getDisplay(), new Runnable() {
public void run() {
setupBasedOnInitialSelections();
}
});
setControl(composite);
update();
giveFocusToDestination();
Dialog.applyDialogFont(composite);
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.JARPACKAGER_WIZARD_PAGE);
}
/**
* Create the export options specification widgets.
*
* @param parent org.eclipse.swt.widgets.Composite
*/
protected void createOptionsGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
optionsGroup.setLayout(layout);
fCompressCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fCompressCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.compress.text")); //$NON-NLS-1$
fCompressCheckbox.addListener(SWT.Selection, this);
fOverwriteCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fOverwriteCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.overwrite.text")); //$NON-NLS-1$
fOverwriteCheckbox.addListener(SWT.Selection, this);
}
/**
* Answer the contents of the destination specification widget. If this
* value does not have the required suffix then add it first.
*
* @return java.lang.String
*/
protected String getDestinationValue() {
String destinationText= fDestinationNamesCombo.getText().trim();
if (destinationText.indexOf('.') < 0)
destinationText += getOutputSuffix();
return destinationText;
}
/**
* Answer the string to display in self as the destination type
*
* @return java.lang.String
*/
protected String getDestinationLabel() {
return JarPackagerMessages.getString("JarPackageWizardPage.destination.label"); //$NON-NLS-1$
}
/**
* Answer the suffix that files exported from this wizard must have.
* If this suffix is a file extension (which is typically the case)
* then it must include the leading period character.
*
* @return java.lang.String
*/
protected String getOutputSuffix() {
return "." + JarPackagerUtil.JAR_EXTENSION; //$NON-NLS-1$
}
/**
* Returns an iterator over this page's collection of currently-specified
* elements to be exported. This is the primary element selection facility
* accessor for subclasses.
*
* @return an iterator over the collection of elements currently selected for export
*/
protected Iterator getSelectedResourcesIterator() {
return fInputGroup.getAllCheckedListItems();
}
/**
* Persists resource specification control setting that are to be restored
* in the next instance of this page. Subclasses wishing to persist
* settings for their controls should extend the hook method
* <code>internalSaveWidgetValues</code>.
*/
public final void saveWidgetValues() {
// update directory names history
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
directoryNames= new String[0];
directoryNames= addToHistory(directoryNames, getDestinationValue());
settings.put(STORE_DESTINATION_NAMES, directoryNames);
settings.put(STORE_EXPORT_CLASS_FILES, fJarPackage.areClassFilesExported());
settings.put(STORE_EXPORT_JAVA_FILES, fJarPackage.areJavaFilesExported());
// options
settings.put(STORE_COMPRESS, fJarPackage.isCompressed());
settings.put(STORE_OVERWRITE, fJarPackage.allowOverwrite());
}
// Allow subclasses to save values
internalSaveWidgetValues();
}
/**
* Hook method for subclasses to persist their settings.
*/
protected void internalSaveWidgetValues() {
}
/**
* Hook method for restoring widget values to the values that they held
* last time this wizard was used to completion.
*/
protected void restoreWidgetValues() {
if (!((JarPackageWizard)getWizard()).isInitializingFromJarPackage())
initializeJarPackage();
fExportClassFilesCheckbox.setSelection(fJarPackage.areClassFilesExported());
fExportJavaFilesCheckbox.setSelection(fJarPackage.areJavaFilesExported());
// destination
if (fJarPackage.getJarLocation().isEmpty())
fDestinationNamesCombo.setText(""); //$NON-NLS-1$
else
fDestinationNamesCombo.setText(fJarPackage.getJarLocation().toOSString());
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
if (! fDestinationNamesCombo.getText().equals(directoryNames[0]))
fDestinationNamesCombo.add(fDestinationNamesCombo.getText());
for (int i= 0; i < directoryNames.length; i++)
fDestinationNamesCombo.add(directoryNames[i]);
}
// options
fCompressCheckbox.setSelection(fJarPackage.isCompressed());
fOverwriteCheckbox.setSelection(fJarPackage.allowOverwrite());
}
/**
* Initializes the JAR package from last used wizard page values.
*/
protected void initializeJarPackage() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// source
fJarPackage.setElements(getSelectedElements());
fJarPackage.setExportClassFiles(settings.getBoolean(STORE_EXPORT_CLASS_FILES));
fJarPackage.setExportJavaFiles(settings.getBoolean(STORE_EXPORT_JAVA_FILES));
// options
fJarPackage.setCompress(settings.getBoolean(STORE_COMPRESS));
fJarPackage.setOverwrite(settings.getBoolean(STORE_OVERWRITE));
// destination
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
fJarPackage.setJarLocation(new Path(directoryNames[0]));
}
}
/**
* Stores the widget values in the JAR package.
*/
protected void updateModel() {
if (getControl() == null)
return;
// source
fJarPackage.setElements(getSelectedElements());
fJarPackage.setExportClassFiles(fExportClassFilesCheckbox.getSelection());
fJarPackage.setExportJavaFiles(fExportJavaFilesCheckbox.getSelection());
// destination
String comboText= fDestinationNamesCombo.getText();
IPath path= new Path(comboText);
if (!new File(comboText).isAbsolute())
// prepend workspace path
path= getWorkspaceLocation().append(path);
if (path.segmentCount() > 0 && ensureTargetFileIsValid(path.toFile()) && path.getFileExtension() == null) //$NON-NLS-1$
// append .jar
path= path.addFileExtension(JarPackagerUtil.JAR_EXTENSION);
fJarPackage.setJarLocation(path);
// options
fJarPackage.setCompress(fCompressCheckbox.getSelection());
fJarPackage.setOverwrite(fOverwriteCheckbox.getSelection());
}
/**
* Returns a boolean indicating whether the passed File handle is
* is valid and available for use.
*
* @return boolean
*/
protected boolean ensureTargetFileIsValid(File targetFile) {
if (targetFile.exists() && targetFile.isDirectory() && fDestinationNamesCombo.getText().length() > 0) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
if (targetFile.exists()) {
if (!targetFile.canWrite()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.jarFileExistsAndNotWritable")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
}
return true;
}
/*
* Overrides method from WizardExportPage
*/
protected void createDestinationGroup(Composite parent) {
initializeDialogUnits(parent);
// destination specification group
Composite destinationSelectionGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
destinationSelectionGroup.setLayout(layout);
destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
new Label(destinationSelectionGroup, SWT.NONE).setText(getDestinationLabel());
// destination name entry field
fDestinationNamesCombo= new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
fDestinationNamesCombo.addListener(SWT.Modify, this);
fDestinationNamesCombo.addListener(SWT.Selection, this);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= SIZING_TEXT_FIELD_WIDTH;
fDestinationNamesCombo.setLayoutData(data);
// destination browse button
fDestinationBrowseButton= new Button(destinationSelectionGroup, SWT.PUSH);
fDestinationBrowseButton.setText(JarPackagerMessages.getString("JarPackageWizardPage.browseButton.text")); //$NON-NLS-1$
fDestinationBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
SWTUtil.setButtonDimensionHint(fDestinationBrowseButton);
fDestinationBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleDestinationBrowseButtonPressed();
}
});
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDescriptionFileBrowseButtonPressed() {
SaveAsDialog dialog= new SaveAsDialog(getContainer().getShell());
dialog.create();
dialog.getShell().setText(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.message")); //$NON-NLS-1$
dialog.setOriginalFile(createFileHandle(fJarPackage.getDescriptionLocation()));
if (dialog.open() == SaveAsDialog.OK) {
IPath path= dialog.getResult();
path= path.removeFileExtension().addFileExtension(JarPackagerUtil.DESCRIPTION_EXTENSION);
fDescriptionFileText.setText(path.toString());
}
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDestinationBrowseButtonPressed() {
FileDialog dialog= new FileDialog(getContainer().getShell(), SWT.SAVE);
dialog.setFilterExtensions(new String[] {"*.jar", "*.zip"}); //$NON-NLS-1$ //$NON-NLS-2$
String currentSourceString= getDestinationValue();
int lastSeparatorIndex= currentSourceString.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1) {
dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
dialog.setFileName(currentSourceString.substring(lastSeparatorIndex + 1, currentSourceString.length()));
}
else
dialog.setFileName(currentSourceString);
String selectedFileName= dialog.open();
if (selectedFileName != null)
fDestinationNamesCombo.setText(selectedFileName);
}
/**
* Returns the resource for the specified path.
*
* @param path the path for which the resource should be returned
* @return the resource specified by the path or <code>null</code>
*/
protected IResource findResource(IPath path) {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IStatus result= workspace.validatePath(
path.toString(),
IResource.ROOT | IResource.PROJECT | IResource.FOLDER | IResource.FILE);
if (result.isOK() && workspace.getRoot().exists(path))
return workspace.getRoot().findMember(path);
return null;
}
/**
* Creates the checkbox tree and list for selecting resources.
*
* @param parent the parent control
*/
protected void createInputGroup(Composite parent) {
int labelFlags= JavaElementLabelProvider.SHOW_BASICS
| JavaElementLabelProvider.SHOW_OVERLAY_ICONS
| JavaElementLabelProvider.SHOW_SMALL_ICONS;
ITreeContentProvider treeContentProvider=
new StandardJavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
fInputGroup= new CheckboxTreeAndListGroup(
parent,
JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()),
treeContentProvider,
new JavaElementLabelProvider(labelFlags),
new StandardJavaElementContentProvider(),
new JavaElementLabelProvider(labelFlags),
SWT.NONE,
SIZING_SELECTION_WIDGET_WIDTH,
SIZING_SELECTION_WIDGET_HEIGHT);
fInputGroup.addTreeFilter(new EmptyInnerPackageFilter());
fInputGroup.setTreeSorter(new JavaElementSorter());
fInputGroup.setListSorter(new JavaElementSorter());
fInputGroup.addTreeFilter(new ContainerFilter(ContainerFilter.FILTER_NON_CONTAINERS));
fInputGroup.addTreeFilter(new LibraryFilter());
fInputGroup.addListFilter(new ContainerFilter(ContainerFilter.FILTER_CONTAINERS));
fInputGroup.getTree().addListener(SWT.MouseUp, this);
fInputGroup.getTable().addListener(SWT.MouseUp, this);
}
/**
* Creates the export type controls.
*
* @param parent the parent control
*/
protected void createExportTypeGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout optionsLayout= new GridLayout();
optionsLayout.marginHeight= 0;
optionsGroup.setLayout(optionsLayout);
fExportClassFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportClassFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportClassFiles.text")); //$NON-NLS-1$
fExportClassFilesCheckbox.addListener(SWT.Selection, this);
fExportJavaFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportJavaFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportJavaFiles.text")); //$NON-NLS-1$
fExportJavaFilesCheckbox.addListener(SWT.Selection, this);
}
/**
* Updates the enablements of this page's controls. Subclasses may extend.
*/
protected void updateWidgetEnablements() {
}
/*
* Overrides method from IJarPackageWizardPage
*/
public boolean isPageComplete() {
boolean complete= validateSourceGroup();
complete= validateDestinationGroup() && complete;
complete= validateOptionsGroup() && complete;
if (complete)
setErrorMessage(null);
return complete;
}
/*
* Implements method from Listener
*/
public void handleEvent(Event e) {
if (getControl() == null)
return;
update();
}
protected void update() {
updateModel();
updateWidgetEnablements();
updatePageCompletion();
}
protected void updatePageCompletion() {
boolean pageComplete= isPageComplete();
setPageComplete(pageComplete);
if (pageComplete)
setErrorMessage(null);
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateDestinationGroup() {
if (fDestinationNamesCombo.getText().length() == 0) {
// Clear error
if (getErrorMessage() != null)
setErrorMessage(null);
if (getMessage() != null)
setMessage(null);
return false;
}
if (fJarPackage.getJarLocation().toString().endsWith("/")) { //$NON-NLS-1$
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
if (getWorkspaceLocation() != null && getWorkspaceLocation().isPrefixOf(fJarPackage.getJarLocation())) {
int segments= getWorkspaceLocation().matchingFirstSegments(fJarPackage.getJarLocation());
IPath path= fJarPackage.getJarLocation().removeFirstSegments(segments);
IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(path);
if (resource != null && resource.getType() == IResource.FILE) {
// test if included
if (JarPackagerUtil.contains(JarPackagerUtil.asResources(fJarPackage.getElements()), (IFile)resource)) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.cantExportJARIntoItself")); //$NON-NLS-1$
return false;
}
}
}
// Inform user about relative directory
String currentMessage= getMessage();
if (!(new File(fDestinationNamesCombo.getText()).isAbsolute())) {
if (currentMessage == null)
setMessage(JarPackagerMessages.getString("JarPackageWizardPage.info.relativeExportDestination"), WizardPage.INFORMATION); //$NON-NLS-1$
} else {
if (currentMessage != null)
setMessage(null);
}
return ensureTargetFileIsValid(fJarPackage.getJarLocation().toFile());
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateOptionsGroup() {
return true;
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateSourceGroup() {
if (!fExportClassFilesCheckbox.getSelection()
&& !fExportJavaFilesCheckbox.getSelection()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.noExportTypeChecked")); //$NON-NLS-1$
return false;
}
if (getSelectedResources().size() == 0) {
if (getErrorMessage() != null)
setErrorMessage(null);
return false;
}
if (fExportClassFilesCheckbox.getSelection() || !fExportJavaFilesCheckbox.getSelection())
return true;
// No class file export - check if there are source files
Iterator iter= getSelectedResourcesIterator();
while (iter.hasNext()) {
if (!(iter.next() instanceof IClassFile))
return true;
}
if (getErrorMessage() != null)
setErrorMessage(null);
return false;
}
/*
* Overwrides method from WizardExportPage
*/
protected IPath getResourcePath() {
return getPathFromText(fSourceNameField);
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Set the current input focus to self's destination entry field
*/
protected void giveFocusToDestination() {
fDestinationNamesCombo.setFocus();
}
/*
* Overrides method from WizardExportResourcePage
*/
protected void setupBasedOnInitialSelections() {
Iterator enum= fInitialSelection.iterator();
while (enum.hasNext()) {
Object selectedElement= enum.next();
if (selectedElement instanceof IResource && !((IResource)selectedElement).isAccessible())
continue;
if (selectedElement instanceof IJavaElement && !((IJavaElement)selectedElement).exists())
continue;
if (selectedElement instanceof ICompilationUnit || selectedElement instanceof IClassFile || selectedElement instanceof IFile)
fInputGroup.initialCheckListItem(selectedElement);
else {
if (selectedElement instanceof IFolder) {
// Convert resource to Java element if possible
IJavaElement je= JavaCore.create((IResource)selectedElement);
if (je != null && je.exists() && je.getJavaProject().isOnClasspath((IResource)selectedElement))
selectedElement= je;
}
fInputGroup.initialCheckTreeItem(selectedElement);
}
}
TreeItem[] items= fInputGroup.getTree().getItems();
int i= 0;
while (i < items.length && !items[i].getChecked())
i++;
if (i < items.length) {
fInputGroup.getTree().setSelection(new TreeItem[] {items[i]});
fInputGroup.getTree().showSelection();
fInputGroup.populateListViewer(items[i].getData());
}
}
/*
* Implements method from IJarPackageWizardPage.
*/
public void finish() {
saveWidgetValues();
}
/*
* Method declared on IWizardPage.
*/
public void setPreviousPage(IWizardPage page) {
super.setPreviousPage(page);
if (getControl() != null)
updatePageCompletion();
}
Object[] getSelectedElementsWithoutContainedChildren() {
Set closure= removeContainedChildren(fInputGroup.getWhiteCheckedTreeItems());
closure.addAll(getExportedNonContainers());
return closure.toArray();
}
private Set removeContainedChildren(Set elements) {
Set newList= new HashSet(elements.size());
Set javaElementResources= getCorrespondingContainers(elements);
Iterator iter= elements.iterator();
boolean removedOne= false;
while (iter.hasNext()) {
Object element= iter.next();
Object parent;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement) {
parent= ((IJavaElement)element).getParent();
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)parent;
try {
if (pkgRoot.getCorrespondingResource() instanceof IProject)
parent= pkgRoot.getJavaProject();
} catch (JavaModelException ex) {
// leave parent as is
}
}
}
else {
// unknown type
newList.add(element);
continue;
}
if (element instanceof IJavaModel || ((!(parent instanceof IJavaModel)) && (elements.contains(parent) || javaElementResources.contains(parent))))
removedOne= true;
else
newList.add(element);
}
if (removedOne)
return removeContainedChildren(newList);
else
return newList;
}
private Set getExportedNonContainers() {
Set whiteCheckedTreeItems= fInputGroup.getWhiteCheckedTreeItems();
Set exportedNonContainers= new HashSet(whiteCheckedTreeItems.size());
Set javaElementResources= getCorrespondingContainers(whiteCheckedTreeItems);
Iterator iter= fInputGroup.getAllCheckedListItems();
while (iter.hasNext()) {
Object element= iter.next();
Object parent= null;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement)
parent= ((IJavaElement)element).getParent();
if (!whiteCheckedTreeItems.contains(parent) && !javaElementResources.contains(parent))
exportedNonContainers.add(element);
}
return exportedNonContainers;
}
/*
* Create a list with the folders / projects that correspond
* to the Java elements (Java project, package, package root)
*/
private Set getCorrespondingContainers(Set elements) {
Set javaElementResources= new HashSet(elements.size());
Iterator iter= elements.iterator();
while (iter.hasNext()) {
Object element= iter.next();
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
int type= je.getElementType();
if (type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
// exclude default package since it is covered by the root
if (!(type == IJavaElement.PACKAGE_FRAGMENT && ((IPackageFragment)element).isDefaultPackage())) {
Object resource;
try {
resource= je.getCorrespondingResource();
} catch (JavaModelException ex) {
resource= null;
}
if (resource != null)
javaElementResources.add(resource);
}
}
}
}
return javaElementResources;
}
private Object[] getSelectedElements() {
return getSelectedResources().toArray();
}
/**
* @return the location or <code>null</code>
*/
private IPath getWorkspaceLocation() {
return ResourcesPlugin.getWorkspace().getRoot().getLocation();
}
}
|
37,197 |
Bug 37197 Basepath for relative pathes in JAR-exporter
|
The basepath for the JAR-exporter is the eclipse-install-directory. I prefer it to be the root of the project (the description is saved in), so that relative pathes end inside the project. Now: <jardesc> <jar path="workspace/projectdir/jar.jar"/> Desired: <jardesc> <jar path="jar.jar"/> Reason: To make the jardesc-files portable for shared projects
|
resolved fixed
|
2e55236
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-08T17:06:58Z | 2003-05-03T22:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarPackageData.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.jarpackager;
import java.io.InputStream;
import java.io.OutputStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.jarpackager.JarFileExportOperation;
import org.eclipse.jdt.internal.ui.jarpackager.JarPackageReader;
import org.eclipse.jdt.internal.ui.jarpackager.JarPackageWriter;
import org.eclipse.jdt.internal.ui.jarpackager.JarPackagerUtil;
import org.eclipse.jdt.internal.ui.jarpackager.ManifestProvider;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Model for a JAR package. Describes a JAR package including a bunch of
* useful options to generate a JAR file with a JAR writer.
*
* Clients may subclass.
*
* @see org.eclipse.jdt.ui.jarpackager.JarWriter
* @since 2.0
*/
public class JarPackageData {
private String fManifestVersion;
/*
* What to export - internal locations
* The list fExported* is null if fExport* is false)
*/
private boolean fExportClassFiles; // export generated class files and resources
private boolean fExportJavaFiles; // export java files and resources
/*
* Source folder hierarchy is created in the JAR if true
*/
private boolean fUseSourceFolderHierarchy;
/*
* Projects of which files are expored will be built if true
* and autobuild is off.
*/
private boolean fBuildIfNeeded;
/*
* Leaf elements (no containers) to export
*/
private Object[] fElements; // inside workspace
private IPath fJarLocation; // external location
private boolean fOverwrite;
private boolean fCompress;
private boolean fSaveDescription;
private IPath fDescriptionLocation; // internal location
/*
* A normal JAR has a manifest (fUsesManifest is true)
* The manifest can be contributed in two ways
* - it can be generated (fGenerateManifest is true) and
* - saved (fSaveManifest is true)
* - saved and reused (fReuseManifest is true implies: fSaveManifest is true)
* - it can be specified (fGenerateManifest is false and the
* manifest location must be specified (fManifestLocation))
*/
private boolean fUsesManifest;
private boolean fSaveManifest;
private boolean fReuseManifest;
private boolean fGenerateManifest;
private IPath fManifestLocation; // internal location
/*
* Sealing: a JAR can be
* - sealed (fSealJar is true) and a list of
* unsealed packages can be defined (fPackagesToUnseal)
* while the list of sealed packages is ignored
* - unsealed (fSealJar is false) and the list of
* sealed packages can be defined (fPackagesToSeal)
* while the list of unsealed packages is ignored
*/
private boolean fSealJar;
private IPackageFragment[] fPackagesToSeal;
private IPackageFragment[] fPackagesToUnseal;
private IType fManifestMainClass;
private String fComment; // the JAR comment
/*
* Error handling
*/
private boolean fExportErrors;
private boolean fExportWarnings;
// The provider for the manifest file
private IManifestProvider fManifestProvider;
public JarPackageData() {
setExportClassFiles(true);
setUseSourceFolderHierarchy(false);
setCompress(true);
setSaveDescription(false);
setJarLocation(new Path("")); //$NON-NLS-1$
setDescriptionLocation(new Path("")); //$NON-NLS-1$
setUsesManifest(true);
setGenerateManifest(true);
setReuseManifest(false);
setSaveManifest(false);
setManifestLocation(new Path("")); //$NON-NLS-1$
setExportErrors(true);
setExportWarnings(true);
setBuildIfNeeded(true);
}
// ----------- Accessors -----------
/**
* Tells whether the JAR is compressed or not.
*
* @return <code>true</code> if the JAR is compressed
*/
public boolean isCompressed() {
return fCompress;
}
/**
* Set whether the JAR is compressed or not.
*
* @param state a boolean indicating the new state
*/
public void setCompress(boolean state) {
fCompress= state;
}
/**
* Tells whether files can be overwritten without warning.
*
* @return <code>true</code> if files can be overwritten without warning
*/
public boolean allowOverwrite() {
return fOverwrite;
}
/**
* Set whether files can be overwritten without warning.
*
* @param state a boolean indicating the new state
*/
public void setOverwrite(boolean state) {
fOverwrite= state;
}
/**
* Tells whether class files and resources are exported.
*
* @return <code>true</code> if class files and resources are exported
*/
public boolean areClassFilesExported() {
return fExportClassFiles;
}
/**
* Set option to export class files and resources.
*
* @param state a boolean indicating the new state
*/
public void setExportClassFiles(boolean state) {
fExportClassFiles= state;
}
/**
* Tells whether java files and resources are exported.
*
* @return <code>true</code> if java files and resources are exported
*/
public boolean areJavaFilesExported() {
return fExportJavaFiles;
}
/**
* Set the option to export Java source and resources.
*
* @param state the new state
*/
public void setExportJavaFiles(boolean state) {
fExportJavaFiles= state;
}
/**
* Tells whether the source folder hierarchy is used.
* <p>
* Using the source folder hierarchy only makes sense if
* java files are but class files aren't exported.
* </p>
*
* @return <code>true</code> if source folder hierarchy is used
*/
public boolean useSourceFolderHierarchy() {
return fUseSourceFolderHierarchy;
}
/**
* Set the option to export the source folder hierarchy.
*
* @param state the new state
*/
public void setUseSourceFolderHierarchy(boolean state) {
fUseSourceFolderHierarchy= state;
}
/**
* Gets the location of the JAR file.
* This path is normally external to the workspace.
*
* @return the path representing the location of the JAR file
*/
public IPath getJarLocation() {
return fJarLocation;
}
/**
* Set the JAR file location.
*
* @param jarLocation a path denoting the location of the JAR file
*/
public void setJarLocation(IPath jarLocation) {
fJarLocation= jarLocation;
}
/**
* Tells whether the manifest file must be generated.
*
* @return <code>true</code> if the manifest has to be generated
*/
public boolean isManifestGenerated() {
return fGenerateManifest;
}
/**
* Set whether a manifest must be generated or not.
*
* @param state the new state
*/
public void setGenerateManifest(boolean state) {
fGenerateManifest= state;
}
/**
* Tells whether the manifest file must be saved to the
* specified file during the export operation.
*
* @return <code>true</code> if the manifest must be saved
* @see #getManifestLocation()
*/
public boolean isManifestSaved() {
return fSaveManifest;
}
/**
* Set whether the manifest file must be saved during export
* operation or not.
*
* @param state the new state
* @see #getManifestLocation()
*/
public void setSaveManifest(boolean state) {
fSaveManifest= state;
if (!fSaveManifest)
// can't reuse manifest if it is not saved
setReuseManifest(false);
}
/**
* Tells whether a previously generated manifest should be reused.
*
* @return <code>true</code> if the generated manifest will be reused when regenerating this JAR,
* <code>false</code> if the manifest has to be regenerated
*/
public boolean isManifestReused() {
return fReuseManifest;
}
/**
* Set whether a previously generated manifest should be reused.
*
* @param state the new state
*/
public void setReuseManifest(boolean state) {
fReuseManifest= state;
if (fReuseManifest)
// manifest must be saved in order to be reused
setSaveManifest(true);
}
/**
* Returns the location of a user-defined manifest file.
*
* @return the path of the user-defined manifest file location,
* or <code>null</code> if none is specified
*/
public IPath getManifestLocation() {
return fManifestLocation;
}
/**
* Set the location of a user-defined manifest file.
*
* @param manifestLocation the path of the user-define manifest location
*/
public void setManifestLocation(IPath manifestLocation) {
fManifestLocation= manifestLocation;
}
/**
* Gets the manifest file (as workspace resource).
*
* @return a file which points to the manifest
*/
public IFile getManifestFile() {
IPath path= getManifestLocation();
if (path.isValidPath(path.toString()) && path.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(path);
else
return null;
}
/**
* Gets the manifest version.
*
* @return a string containing the manifest version
*/
public String getManifestVersion() {
if (fManifestVersion == null)
return "1.0"; //$NON-NLS-1$
return fManifestVersion;
}
/**
* Set the manifest version.
*
* @param manifestVersion the string which contains the manifest version
*/
public void setManifestVersion(String manifestVersion) {
fManifestVersion= manifestVersion;
}
/**
* Answers whether a manifest must be included in the JAR.
*
* @return <code>true</code> if a manifest has to be included
*/
public boolean usesManifest() {
return fUsesManifest;
}
/**
* Set whether a manifest must be included in the JAR.
*
* @param state the new state
*/
public void setUsesManifest(boolean state) {
fUsesManifest= state;
}
/**
* Gets the manifest provider for this JAR package.
*
* @return the IManifestProvider
*/
public IManifestProvider getManifestProvider() {
if (fManifestProvider == null)
fManifestProvider= new ManifestProvider();
return fManifestProvider;
}
/**
* Set the manifest provider.
*
* @param manifestProvider the ManifestProvider to set
*/
public void setManifestProvider(IManifestProvider manifestProvider) {
fManifestProvider= manifestProvider;
}
/**
* Answers whether the JAR itself is sealed.
* The manifest will contain a "Sealed: true" statement.
* <p>
* This option should only be considered when the
* manifest file is generated.
* </p>
*
* @return <code>true</code> if the JAR must be selead
* @see #isManifestGenerated()
*/
public boolean isJarSealed() {
return fSealJar;
}
/**
* Set whether the JAR itself is sealed.
* The manifest will contain the following entry:
* Sealed: true
* <p>
* This option should only be considered when the
* manifest file is generated.
* </p>
*
* @param sealJar <code>true</code> if the JAR must be selead
* @see #isManifestGenerated()
*/
public void setSealJar(boolean sealJar) {
fSealJar= sealJar;
}
/**
* Set the packages which should be sealed.
* The following entry will be added to the manifest file for each package:
* Name: <name of the package>
* Sealed: true
* <p>
* This should only be used if the JAR itself is not sealed.
* </p>
*
* @param packagesToSeal an array of <code>IPackageFragment</code> to seal
*/
public void setPackagesToSeal(IPackageFragment[] packagesToSeal) {
fPackagesToSeal= packagesToSeal;
}
/**
* Gets the packages which should be sealed.
* The following entry will be added to the manifest file for each package:
* Name: <name of the package>
* Sealed: true
* <p>
* This should only be used if the JAR itself is not sealed.
* </p>
*
* @return an array of <code>IPackageFragment</code>
*/
public IPackageFragment[] getPackagesToSeal() {
if (fPackagesToSeal == null)
return new IPackageFragment[0];
else
return fPackagesToSeal;
}
/**
* Gets the packages which should explicitly be unsealed.
* The following entry will be added to the manifest file for each package:
* Name: <name of the package>
* Sealed: false
* <p>
* This should only be used if the JAR itself is sealed.
* </p>
*
* @return an array of <code>IPackageFragment</code>
*/
public IPackageFragment[] getPackagesToUnseal() {
if (fPackagesToUnseal == null)
return new IPackageFragment[0];
else
return fPackagesToUnseal;
}
/**
* Set the packages which should explicitly be unsealed.
* The following entry will be added to the manifest file for each package:
* Name: <name of the package>
* Sealed: false
* <p>
* This should only be used if the JAR itself is sealed.
* </p>
*
* @return an array of <code>IPackageFragment</code>
*/
public void setPackagesToUnseal(IPackageFragment[] packagesToUnseal) {
fPackagesToUnseal= packagesToUnseal;
}
/**
* Tells whether a description of this JAR package must be saved
* to a file by a JAR description writer during the export operation.
* <p>
* The JAR writer defines the format of the file.
* </p>
*
* @return <code>true</code> if this JAR package will be saved
* @see #getDescriptionLocation()
*/
public boolean isDescriptionSaved() {
return fSaveDescription;
}
/**
* Set whether a description of this JAR package must be saved
* to a file by a JAR description writer during the export operation.
* <p>
* The format is defined by the client who implements the
* reader/writer pair.
* </p>
* @param state a boolean containing the new state
* @see #getDescriptionLocation()
* @see IJarDescriptionWriter
*/
public void setSaveDescription(boolean state) {
fSaveDescription= state;
}
/**
* Returns the location of file containing the description of a JAR.
* This location is inside the workspace.
*
* @return the path of the description file location,
* or <code>null</code> if none is specified
*/
public IPath getDescriptionLocation() {
return fDescriptionLocation;
}
/**
* Set the location of the JAR description file.
*
* @param descriptionLocation the path of location
*/
public void setDescriptionLocation(IPath descriptionLocation) {
fDescriptionLocation= descriptionLocation;
}
/**
* Gets the description file (as workspace resource).
*
* @return a file which points to the description
*/
public IFile getDescriptionFile() {
IPath path= getDescriptionLocation();
if (path.isValidPath(path.toString()) && path.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(path);
else
return null;
}
/**
* Gets the manifest's main class.
*
* @return the type which contains the main class or,
* <code>null</code> if none is specified
*/
public IType getManifestMainClass() {
return fManifestMainClass;
}
/**
* Set the manifest's main class.
*
* @param mainClass the type with the main class for the manifest file
*/
public void setManifestMainClass(IType manifestMainClass) {
fManifestMainClass= manifestMainClass;
}
/**
* Returns the elements which will be exported.
* These elements are leaf objects e.g. <code>IFile</code>
* and not containers.
*
* @return an array of leaf objects
*/
public Object[] getElements() {
if (fElements == null)
setElements(new Object[0]);
return fElements;
}
/**
* Set the elements which will be exported.
*
* These elements are leaf objects e.g. <code>IFile</code>.
* and not containers.
*
* @param elements an array with leaf objects
*/
public void setElements(Object[] elements) {
fElements= elements;
}
/**
* Returns the JAR's comment.
*
* @return the comment string or <code>null</code>
* if the JAR does not contain a comment
*/
public String getComment() {
return fComment;
}
/**
* Sets the JAR's comment.
*
* @param comment a string or <code>null</code>
* if the JAR does not contain a comment
*/
public void setComment(String comment) {
fComment= comment;
}
/**
* Tell whether errors are logged.
* <p>
* The export operation decides where and
* how the errors are logged.
* </p>
*
* @return <code>true</code> if errors are logged
* @deprecated will be removed in final 2.0
*/
public boolean logErrors() {
return true;
}
/**
* Set whether errors are logged.
* <p>
* The export operation decides where and
* how the errors are logged.
* </p>
*
* @param logErrors <code>true</code> if errors are logged
* @deprecated will be removed in final 2.0
*/
public void setLogErrors(boolean logErrors) {
// always true
}
/**
* Tells whether warnings are logged or not.
* <p>
* The export operation decides where and
* how the warnings are logged.
* </p>
*
* @return <code>true</code> if warnings are logged
* @deprecated will be removed in final 2.0
*/
public boolean logWarnings() {
return true;
}
/**
* Set if warnings are logged.
* <p>
* The export operation decides where and
* how the warnings are logged.
* </p>
*
* @param logWarnings <code>true</code> if warnings are logged
* @deprecated will be removed in final 2.0
*/
public void setLogWarnings(boolean logWarnings) {
// always true
}
/**
* Answers if compilation units with errors are exported.
*
* @return <code>true</code> if CUs with errors should be exported
*/
public boolean areErrorsExported() {
return fExportErrors;
}
/**
* Set if compilation units with errors are exported.
*
* @param exportErrors <code>true</code> if CUs with errors should be exported
*/
public void setExportErrors(boolean exportErrors) {
fExportErrors= exportErrors;
}
/**
* Answers if compilation units with warnings are exported.
*
* @return <code>true</code> if CUs with warnings should be exported
*/
public boolean exportWarnings() {
return fExportWarnings;
}
/**
* Set if compilation units with warnings are exported.
*
* @param exportWarnings <code>true</code> if CUs with warnings should be exported
*/
public void setExportWarnings(boolean exportWarnings) {
fExportWarnings= exportWarnings;
}
/**
* Answers if a build should be performed before exporting files.
* This flag is only considered if auto-build is off.
*
* @return a boolean telling if a build should be performed
*/
public boolean isBuildingIfNeeded() {
return fBuildIfNeeded;
}
/**
* Set if a build should be performed before exporting files.
* This flag is only considered if auto-build is off.
*
* @param a boolean telling if a build should be performed
*/
public void setBuildIfNeeded(boolean fBuildIfNeeded) {
this.fBuildIfNeeded= fBuildIfNeeded;
}
// ----------- Utility methods -----------
/**
* Finds the class files for the given java file
* and returns them.
* <p>
* This is a hook for subclasses which want to implement
* a different strategy for finding the class files. The default
* strategy is to query the class files for the source file
* name attribute. If this attribute is missing then all class
* files in the corresponding output folder are exported.
* </p>
* <p>
* A CoreException can be thrown if an error occurs during this
* operation. The <code>CoreException</code> will not stop the export
* process but adds the status object to the status of the
* export runnable.
* </p>
*
* @param javaFile a .java file
* @return an array with class files or <code>null</code> to used the default strategy
* @throws CoreException if find failed, e.g. I/O error or resource out of synch
* @see IJarExportRunnable#getStatus()
*/
public IFile[] findClassfilesFor(IFile javaFile) throws CoreException {
return null;
}
/**
* Creates and returns a JarWriter for this JAR package.
*
* @param parent the shell used to display question dialogs,
* or <code>null</code> if "false/no/cancel" is the answer
* and no dialog should be shown
* @return a JarWriter
* @see JarWriter
*/
public JarWriter createJarWriter(Shell parent) throws CoreException {
return new JarWriter(this, parent);
}
/**
* Creates and returns a JarExportRunnable.
*
* @param parent the parent for the dialog,
* or <code>null</code> if no questions should be asked and
* no checks for unsaved files should be made.
* @return a JarExportRunnable
*/
public IJarExportRunnable createJarExportRunnable(Shell parent) {
return new JarFileExportOperation(this, parent);
}
/**
* Creates and returns a JarExportRunnable for a list of JAR package
* data objects.
*
* @param jarPackagesData an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public IJarExportRunnable createJarExportRunnable(JarPackageData[] jarPackagesData, Shell parent) {
return new JarFileExportOperation(jarPackagesData, parent);
}
/**
* Creates and returns a JAR package data description writer
* for this JAR package data object.
* <p>
* It is the client's responsibility to close this writer.
* </p>
* @param outputStream the output stream to write to
* @return a JarWriter
*/
public IJarDescriptionWriter createJarDescriptionWriter(OutputStream outputStream) {
return new JarPackageWriter(outputStream);
}
/**
* Creates and returns a JAR package data description reader
* for this JAR package data object.
* <p>
* It is the client's responsibility to close this reader.
* </p>
* @param inputStream the input stream to read from
* @return a JarWriter
*/
public IJarDescriptionReader createJarDescriptionReader(InputStream inputStream) {
return new JarPackageReader(inputStream);
}
/**
* Tells whether this JAR package data can be used to generate
* a valid JAR.
*
* @return <code>true</code> if the JAR Package info is valid
*/
public boolean isValid() {
return (areClassFilesExported() || areJavaFilesExported())
&& getElements() != null && getElements().length > 0
&& getJarLocation() != null
&& isManifestAccessible()
&& isMainClassValid(new BusyIndicatorRunnableContext());
}
/**
* Tells whether a manifest is available.
*
* @return <code>true</code> if the manifest is generated or the provided one is accessible
*/
public boolean isManifestAccessible() {
if (isManifestGenerated())
return true;
IFile file= getManifestFile();
return file != null && file.isAccessible();
}
/**
* Tells whether the specified manifest main class is valid.
*
* @return <code>true</code> if a main class is specified and valid
*/
public boolean isMainClassValid(IRunnableContext context) {
return JarPackagerUtil.isMainClassValid(this, context);
}
}
|
37,197 |
Bug 37197 Basepath for relative pathes in JAR-exporter
|
The basepath for the JAR-exporter is the eclipse-install-directory. I prefer it to be the root of the project (the description is saved in), so that relative pathes end inside the project. Now: <jardesc> <jar path="workspace/projectdir/jar.jar"/> Desired: <jardesc> <jar path="jar.jar"/> Reason: To make the jardesc-files portable for shared projects
|
resolved fixed
|
2e55236
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-08T17:06:58Z | 2003-05-03T22:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarWriter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.jarpackager;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.CRC32;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.jarpackager.JarPackagerMessages;
import org.eclipse.jdt.internal.ui.jarpackager.JarPackagerUtil;
/**
* Creates a JAR file for the given JAR package data.
*
* Clients may subclass.
*
* @see org.eclipse.jdt.ui.jarpackager.JarPackageData
* @since 2.0
*/
public class JarWriter {
private JarOutputStream fJarOutputStream;
private JarPackageData fJarPackage;
/**
* Creates an instance which is used to create a JAR based
* on the given JarPackage.
*
* @param jarPackage the JAR specification
* @param parent the shell used to display question dialogs,
* or <code>null</code> if "false/no/cancel" is the answer
* and no dialog should be shown
* @throws CoreException to signal any other unusal termination.
* This can also be used to return information
* in the status object.
*/
public JarWriter(JarPackageData jarPackage, Shell parent) throws CoreException {
Assert.isNotNull(jarPackage, "The JAR specification is null"); //$NON-NLS-1$
fJarPackage= jarPackage;
Assert.isTrue(fJarPackage.isValid(), "The JAR package specification is invalid"); //$NON-NLS-1$
if (!canCreateJar(parent))
throw new OperationCanceledException();
try {
if (fJarPackage.usesManifest() && fJarPackage.areClassFilesExported()) {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
fJarOutputStream= new JarOutputStream(new FileOutputStream(fJarPackage.getJarLocation().toOSString()), manifest);
} else
fJarOutputStream= new JarOutputStream(new FileOutputStream(fJarPackage.getJarLocation().toOSString()));
String comment= jarPackage.getComment();
if (comment != null)
fJarOutputStream.setComment(comment);
} catch (IOException ex) {
throw JarPackagerUtil.createCoreException(ex.getLocalizedMessage(), ex);
}
}
/**
* Closes the archive and does all required cleanup.
*
* @throws CoreException to signal any other unusal termination.
* This can also be used to return information
* in the status object.
*/
public void close() throws CoreException {
if (fJarOutputStream != null)
try {
fJarOutputStream.close();
registerInWorkspaceIfNeeded();
} catch (IOException ex) {
throw JarPackagerUtil.createCoreException(ex.getLocalizedMessage(), ex);
}
}
/**
* Writes the passed resource to the current archive.
*
* @param resource the file to be written
* @param destinationPath the path for the file inside the archive
* @throws CoreException to signal any other unusal termination.
* This can also be used to return information
* in the status object.
*/
public void write(IFile resource, IPath destinationPath) throws CoreException {
ByteArrayOutputStream output= null;
BufferedInputStream contentStream= null;
try {
output= new ByteArrayOutputStream();
if (!resource.isLocal(IResource.DEPTH_ZERO)) {
String message= JarPackagerMessages.getFormattedString("JarWriter.error.fileNotAccessible", resource.getFullPath()); //$NON-NLS-1$
throw JarPackagerUtil.createCoreException(message, null);
}
contentStream= new BufferedInputStream(resource.getContents(false));
int chunkSize= 4096;
byte[] readBuffer= new byte[chunkSize];
int count;
while ((count= contentStream.read(readBuffer, 0, chunkSize)) != -1)
output.write(readBuffer, 0, count);
} catch (IOException ex) {
throw JarPackagerUtil.createCoreException(ex.getLocalizedMessage(), ex);
} finally {
try {
if (output != null)
output.close();
if (contentStream != null)
contentStream.close();
} catch (IOException ex) {
throw JarPackagerUtil.createCoreException(ex.getLocalizedMessage(), ex);
}
}
try {
IPath fileLocation= resource.getLocation();
long lastModified= System.currentTimeMillis();
if (fileLocation != null) {
File file= new File(fileLocation.toOSString());
if (file.exists())
lastModified= file.lastModified();
}
write(destinationPath, output.toByteArray(), lastModified);
} catch (IOException ex) {
// Ensure full path is visible
String message= null;
if (ex.getLocalizedMessage() != null)
message= JarPackagerMessages.getFormattedString("JarWriter.writeProblemWithMessage", resource.getFullPath(), ex.getLocalizedMessage()); //$NON-NLS-1$;
else
message= JarPackagerMessages.getFormattedString("JarWriter.writeProblem", resource.getFullPath()); //$NON-NLS-1$
throw JarPackagerUtil.createCoreException(message, ex);
}
}
/**
* Creates a new JarEntry with the passed path and contents, and writes it
* to the current archive.
*
* @param path the path inside the archive
* @param contents the bytes to write
* @param lastModified a long which represents the last modification date
* @throws IOException if an I/O error has occurred
*/
protected void write(IPath path, byte[] contents, long lastModified) throws IOException {
JarEntry newEntry= new JarEntry(path.toString().replace(File.separatorChar, '/'));
if (fJarPackage.isCompressed())
newEntry.setMethod(JarEntry.DEFLATED);
// Entry is filled automatically.
else {
newEntry.setMethod(JarEntry.STORED);
newEntry.setSize(contents.length);
CRC32 checksumCalculator= new CRC32();
checksumCalculator.update(contents);
newEntry.setCrc(checksumCalculator.getValue());
}
// Set modification time
newEntry.setTime(lastModified);
try {
fJarOutputStream.putNextEntry(newEntry);
fJarOutputStream.write(contents);
} finally {
/*
* Commented out because some JREs throw an NPE if a stream
* is closed twice. This works because
* a) putNextEntry closes the previous entry
* b) closing the stream closes the last entry
*/
// fJarOutputStream.closeEntry();
}
}
/**
* Checks if the JAR file can be overwritten.
* If the JAR package setting does not allow to overwrite the JAR
* then a dialog will ask the user again.
*
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
* @return <code>true</code> if it is OK to create the JAR
*/
protected boolean canCreateJar(Shell parent) {
File file= fJarPackage.getJarLocation().toFile();
if (file.exists()) {
if (!file.canWrite())
return false;
if (fJarPackage.allowOverwrite())
return true;
return parent != null && JarPackagerUtil.askForOverwritePermission(parent, fJarPackage.getJarLocation().toOSString());
}
// Test if directory exists
String path= file.getAbsolutePath();
int separatorIndex = path.lastIndexOf(File.separator);
if (separatorIndex == -1) // ie.- default dir, which is fine
return true;
File directory= new File(path.substring(0, separatorIndex));
if (!directory.exists()) {
if (JarPackagerUtil.askToCreateDirectory(parent, directory))
return directory.mkdirs();
else
return false;
}
return true;
}
private void registerInWorkspaceIfNeeded() {
IPath jarPath= fJarPackage.getJarLocation();
IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (int i= 0; i < projects.length; i++) {
IProject project= projects[i];
IPath projectLocation= project.getLocation();
boolean isInWorkspace= projectLocation != null && projectLocation.isPrefixOf(jarPath);
if (isInWorkspace)
try {
jarPath= jarPath.removeFirstSegments(projectLocation.segmentCount());
jarPath= jarPath.removeLastSegments(1);
IResource containingFolder= project.findMember(jarPath);
if (containingFolder != null && containingFolder.isAccessible())
containingFolder.refreshLocal(IResource.DEPTH_ONE, null);
} catch (CoreException ex) {
// don't refresh the folder but log the problem
JavaPlugin.log(ex);
} finally {
return;
}
}
}
}
|
31,794 |
Bug 31794 Types views show too many errors
|
create this in 1 file (e.g. A.java) class B{} class A extends B{ + //<<syntax error } class P {} class O extends P{} in java browsing you see error decorations for all 4 types, which is incorrect
|
verified fixed
|
2da5160
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-09T09:39:30Z | 2003-02-13T18:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/TopLevelTypeProblemsLabelDecorator.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.browsing;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.ui.ProblemsLabelDecorator;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
/**
* Decorates top-level types with problem markers that
* are above the first type.
*/
class TopLevelTypeProblemsLabelDecorator extends ProblemsLabelDecorator {
public TopLevelTypeProblemsLabelDecorator(ImageDescriptorRegistry registry) {
super(registry);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.ui.ProblemsLabelDecorator#isInside(int, ISourceReference)
*/
protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException {
// XXX: Work in progress for problem decorator being a workbench decorator
// IDecoratorManager decoratorMgr= PlatformUI.getWorkbench().getDecoratorManager();
// if (!decoratorMgr.getEnabled("org.eclipse.jdt.ui.problem.decorator")) //$NON-NLS-1$
// return false;
if (!(sourceElement instanceof IType) || ((IType)sourceElement).getDeclaringType() != null)
return false;
ICompilationUnit cu= ((IType)sourceElement).getCompilationUnit();
if (cu == null)
return false;
IType[] types= cu.getAllTypes();
if (types.length < 1)
return false;
ISourceRange range= types[0].getSourceRange();
if (range == null)
return false;
return pos < range.getOffset() || isInside(pos, cu.getSourceRange());
}
private boolean isInside(int pos, ISourceRange range) {
if (range == null)
return false;
int offset= range.getOffset();
return offset <= pos && pos < offset + range.getLength();
}
}
|
35,543 |
Bug 35543 Export Jar takes forever [jar creation]
|
The "Saving Files..." part of the Export Jar wizard takes several minutes. This could be because the jar I am rebuilding in on my classpath... I do not know since the feedback only says "Saving Files...". So, perhaps only better feedback is needed if e is recompiling my project. Version: 2.1.0 Build id: 200303202147
|
resolved fixed
|
6819939
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-09T12:34:09Z | 2003-03-22T19:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import java.util.zip.ZipException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
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.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static class MessageMultiStatus extends MultiStatus {
MessageMultiStatus(String pluginId, int code, String message, Throwable exception) {
super(pluginId, code, message, exception);
}
/*
* allows to change the message
*/
protected void setMessage(String message) {
super.setMessage(message);
}
}
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MessageMultiStatus fStatus;
private StandardJavaElementContentProvider fJavaElementContentProvider;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param jarPackages an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fStatus= new MessageMultiStatus(JavaPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
fJavaElementContentProvider= new StandardJavaElementContentProvider();
}
protected void addToStatus(CoreException ex) {
IStatus status= ex.getStatus();
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
message= JarPackagerMessages.getString("JarFileExportOperation.coreErrorDuringExport"); //$NON-NLS-1$
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
}
fStatus.add(status);
}
/**
* Adds a new info to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addInfo(String message, Throwable error) {
fStatus.add(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
continue;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
int type= je.getElementType();
if (type != IJavaElement.CLASS_FILE && type != IJavaElement.COMPILATION_UNIT) {
exportJavaElement(progressMonitor, je);
return;
}
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= findPackageFragmentRoot(jProject, resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
boolean isOnBuildPath;
isOnBuildPath= jProject.isOnClasspath(resource);
if (!isOnBuildPath || (mustUseSourceFolderHierarchy() && !pkgRoot.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportJavaElement(IProgressMonitor progressMonitor, IJavaElement je) throws java.lang.InterruptedException {
if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && ((IPackageFragmentRoot)je).isArchive())
return;
Object[] children= fJavaElementContentProvider.getChildren(je);
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
if (jProject == null || path == null || path.segmentCount() <= 0)
return null;
IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
if (pkgRoot != null)
return pkgRoot;
else
return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
// Handle case where META-INF/MANIFEST.MF is part of the exported files
if (fJarPackage.areClassFilesExported() && destinationPath.toString().equals("META-INF/MANIFEST.MF")) {//$NON-NLS-1$
if (fJarPackage.isManifestGenerated())
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.didNotAddManifestToJar", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == IPackageFragmentRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (CoreException ex) {
Throwable realEx= ex.getStatus().getException();
if (realEx instanceof ZipException && realEx.getMessage() != null && realEx.getMessage().startsWith("duplicate entry:")) //$NON-NLS-1$
addWarning(ex.getMessage(), realEx);
else
addToStatus(ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
if (!jProject.isOnClasspath(resource))
return;
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, pkgRoot, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
* @deprecated As of 2.1 use the method with additional IPackageFragmentRoot paramter
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
return filesOnClasspath(file, pathInJar, javaProject, null, progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @param pkgRoot the package fragment root that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IPackageFragmentRoot pkgRoot, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= null;
if (pkgRoot != null) {
IClasspathEntry cpEntry= pkgRoot.getRawClasspathEntry();
if (cpEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE)
outputPath= cpEntry.getOutputLocation();
}
if (outputPath == null)
// Use default output location
outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
IPath location= classContainer.getLocation();
String containerName= ""; //$NON-NLS-1$
if (location != null)
containerName= location.toFile().toString();
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", containerName); //$NON-NLS-1$
addInfo(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader= null;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
IPath location= classFile.getLocation();
if (location != null) {
File file= location.toFile();
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(location.toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", file), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", file), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", file), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* The result is a status object containing individual
* status objects.
*
* @return the status of this operation
*/
public IStatus getStatus() {
String message= null;
switch (fStatus.getSeverity()) {
case IStatus.OK:
message= ""; //$NON-NLS-1$
break;
case IStatus.INFO:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithInfo"); //$NON-NLS-1$
break;
case IStatus.WARNING:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"); //$NON-NLS-1$
break;
case IStatus.ERROR:
if (fJarPackages.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
break;
default:
// defensive code in case new severity is defined
message= ""; //$NON-NLS-1$
break;
}
fStatus.setMessage(message);
return fStatus;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded() && fJarPackage.areClassFilesExported()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (CoreException ex) {
addToStatus(ex);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (CoreException ex) {
addToStatus(ex);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getAbsoluteJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
File targetFile= fJarPackage.getAbsoluteJarLocation().toFile();
if (targetFile.exists() && !targetFile.canWrite()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.jarFileExistsAndNotWritable"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
if (fParentShell == null)
// no checking if shell is null
return true;
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles() {
IEditorPart[] dirtyEditors= getDirtyEditors(fParentShell);
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (JarPackagerUtil.contains(selection, dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= getDirtyEditors(fParentShell);
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.areClassFilesExported() && fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
private IEditorPart[] getDirtyEditors(Shell parent) {
Display display= parent.getDisplay();
final Object[] result= new Object[1];
display.syncExec(
new Runnable() {
public void run() {
result[0]= JavaPlugin.getDirtyEditors();
}
}
);
return (IEditorPart[])result[0];
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString()))
descriptionFile.setContents(fileInput, true, true, null);
} else
descriptionFile.create(fileInput, true, null);
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString()))
manifestFile.setContents(fileInput, true, true, null);
} else
manifestFile.create(fileInput, true, null);
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(JavaCore.COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
private boolean mustUseSourceFolderHierarchy() {
return fJarPackage.useSourceFolderHierarchy() && fJarPackage.areJavaFilesExported() && !fJarPackage.areClassFilesExported();
}
}
|
37,290 |
Bug 37290 call hierarchy: Searching for callees into anonymous inner classes fails
| null |
resolved fixed
|
54ee582
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-09T12:34:54Z | 2003-05-06T19:40:00Z |
org.eclipse.jdt.ui/core
| |
37,290 |
Bug 37290 call hierarchy: Searching for callees into anonymous inner classes fails
| null |
resolved fixed
|
54ee582
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-09T12:34:54Z | 2003-05-06T19:40:00Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/CalleeAnalyzerVisitor.java
| |
37,333 |
Bug 37333 Failure Trace cannot navigate to non-public class in CU throwing Exception [JUnit]
|
import junit.framework.TestCase; class A { public void test() { throw new RuntimeException(); } } public class Test extends TestCase { public void testA() { new A().test(); } } @@@@ My failure trace will be: java.lang.RuntimeException at A.test(Test.java:5) at Test2.testA(Test.java:12) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:392) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:276) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:167) @@@@ Clicking on "at A.test(Test.java:5)" will show an dialog stating "Test class not found in project".
|
closed fixed
|
ef49778
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-10T21:39:31Z | 2003-05-07T15:06:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FailureTraceView.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.Assert;
/**
* A view that shows a stack trace of a failed test.
*/
class FailureTraceView implements IMenuListener {
private static final String FRAME_PREFIX= "at "; //$NON-NLS-1$
private Table fTable;
private TestRunnerViewPart fTestRunner;
private String fInputTrace;
private final Clipboard fClipboard;
private final Image fStackIcon= TestRunnerViewPart.createImage("obj16/stkfrm_obj.gif"); //$NON-NLS-1$
private final Image fExceptionIcon= TestRunnerViewPart.createImage("obj16/exc_catch.gif"); //$NON-NLS-1$
public FailureTraceView(Composite parent, Clipboard clipboard, TestRunnerViewPart testRunner) {
Assert.isNotNull(clipboard);
fTable= new Table(parent, SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL);
fTestRunner= testRunner;
fClipboard= clipboard;
fTable.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e){
handleDoubleClick(e);
}
});
initMenu();
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
}
void handleDoubleClick(MouseEvent e) {
if(fTable.getSelection().length != 0) {
Action a= createOpenEditorAction(getSelectedText());
if (a != null)
a.run();
}
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTable);
fTable.setMenu(menu);
}
public void menuAboutToShow(IMenuManager manager) {
if (fTable.getSelectionCount() > 0) {
Action a= createOpenEditorAction(getSelectedText());
if (a != null)
manager.add(a);
manager.add(new CopyTraceAction(FailureTraceView.this, fClipboard));
}
}
public String getTrace() {
return fInputTrace;
}
private String getSelectedText() {
return fTable.getSelection()[0].getText();
}
private Action createOpenEditorAction(String traceLine) {
try {
//TODO: works for JDK stack trace only
String testName= traceLine;
testName= testName.substring(testName.indexOf(FRAME_PREFIX)); //$NON-NLS-1$
testName= testName.substring(FRAME_PREFIX.length(), testName.indexOf('(')).trim();
testName= testName.substring(0, testName.lastIndexOf('.'));
int innerSeparatorIndex= testName.indexOf('$');
if (innerSeparatorIndex != -1)
testName= testName.substring(0, innerSeparatorIndex);
String lineNumber= traceLine;
lineNumber= lineNumber.substring(lineNumber.indexOf(':') + 1, lineNumber.indexOf(")")); //$NON-NLS-1$
int line= Integer.valueOf(lineNumber).intValue();
return new OpenEditorAtLineAction(fTestRunner, testName, line);
} catch(NumberFormatException e) {
}
catch(IndexOutOfBoundsException e) {
}
return null;
}
private void disposeIcons(){
if (fExceptionIcon != null && !fExceptionIcon.isDisposed())
fExceptionIcon.dispose();
if (fStackIcon != null && !fStackIcon.isDisposed())
fStackIcon.dispose();
}
/**
* Returns the composite used to present the trace
*/
Composite getComposite(){
return fTable;
}
/**
* Refresh the table from the the trace.
*/
public void refresh() {
updateTable(fInputTrace);
}
/**
* Shows a TestFailure
*/
public void showFailure(String trace) {
if (fInputTrace == trace)
return;
fInputTrace= trace;
updateTable(trace);
}
private void updateTable(String trace) {
if(trace == null || trace.trim().equals("")) { //$NON-NLS-1$
clear();
return;
}
trace= trace.trim();
fTable.setRedraw(false);
fTable.removeAll();
fillTable(filterStack(trace));
fTable.setRedraw(true);
}
private void fillTable(String trace) {
StringReader stringReader= new StringReader(trace);
BufferedReader bufferedReader= new BufferedReader(stringReader);
String line;
try {
// first line contains the thrown exception
line= bufferedReader.readLine();
if (line == null)
return;
TableItem tableItem= new TableItem(fTable, SWT.NONE);
String itemLabel= line.replace('\t', ' ');
tableItem.setText(itemLabel);
tableItem.setImage(fExceptionIcon);
// the stack frames of the trace
while ((line= bufferedReader.readLine()) != null) {
itemLabel= line.replace('\t', ' ');
tableItem= new TableItem(fTable, SWT.NONE);
// heuristic for detecting a stack frame - works for JDK
if ((itemLabel.indexOf(" at ") >= 0)) { //$NON-NLS-1$
tableItem.setImage(fStackIcon);
}
tableItem.setText(itemLabel);
}
} catch (IOException e) {
TableItem tableItem= new TableItem(fTable, SWT.NONE);
tableItem.setText(trace);
}
}
/**
* Shows other information than a stack trace.
*/
public void setInformation(String text) {
clear();
TableItem tableItem= new TableItem(fTable, SWT.NONE);
tableItem.setText(text);
}
/**
* Clears the non-stack trace info
*/
public void clear() {
fTable.removeAll();
fInputTrace= null;
}
private String filterStack(String stackTrace) {
if (!JUnitPreferencePage.getFilterStack() || stackTrace == null)
return stackTrace;
StringWriter stringWriter= new StringWriter();
PrintWriter printWriter= new PrintWriter(stringWriter);
StringReader stringReader= new StringReader(stackTrace);
BufferedReader bufferedReader= new BufferedReader(stringReader);
String line;
String[] patterns= JUnitPreferencePage.getFilterPatterns();
try {
while ((line= bufferedReader.readLine()) != null) {
if (!filterLine(patterns, line))
printWriter.println(line);
}
} catch (IOException e) {
return stackTrace; // return the stack unfiltered
}
return stringWriter.toString();
}
private boolean filterLine(String[] patterns, String line) {
String pattern;
int len;
for (int i= (patterns.length - 1); i >= 0; --i) {
pattern= patterns[i];
len= pattern.length() - 1;
if (pattern.charAt(len) == '*') {
//strip trailing * from a package filter
pattern= pattern.substring(0, len);
} else if (Character.isUpperCase(pattern.charAt(0))) {
//class in the default package
pattern= FRAME_PREFIX + pattern + '.';
} else {
//class names start w/ an uppercase letter after the .
final int lastDotIndex= pattern.lastIndexOf('.');
if ((lastDotIndex != -1) && (lastDotIndex != len) && Character.isUpperCase(pattern.charAt(lastDotIndex + 1)))
pattern += '.'; //append . to a class filter
}
if (line.indexOf(pattern) > 0)
return true;
}
return false;
}
}
|
37,333 |
Bug 37333 Failure Trace cannot navigate to non-public class in CU throwing Exception [JUnit]
|
import junit.framework.TestCase; class A { public void test() { throw new RuntimeException(); } } public class Test extends TestCase { public void testA() { new A().test(); } } @@@@ My failure trace will be: java.lang.RuntimeException at A.test(Test.java:5) at Test2.testA(Test.java:12) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:392) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:276) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:167) @@@@ Clicking on "at A.test(Test.java:5)" will show an dialog stating "Test class not found in project".
|
closed fixed
|
ef49778
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-10T21:39:31Z | 2003-05-07T15:06:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/OpenEditorAtLineAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
/**
* Open a test in the Java editor and reveal a given line
*/
public class OpenEditorAtLineAction extends OpenEditorAction {
private int fLineNumber;
/**
* Constructor for OpenEditorAtLineAction.
*/
public OpenEditorAtLineAction(TestRunnerViewPart testRunner, String className, int line) {
super(testRunner, className);
WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.OPENEDITORATLINE_ACTION);
fLineNumber= line;
}
protected void reveal(ITextEditor textEditor) {
if (fLineNumber >= 0) {
try {
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
textEditor.selectAndReveal(document.getLineOffset(fLineNumber-1), document.getLineLength(fLineNumber-1));
} catch (BadLocationException x) {
// marker refers to invalid text position -> do nothing
}
}
}
protected IJavaElement findElement(IJavaProject project, String className) throws JavaModelException {
return project.findType(className);
}
public boolean isEnabled() {
try {
return getLaunchedProject().findType(getClassName()) != null;
} catch (JavaModelException e) {
}
return false;
}
}
|
37,445 |
Bug 37445 call hierarchy: Open Call Hierarchy beeps instead of showing info about the current method
|
Reporting against I20030506 build. As of I20030422, the "Open Call Hierarchy" action worked for the method in which the cursor was located. In the new build, it emits a confusing beep instead of opening the call hierarchy for the current method. It works as expected if you highlight the method's name, but the other way of invoking it was more convenient. If the new behavior is intended, at the very least some hint should be provided that a method selection is required, not just a beep. I tracked down the problem to OpenCallHierarchyAction.java:113 where CallHierarchyUI.getCandidates is called and returns null instead of the "current" IMethod.
|
resolved fixed
|
3a24d35
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T09:38:20Z | 2003-05-09T17:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyUI.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.callhierarchy.CallHierarchy;
import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.texteditor.ITextEditor;
public class CallHierarchyUI {
private static final int DEFAULT_MAX_CALL_DEPTH= 10;
private static final String PREF_MAX_CALL_DEPTH = "PREF_MAX_CALL_DEPTH"; //$NON-NLS-1$
private static CallHierarchyUI fgInstance;
private CallHierarchyUI() { }
public static CallHierarchyUI getDefault() {
if (fgInstance == null) {
fgInstance = new CallHierarchyUI();
}
return fgInstance;
}
/**
* Returns the maximum tree level allowed
* @return int
*/
public int getMaxCallDepth() {
int maxCallDepth;
IPreferenceStore settings = JavaPlugin.getDefault().getPreferenceStore();
maxCallDepth = settings.getInt(PREF_MAX_CALL_DEPTH);
if (maxCallDepth < 1 || maxCallDepth > 99) {
maxCallDepth= DEFAULT_MAX_CALL_DEPTH;
}
return maxCallDepth;
}
public void setMaxCallDepth(int maxCallDepth) {
IPreferenceStore settings = JavaPlugin.getDefault().getPreferenceStore();
settings.setValue(PREF_MAX_CALL_DEPTH, maxCallDepth);
}
public static void jumpToMember(IJavaElement element) {
if (element != null) {
try {
IEditorPart methodEditor = EditorUtility.openInEditor(element, true);
JavaUI.revealInEditor(methodEditor, (IJavaElement) element);
} catch (JavaModelException e) {
JavaPlugin.log(e);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
}
public static void jumpToLocation(CallLocation callLocation) {
try {
IEditorPart methodEditor = EditorUtility.openInEditor(callLocation.getMember(),
false);
if (methodEditor instanceof ITextEditor) {
ITextEditor editor = (ITextEditor) methodEditor;
editor.selectAndReveal(callLocation.getStart(),
(callLocation.getEnd() - callLocation.getStart()));
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
public static void openInEditor(Object element, Shell shell, String title) {
CallLocation callLocation= null;
if (element instanceof CallLocation) {
callLocation= (CallLocation) element;
} else if (element instanceof CallLocation) {
callLocation= CallHierarchy.getCallLocation(element);
}
if (callLocation == null) {
return;
}
try {
boolean activateOnOpen = OpenStrategy.activateOnOpen();
IEditorPart methodEditor = EditorUtility.openInEditor(callLocation.getMember(),
activateOnOpen);
if (methodEditor instanceof ITextEditor) {
ITextEditor editor = (ITextEditor) methodEditor;
editor.selectAndReveal(callLocation.getStart(),
(callLocation.getEnd() - callLocation.getStart()));
}
} catch (JavaModelException e) {
JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),
IJavaStatusConstants.INTERNAL_ERROR,
CallHierarchyMessages.getString(
"CallHierarchyUI.open_in_editor.error.message"), e)); //$NON-NLS-1$
ErrorDialog.openError(shell, title,
CallHierarchyMessages.getString(
"CallHierarchyUI.open_in_editor.error.messageProblems"), //$NON-NLS-1$
e.getStatus());
} catch (PartInitException x) {
String name = callLocation.getCalledMember().getElementName();
MessageDialog.openError(shell,
CallHierarchyMessages.getString(
"CallHierarchyUI.open_in_editor.error.messageProblems"), //$NON-NLS-1$
CallHierarchyMessages.getFormattedString(
"CallHierarchyUI.open_in_editor.error.messageArgs", //$NON-NLS-1$
new String[] { name, x.getMessage() }));
}
}
/**
* @param elem
* @return
*/
public static IEditorPart isOpenInEditor(Object elem) {
IJavaElement javaElement= null;
if (elem instanceof MethodWrapper) {
javaElement= ((MethodWrapper) elem).getMember();
} else if (elem instanceof CallLocation) {
javaElement= ((CallLocation) elem).getCalledMember();
}
if (javaElement != null) {
return EditorUtility.isOpenInEditor(javaElement);
}
return null;
}
/**
* Converts the input to a possible input candidates
*/
public static IJavaElement[] getCandidates(Object input) {
if (!(input instanceof IJavaElement)) {
return null;
}
IJavaElement elem= (IJavaElement) input;
switch (elem.getElementType()) {
case IJavaElement.METHOD:
return new IJavaElement[] { elem };
default:
}
return null;
}
public static CallHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) {
Assert.isTrue(candidates != null && candidates.length != 0);
IJavaElement input= null;
if (candidates.length > 1) {
String title= CallHierarchyMessages.getString("CallHierarchyUI.selectionDialog.title"); //$NON-NLS-1$
String message= CallHierarchyMessages.getString("CallHierarchyUI.selectionDialog.message"); //$NON-NLS-1$
input= OpenActionUtil.selectJavaElement(candidates, window.getShell(), title, message);
} else {
input= candidates[0];
}
if (input == null)
return null;
return openInViewPart(window, input);
}
private static void openEditor(Object input, boolean activate) throws PartInitException, JavaModelException {
IEditorPart part= EditorUtility.openInEditor(input, activate);
if (input instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) input);
}
private static CallHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) {
IWorkbenchPage page= window.getActivePage();
try {
CallHierarchyViewPart result= (CallHierarchyViewPart)page.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY);
result.setMethod((IMethod)input);
openEditor(input, false);
return result;
} catch (CoreException e) {
ExceptionHandler.handle(e, window.getShell(),
CallHierarchyMessages.getString("CallHierarchyUI.error.open_view"), e.getMessage()); //$NON-NLS-1$
}
return null;
}
}
|
37,445 |
Bug 37445 call hierarchy: Open Call Hierarchy beeps instead of showing info about the current method
|
Reporting against I20030506 build. As of I20030422, the "Open Call Hierarchy" action worked for the method in which the cursor was located. In the new build, it emits a confusing beep instead of opening the call hierarchy for the current method. It works as expected if you highlight the method's name, but the other way of invoking it was more convenient. If the new behavior is intended, at the very least some hint should be provided that a method selection is required, not just a beep. I tracked down the problem to OpenCallHierarchyAction.java:113 where CallHierarchyUI.getCandidates is called and returns null instead of the "current" IMethod.
|
resolved fixed
|
3a24d35
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T09:38:20Z | 2003-05-09T17:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/OpenCallHierarchyAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
/**
* This action opens a call hierarchy on the selected method.
* <p>
* The action is applicable to selections containing elements of type
* <code>IMethod</code>.
*/
public class OpenCallHierarchyAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/**
* Creates a new <code>OpenCallHierarchyAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public OpenCallHierarchyAction(IWorkbenchSite site) {
super(site);
setText(CallHierarchyMessages.getString("OpenCallHierarchyAction.label")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("OpenCallHierarchyAction.tooltip")); //$NON-NLS-1$
setDescription(CallHierarchyMessages.getString("OpenCallHierarchyAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_OPEN_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OpenCallHierarchyAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.canOperateOn(fEditor));
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(isEnabled(selection));
}
private boolean isEnabled(IStructuredSelection selection) {
if (selection.size() != 1)
return false;
Object input= selection.getFirstElement();
if (!(input instanceof IJavaElement))
return false;
switch (((IJavaElement)input).getElementType()) {
case IJavaElement.METHOD:
return true;
default:
return false;
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(ITextSelection selection) {
IJavaElement input= SelectionConverter.getInput(fEditor);
if (!ActionUtil.isProcessable(getShell(), input))
return;
IJavaElement[] elements= SelectionConverter.codeResolveOrInputHandled(fEditor, getShell(), getDialogTitle());
if (elements == null)
return;
List candidates= new ArrayList(elements.length);
for (int i= 0; i < elements.length; i++) {
IJavaElement[] resolvedElements= CallHierarchyUI.getCandidates(elements[i]);
if (resolvedElements != null)
candidates.addAll(Arrays.asList(resolvedElements));
}
run((IJavaElement[])candidates.toArray(new IJavaElement[candidates.size()]));
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
if (selection.size() != 1)
return;
Object input= selection.getFirstElement();
if (!(input instanceof IJavaElement)) {
IStatus status= createStatus(CallHierarchyMessages.getString("OpenCallHierarchyAction.messages.no_java_element")); //$NON-NLS-1$
ErrorDialog.openError(getShell(), getDialogTitle(), CallHierarchyMessages.getString("OpenCallHierarchyAction.messages.title"), status); //$NON-NLS-1$
return;
}
IJavaElement element= (IJavaElement) input;
if (!ActionUtil.isProcessable(getShell(), element))
return;
List result= new ArrayList(1);
IStatus status= compileCandidates(result, element);
if (status.isOK()) {
run((IJavaElement[]) result.toArray(new IJavaElement[result.size()]));
} else {
ErrorDialog.openError(getShell(), getDialogTitle(), CallHierarchyMessages.getString("OpenCallHierarchyAction.messages.title"), status); //$NON-NLS-1$
}
}
private void run(IJavaElement[] elements) {
if (elements.length == 0) {
getShell().getDisplay().beep();
return;
}
CallHierarchyUI.open(elements, getSite().getWorkbenchWindow());
}
private static String getDialogTitle() {
return CallHierarchyMessages.getString("OpenCallHierarchyAction.dialog.title"); //$NON-NLS-1$
}
private static IStatus compileCandidates(List result, IJavaElement elem) {
IStatus ok= new Status(IStatus.OK, JavaPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$
switch (elem.getElementType()) {
case IJavaElement.METHOD:
result.add(elem);
return ok;
}
return createStatus(CallHierarchyMessages.getString("OpenCallHierarchyAction.messages.no_valid_java_element")); //$NON-NLS-1$
}
private static IStatus createStatus(String message) {
return new Status(IStatus.INFO, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
}
}
|
37,499 |
Bug 37499 JUnit: Error on startup
|
I20030507.from20030512_1126 On startup of an existing workspace (containing a JUnit view as fast view), the Junit view fails to create java.lang.NullPointerException at org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart.restoreLayoutState(TestRunnerViewPart.java:274) at org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart.createPartControl(TestRunnerViewPart.java:842) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:141) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:889) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.PartPane.createChildControl(PartPane.java:137) at org.eclipse.ui.internal.ViewPane.createChildControl(ViewPane.java:211) at org.eclipse.ui.internal.ViewFactory$2.run(ViewFactory.java:167) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:889) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.ui.internal.ViewFactory.busyRestoreView(ViewFactory.java:98) at org.eclipse.ui.internal.ViewFactory$1.run(ViewFactory.java:82) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.ui.internal.ViewFactory.restoreView(ViewFactory.java:78) at org.eclipse.ui.internal.ViewFactory$ViewReference.getPart(ViewFactory.java:332) at org.eclipse.ui.internal.ViewFactory$ViewReference.getView(ViewFactory.java:311) at org.eclipse.ui.internal.WorkbenchPage.findView(WorkbenchPage.java:1166) at org.eclipse.jdt.internal.junit.ui.JUnitPlugin.findTestRunnerViewPartInActivePage(JUnitPlugin.java:224) at org.eclipse.jdt.internal.junit.ui.JUnitPlugin.connectTestRunner(JUnitPlugin.java:191) at org.eclipse.jdt.internal.junit.ui.JUnitPlugin$1.run(JUnitPlugin.java:254) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:98) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1915) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1649) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block(ModalContext.java:136) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:261) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:357) at org.eclipse.debug.ui.DebugUITools.launch(DebugUITools.java:494) at org.eclipse.debug.ui.actions.LaunchAction.run(LaunchAction.java:66) at org.eclipse.debug.ui.actions.LaunchAction.runWithEvent(LaunchAction.java:81) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:526) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:480) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:452) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:81) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1938) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1645) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1402) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1385) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583) !ENTRY org.eclipse.ui 4 4 Mai 12, 2003 16:56:05.618 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Mai 12, 2003 16:56:05.628 !MESSAGE Failed to execute runnable (java.lang.ClassCastException) !STACK 0 org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.ClassCastException) at org.eclipse.swt.SWT.error(SWT.java:2345) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:101) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1915) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1649) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block(ModalContext.java:136) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:261) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:357) at org.eclipse.debug.ui.DebugUITools.launch(DebugUITools.java:494) at org.eclipse.debug.ui.actions.LaunchAction.run(LaunchAction.java:66) at org.eclipse.debug.ui.actions.LaunchAction.runWithEvent(LaunchAction.java:81) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:526) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:480) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:452) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:81) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1938) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1645) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1402) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1385) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583) !ENTRY org.eclipse.ui 4 4 Mai 12, 2003 16:56:05.638 !MESSAGE *** Stack trace of contained exception *** !ENTRY org.eclipse.ui 4 0 Mai 12, 2003 16:56:05.638 !MESSAGE java.lang.ClassCastException !STACK 0 java.lang.ClassCastException at org.eclipse.jdt.internal.junit.ui.JUnitPlugin.findTestRunnerViewPartInActivePage(JUnitPlugin.java:224) at org.eclipse.jdt.internal.junit.ui.JUnitPlugin.connectTestRunner(JUnitPlugin.java:191) at org.eclipse.jdt.internal.junit.ui.JUnitPlugin$1.run(JUnitPlugin.java:254) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:98) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1915) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1649) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block(ModalContext.java:136) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:261) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:357) at org.eclipse.debug.ui.DebugUITools.launch(DebugUITools.java:494) at org.eclipse.debug.ui.actions.LaunchAction.run(LaunchAction.java:66) at org.eclipse.debug.ui.actions.LaunchAction.runWithEvent(LaunchAction.java:81) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:526) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:480) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:452) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:81) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1938) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1645) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1402) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1385) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
7df5b86
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T15:29:42Z | 2003-05-12T14:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Julien Ruaux: [email protected] see bug 25324 Ability to know when tests are finished [junit]
* Vincent Massol: [email protected] 25324 Ability to know when tests are finished [junit]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener2, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrors;
/**
* Number of failures during this test run
*/
protected int fFailures;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Whether the output scrolls and reveals tests as they are executed.
*/
private boolean fAutoScroll = true;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos= new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private TestRunInfo fFirstFailure;
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
private Clipboard fClipboard;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch;
/**
* Actions
*/
private Action fRerunLastTestAction;
private ScrollLockAction fScrollLockAction;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
// Persistance tags.
static final String TAG_PAGE= "page"; //$NON-NLS-1$
static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
static final String TAG_TRACEFILTER= "tracefilter"; //$NON-NLS-1$
private IMemento fMemento;
Image fOriginalViewImage;
IElementChangedListener fDirtyListener;
private CTabFolder fTabFolder;
private SashForm fSashForm;
private class StopAction extends Action{
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action{
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit unit= (ICompilationUnit)delta.getElement();
// If we change a working copy we do nothing
if (unit.isWorkingCopy()) {
// Don't examine children of a working copy but keep processing siblings.
return true;
} else {
codeHasChanged();
return false;
}
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
private void restoreLayoutState(IMemento memento) {
Integer page= memento.getInteger(TAG_PAGE);
fTabFolder.setSelection(page.intValue());
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null)
fSashForm.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
public void setAutoScroll(boolean scroll) {
fAutoScroll = scroll;
}
public boolean isAutoScroll() {
return fAutoScroll;
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void reset(){
reset(0);
setViewPartTitle(null);
clearStatus();
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrors), String.valueOf(fFailures)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFirstFailure != null && fAutoScroll) {
fActiveRunView.setSelectedTest(fFirstFailure.getTestId());
handleTestSelected(fFirstFailure.getTestId());
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrors+fFailures > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testId, String testName) {
postStartTest(testId, testName);
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
postInfo(JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", testName)); //$NON-NLS-1$
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null)
fTestInfos.put(testId, new TestRunInfo(testId, testName));
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testId, String testName){
postEndTest(testId, testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace){
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testName, testInfo);
}
testInfo.setTrace(trace);
testInfo.setStatus(status);
if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
else
fFailures++;
if (fFirstFailure == null)
fFirstFailure= testInfo;
// show the view on the first error only
if (fShowOnErrorOnly && (fErrors + fFailures == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String testId, String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
TestRunInfo info= getTestInfo(testId);
updateTest(info, status);
if (info.getTrace() == null || !info.getTrace().equals(trace)) {
info.setTrace(trace);
showFailure(info.getTrace());
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.getStatus())
return;
if (info.getStatus() == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailures++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
} else if (info.getStatus() == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrors--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrors--;
fFailures++;
}
} else if (info.getStatus() == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailures--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailures--;
fErrors++;
}
}
info.setStatus(status);
final TestRunInfo finalInfo= info;
postAsyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
Vector listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.copyInto(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
if (fClipboard != null)
fClipboard.dispose();
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void postAsyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
}
}
});
}
private void postEndTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testId);
}
}
});
}
private void postStartTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.startTest(testId);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailures+fErrors);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrors, fFailures);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrors);
fCounterPanel.setFailureValue(fFailures);
fCounterPanel.setRunValue(fExecutedTests);
fProgressBar.refresh(fErrors+fFailures> 0);
}
protected void postShowTestResultsView() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, fClipboard, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, fClipboard, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getSelectedTestId());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
fSashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(fSashForm, SWT.NONE);
fTabFolder= createTestRunViews(top);
fTabFolder.setLayoutData(new TabFolderLayout());
top.setContent(fTabFolder);
ViewForm bottom= new ViewForm(fSashForm, SWT.NONE);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, fClipboard, this);
bottom.setContent(fFailureView.getComposite());
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
// fill the failure trace viewer toolbar
ToolBarManager failureToolBarmanager= new ToolBarManager(failureToolBar);
failureToolBarmanager.add(new EnableStackFilterAction(fFailureView));
failureToolBarmanager.update(true);
fSashForm.setWeights(new int[]{50, 50});
return fSashForm;
}
private void reset(final int testCount) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailures= 0;
fErrors= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFirstFailure= null;
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
fClipboard= new Clipboard(parent.getDisplay());
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
parent.setLayout(gridLayout);
configureToolBar();
Composite counterPanel= createProgressCountPanel(parent);
counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
getViewSite().getActionBars().setGlobalActionHandler(
IWorkbenchActionConstants.COPY,
new CopyTraceAction(fFailureView, fClipboard));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
if (fMemento != null)
restoreLayoutState(fMemento);
fMemento= null;
}
public void saveState(IMemento memento) {
if (fSashForm == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
int activePage= fTabFolder.getSelectionIndex();
memento.putInteger(TAG_PAGE, activePage);
int weigths[]= fSashForm.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
}
private void configureToolBar() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fRerunLastTestAction= new RerunLastAction();
fScrollLockAction= new ScrollLockAction(this);
toolBar.add(new StopAction());
toolBar.add(new Separator());
toolBar.add(fRerunLastTestAction);
toolBar.add(fScrollLockAction);
fScrollLockAction.setChecked(!fAutoScroll);
actionBars.updateActionBars();
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testId) {
if (testId == null)
return null;
return (TestRunInfo) fTestInfos.get(testId);
}
public void handleTestSelected(String testId) {
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
showFailure(""); //$NON-NLS-1$
} else {
showFailure(testInfo.getTrace());
}
}
private void showFailure(final String failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
public void rerunTest(String testId, String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(testId, className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
}
|
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.tests.core;
import java.io.File;
import java.util.zip.ZipFile;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.testplugin.JavaTestPlugin;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
public class ImportOrganizeTest extends CoreTests {
private static final Class THIS= ImportOrganizeTest.class;
private IJavaProject fJProject1;
public ImportOrganizeTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new ImportOrganizeTest("testBaseGroups1"));
return suite;
}
}
protected void setUp() throws Exception {
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
private IChooseImportQuery createQuery(final String name, final String[] choices, final int[] nEntries) {
return new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
assertTrue(name + "-query-nchoices1", choices.length == openChoices.length);
assertTrue(name + "-query-nchoices2", nEntries.length == openChoices.length);
if (nEntries != null) {
for (int i= 0; i < nEntries.length; i++) {
assertTrue(name + "-query-cnt" + i, openChoices[i].length == nEntries[i]);
}
}
TypeInfo[] res= new TypeInfo[openChoices.length];
for (int i= 0; i < openChoices.length; i++) {
TypeInfo[] selection= openChoices[i];
assertNotNull(name + "-query-setset" + i, selection);
assertTrue(name + "-query-setlen" + i, selection.length > 0);
TypeInfo found= null;
for (int k= 0; k < selection.length; k++) {
if (selection[k].getFullyQualifiedName().equals(choices[i])) {
found= selection[k];
}
}
assertNotNull(name + "-query-notfound" + i, found);
res[i]= found;
}
return res;
}
};
}
private void assertImports(ICompilationUnit cu, String[] imports) throws Exception {
IImportDeclaration[] desc= cu.getImports();
assertTrue(cu.getElementName() + "-count", desc.length == imports.length);
for (int i= 0; i < imports.length; i++) {
assertEquals(cu.getElementName() + "-cmpentries" + i, desc[i].getElementName(), imports[i]);
}
}
public void test1() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/BaseTestRunner.java"));
assertNotNull("BaseTestRunner.java", cu);
IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
IPackageFragment pack= root.createPackageFragment("mytest", true, null);
ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.BufferedReader",
"java.io.File",
"java.io.FileInputStream",
"java.io.IOException",
"java.io.InputStream",
"java.io.PrintWriter",
"java.io.StringReader",
"java.io.StringWriter",
"java.lang.reflect.InvocationTargetException",
"java.lang.reflect.Method",
"java.text.NumberFormat",
"java.util.Properties",
"junit.framework.Test",
"junit.framework.TestListener",
"junit.framework.TestSuite"
});
}
public void test1WithOrder() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/BaseTestRunner.java"));
assertNotNull("BaseTestRunner.java", cu);
IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
IPackageFragment pack= root.createPackageFragment("mytest", true, null);
ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
String[] order= new String[] { "junit", "java.text", "java.io", "java" };
IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"junit.framework.Test",
"junit.framework.TestListener",
"junit.framework.TestSuite",
"java.text.NumberFormat",
"java.io.BufferedReader",
"java.io.File",
"java.io.FileInputStream",
"java.io.IOException",
"java.io.InputStream",
"java.io.PrintWriter",
"java.io.StringReader",
"java.io.StringWriter",
"java.lang.reflect.InvocationTargetException",
"java.lang.reflect.Method",
"java.util.Properties"
});
}
public void test2() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/LoadingTestCollector.java"));
assertNotNull("LoadingTestCollector.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("LoadingTestCollector", new String[] { }, new int[] { });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.lang.reflect.Constructor",
"java.lang.reflect.Method",
"java.lang.reflect.Modifier",
"junit.framework.Test"
});
}
public void test3() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/TestCaseClassLoader.java"));
assertNotNull("TestCaseClassLoader.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("TestCaseClassLoader", new String[] { }, new int[] { });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 3, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.*",
"java.net.URL",
"java.util.*",
"java.util.zip.ZipEntry",
"java.util.zip.ZipFile",
});
}
public void test4() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/textui/TestRunner.java"));
assertNotNull("TestRunner.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("TestRunner", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.PrintStream",
"java.util.Enumeration",
"junit.framework.AssertionFailedError",
"junit.framework.Test",
"junit.framework.TestFailure",
"junit.framework.TestResult",
"junit.framework.TestSuite",
"junit.runner.BaseTestRunner",
"junit.runner.StandardTestSuiteLoader",
"junit.runner.TestSuiteLoader",
"junit.runner.Version"
});
}
public void testVariousTypeReferences() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack= sourceFolder.createPackageFragment("test", false, null);
for (int ch= 'A'; ch < 'M'; ch++) {
String name= String.valueOf((char) ch);
ICompilationUnit cu= pack.getCompilationUnit(name + ".java");
String content= "public class " + name + " {}";
cu.createType(content, null, false, null);
}
for (int ch= 'A'; ch < 'M'; ch++) {
String name= "I" + String.valueOf((char) ch);
ICompilationUnit cu= pack.getCompilationUnit(name + ".java");
String content= "public interface " + name + " {}";
cu.createType(content, null, false, null);
}
StringBuffer buf= new StringBuffer();
buf.append("public class ImportTest extends A implements IA, IB {\n");
buf.append(" private B fB;\n");
buf.append(" private Object fObj= new C();\n");
buf.append(" public IB foo(IC c, ID d) throws IOException {\n");
buf.append(" Object local= (D) fObj;\n");
buf.append(" if (local instanceof E) {};\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack= sourceFolder.createPackageFragment("other", false, null);
ICompilationUnit cu= pack.getCompilationUnit("ImportTest.java");
cu.createType(buf.toString(), null, false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("ImportTest", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.IOException",
"test.A",
"test.B",
"test.C",
"test.D",
"test.E",
"test.IA",
"test.IB",
"test.IC",
"test.ID",
});
}
public void testInnerClassVisibility() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" protected static class C1 {\n");
buf.append(" public static class C2 {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IPackageFragment pack2= sourceFolder.createPackageFragment("test2", false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import test2.A.A1;\n");
buf.append("import test2.A.A1.A2;\n");
buf.append("import test2.A.A1.A2.A3;\n");
buf.append("import test2.A.B1;\n");
buf.append("import test2.A.B1.B2;\n");
buf.append("import test1.C;\n");
buf.append("import test1.C.C1.C2;\n");
buf.append("public class A {\n");
buf.append(" public static class A1 {\n");
buf.append(" public static class A2 {\n");
buf.append(" public static class A3 {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public static class B1 {\n");
buf.append(" public static class B2 {\n");
buf.append(" }\n");
buf.append(" public static class B3 {\n");
buf.append(" public static class B4 extends C {\n");
buf.append(" B4 b4;\n");
buf.append(" B3 b3;\n");
buf.append(" B2 b2;\n");
buf.append(" B1 b1;\n");
buf.append(" A1 a1;\n");
buf.append(" A2 a2;\n");
buf.append(" A3 a3;\n");
buf.append(" C1 c1;\n");
buf.append(" C2 c2;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu2= pack2.createCompilationUnit("A.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("A", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu2, order, 99, false, true, true, query);
op.run(null);
assertImports(cu2, new String[] {
"test1.C",
"test1.C.C1.C2",
"test2.A.A1.A2",
"test2.A.A1.A2.A3"
});
}
public void testClearImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class C {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testNewImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testReplaceImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testClearImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("public class C {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("public class C {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testNewImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testReplaceImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testCommentAfterImport() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\r\n");
buf.append("\r\n");
buf.append("import x;\r\n");
buf.append("import java.util.Vector; // comment\r\n");
buf.append("\r\n");
buf.append("public class C {\r\n");
buf.append(" Vector v;\r\n");
buf.append("}\r\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\r\n");
buf.append("\r\n");
buf.append("import java.util.Vector;\r\n");
buf.append("\r\n");
buf.append("public class C {\r\n");
buf.append(" Vector v;\r\n");
buf.append("}\r\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStar() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStarWithExplicit() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List2 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List2.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("import pack.List2;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.*;\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStarWithExplicit2() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 1, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStarWithExplicit3() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class Set {\n");
buf.append("}\n");
pack2.createCompilationUnit("Set.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 1, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStarWithExplicit4() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
IPackageFragment pack3= sourceFolder.createPackageFragment("pack3", false, null);
buf= new StringBuffer();
buf.append("package pack3;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack3.createCompilationUnit("List.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 1, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStarWithExplicit5() throws Exception {
// unrelated project, to fill the all types cache
IJavaProject project2 = JavaProjectHelper.createJavaProject("TestProject2", "bin");
try {
assertTrue("rt not found", JavaProjectHelper.addRTJar(project2) != null);
IPackageFragmentRoot sourceFolder2= JavaProjectHelper.addSourceContainer(project2, "src");
IPackageFragment pack22= sourceFolder2.createPackageFragment("packx", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class Vector {\n");
buf.append("}\n");
pack22.createCompilationUnit("List.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class Set {\n");
buf.append("}\n");
pack22.createCompilationUnit("Set.java", buf.toString(), false, null);
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 1, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
} finally {
JavaProjectHelper.delete(project2);
}
}
public void testImportFromDefault() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("", false, null);
StringBuffer buf= new StringBuffer();
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List1.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import List1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportFromDefaultWithStar() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("", false, null);
StringBuffer buf= new StringBuffer();
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List1.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("public class List2 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List2.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import List1;\n");
buf.append("import List2;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportOfMemberFromLocal() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" public void foo() {\n");
buf.append(" class Local {\n");
buf.append(" class LocalMember {\n");
buf.append(" }\n");
buf.append(" LocalMember x;\n");
buf.append(" Vector v;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" public void foo() {\n");
buf.append(" class Local {\n");
buf.append(" class LocalMember {\n");
buf.append(" }\n");
buf.append(" LocalMember x;\n");
buf.append(" Vector v;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testGroups1() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack0", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack0;\n");
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List1.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" File f;\n");
buf.append(" IOException f1;\n");
buf.append(" RandomAccessFile f2;\n");
buf.append(" ArrayList f3;\n");
buf.append(" List1 f4;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java.io", "java.util" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.io.File;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.io.RandomAccessFile;\n");
buf.append("\n");
buf.append("import java.util.ArrayList;\n");
buf.append("\n");
buf.append("import pack0.List1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" File f;\n");
buf.append(" IOException f1;\n");
buf.append(" RandomAccessFile f2;\n");
buf.append(" ArrayList f3;\n");
buf.append(" List1 f4;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testBaseGroups1() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack0", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack0;\n");
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List1.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" File f;\n");
buf.append(" IOException f1;\n");
buf.append(" RandomAccessFile f2;\n");
buf.append(" ArrayList f3;\n");
buf.append(" List1 f4;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "java.io" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.ArrayList;\n");
buf.append("\n");
buf.append("import java.io.File;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.io.RandomAccessFile;\n");
buf.append("\n");
buf.append("import pack0.List1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" File f;\n");
buf.append(" IOException f1;\n");
buf.append(" RandomAccessFile f2;\n");
buf.append(" ArrayList f3;\n");
buf.append(" List1 f4;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testVisibility_bug26746() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack0", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack0;\n");
buf.append("public interface MyInterface {\n");
buf.append(" public interface MyInnerInterface {\n");
buf.append(" }\n");
buf.append("}\n");
pack2.createCompilationUnit("MyInterface.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack0;\n");
buf.append("\n");
buf.append("import pack0.MyInterface.MyInnerInterface;\n");
buf.append("public class MyClass implements MyInterface {\n");
buf.append(" public MyInnerInterface myMethod() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack2.createCompilationUnit("MyClass.java", buf.toString(), false, null);
String[] order= new String[] {};
IChooseImportQuery query= createQuery("MyClass", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack0;\n");
buf.append("\n");
buf.append("public class MyClass implements MyInterface {\n");
buf.append(" public MyInnerInterface myMethod() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void test5() throws Exception {
String[] types= new String[] {
"org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader",
"org.eclipse.core.resources.IContainer",
"org.eclipse.core.runtime.IPath",
"org.eclipse.core.runtime.CoreException",
"org.eclipse.core.resources.IResource",
"org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer"
};
String[] order= new String[] { "org.eclipse.jdt", "org.eclipse" };
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
for (int i= 0; i < types.length; i++) {
String pack= Signature.getQualifier(types[i]);
String name= Signature.getSimpleName(types[i]);
IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null);
StringBuffer buf= new StringBuffer();
buf.append("package "); buf.append(pack); buf.append(";\n");
buf.append("public class "); buf.append(name); buf.append(" {\n");
buf.append("}\n");
pack2.createCompilationUnit(name + ".java", buf.toString(), false, null);
}
StringBuffer body= new StringBuffer();
body.append("public class C {\n");
for (int i= 0; i < types.length; i++) {
String name= Signature.getSimpleName(types[i]);
body.append(name); body.append(" a"); body.append(i); body.append(";\n");
}
body.append("}\n");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append(body.toString());
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;\n");
buf.append("import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;\n");
buf.append("\n");
buf.append("import org.eclipse.core.resources.IContainer;\n");
buf.append("import org.eclipse.core.resources.IResource;\n");
buf.append("import org.eclipse.core.runtime.CoreException;\n");
buf.append("import org.eclipse.core.runtime.IPath;\n");
buf.append("\n");
buf.append(body.toString());
assertEqualString(cu.getSource(), buf.toString());
}
public void test_bug25773() throws Exception {
String[] types= new String[] {
"java.util.Vector",
"java.util.Map",
"java.util.Set",
"org.eclipse.gef.X1",
"org.eclipse.gef.X2",
"org.eclipse.gef.X3",
"org.eclipse.core.runtime.IAdaptable",
"org.eclipse.draw2d.IFigure",
"org.eclipse.draw2d.LayoutManager",
"org.eclipse.draw2d.geometry.Point",
"org.eclipse.draw2d.geometry.Rectangle",
"org.eclipse.swt.accessibility.ACC",
"org.eclipse.swt.accessibility.AccessibleControlEvent"
};
String[] order= new String[] { "java", "org.eclipse", "org.eclipse.gef", "org.eclipse.draw2d", "org.eclipse.gef.examples" };
int threshold= 3;
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
for (int i= 0; i < types.length; i++) {
String pack= Signature.getQualifier(types[i]);
if (!pack.startsWith("java.")) {
String name= Signature.getSimpleName(types[i]);
IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null);
StringBuffer buf= new StringBuffer();
buf.append("package "); buf.append(pack); buf.append(";\n");
buf.append("public class "); buf.append(name); buf.append(" {\n");
buf.append("}\n");
pack2.createCompilationUnit(name + ".java", buf.toString(), false, null);
}
}
StringBuffer body= new StringBuffer();
body.append("public class C {\n");
for (int i= 0; i < types.length; i++) {
String name= Signature.getSimpleName(types[i]);
body.append(name); body.append(" a"); body.append(i); body.append(";\n");
}
body.append("}\n");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append(body.toString());
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, threshold, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import org.eclipse.core.runtime.IAdaptable;\n");
buf.append("import org.eclipse.swt.accessibility.ACC;\n");
buf.append("import org.eclipse.swt.accessibility.AccessibleControlEvent;\n");
buf.append("\n");
buf.append("import org.eclipse.gef.*;\n");
buf.append("\n");
buf.append("import org.eclipse.draw2d.IFigure;\n");
buf.append("import org.eclipse.draw2d.LayoutManager;\n");
buf.append("import org.eclipse.draw2d.geometry.Point;\n");
buf.append("import org.eclipse.draw2d.geometry.Rectangle;\n");
buf.append("\n");
buf.append(body.toString());
assertEqualString(cu.getSource(), buf.toString());
}
public void test_bug25113() throws Exception {
String[] types= new String[] {
"com.mycompany.Class1",
"com.foreigncompany.Class2",
"com.foreigncompany.Class3",
"com.mycompany.Class4",
"com.misc.Class5"
};
String[] order= new String[] { "com", "com.foreigncompany", "com.mycompany" };
int threshold= 99;
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
for (int i= 0; i < types.length; i++) {
String pack= Signature.getQualifier(types[i]);
if (!pack.startsWith("java.")) {
String name= Signature.getSimpleName(types[i]);
IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null);
StringBuffer buf= new StringBuffer();
buf.append("package "); buf.append(pack); buf.append(";\n");
buf.append("public class "); buf.append(name); buf.append(" {\n");
buf.append("}\n");
pack2.createCompilationUnit(name + ".java", buf.toString(), false, null);
}
}
StringBuffer body= new StringBuffer();
body.append("public class C {\n");
for (int i= 0; i < types.length; i++) {
String name= Signature.getSimpleName(types[i]);
body.append(name); body.append(" a"); body.append(i); body.append(";\n");
}
body.append("}\n");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append(body.toString());
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, threshold, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import com.misc.Class5;\n");
buf.append("\n");
buf.append("import com.foreigncompany.Class2;\n");
buf.append("import com.foreigncompany.Class3;\n");
buf.append("\n");
buf.append("import com.mycompany.Class1;\n");
buf.append("import com.mycompany.Class4;\n");
buf.append("\n");
buf.append(body.toString());
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportStructureOnNonExistingCU() throws Exception {
IJavaProject project1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(project1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
ICompilationUnit unit= pack1.getCompilationUnit("A.java");
ICompilationUnit wc= (ICompilationUnit) unit.getWorkingCopy(null, JavaUI.getBufferFactory(), null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public Object foo() {\n");
buf.append(" }\n");
buf.append("}\n");
wc.getBuffer().setContents(buf.toString());
String[] order= new String[] { "com", "com.foreigncompany", "com.mycompany" };
int threshold= 99;
ImportsStructure importsStructure= new ImportsStructure(wc, order, threshold, true);
importsStructure.addImport("java.util.HashMap");
importsStructure.create(false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.HashMap;\n");
buf.append("\n");
buf.append("public class A {\n");
buf.append(" public Object foo() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualStringIgnoreDelim(wc.getSource(), buf.toString());
}
}
|
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ScopeAnalyzerTest.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.tests.core;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
/**
*/
public class ScopeAnalyzerTest extends CoreTests {
private static final Class THIS= ScopeAnalyzerTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public ScopeAnalyzerTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new ScopeAnalyzerTest("testDeclarationsAfter"));
return suite;
}
}
protected void setUp() throws Exception {
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK, JavaCore.IGNORE);
options.put(JavaCore.COMPILER_PB_UNREACHABLE_CODE, JavaCore.IGNORE);
JavaCore.setOptions(options);
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testVariableDeclarations1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("public class E {\n");
buf.append(" int[] fGlobal;\n");
buf.append(" public int goo(int param1, int param2) {\n");
buf.append(" int count= 0;\n");
buf.append(" fGlobal= new int[] { 1, 2, 3};\n");
buf.append(" for (int i= 0; i < fGlobal.length; i++) {\n");
buf.append(" int insideFor= 0;\n");
buf.append(" count= insideFor + fGlobal[i];\n");
buf.append(" return -1;\n");
buf.append(" }\n");
buf.append(" count++;\n");
buf.append(" int count2= 0;\n");
buf.append(" count+= count2;\n");
buf.append(" return count;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "count+= count2;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "param2", "count", "count2", "fGlobal" });
}
{
String str= "count++;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "param2", "count", "fGlobal" });
}
{
String str= "return -1;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "param2", "count", "i", "insideFor", "fGlobal" });
}
}
public void testVariableDeclarations2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public int goo(int param1) {\n");
buf.append(" int count= 9, count2= 0;\n");
buf.append(" try {\n");
buf.append(" for (int i= 0, j= 0; i < 9; i++) {\n");
buf.append(" System.out.println(i + j);\n");
buf.append(" j++;\n");
buf.append(" }\n");
buf.append(" return 8;\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" int k= 0;\n");
buf.append(" return k;\n");
buf.append(" } catch (Exception x) {\n");
buf.append(" return 9;\n");
buf.append(" };\n");
buf.append(" return count;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "j++;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "count", "count2", "i", "j"});
}
{
String str= "return 8;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "count", "count2"});
}
{
String str= "return k;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "count", "count2", "e", "k" });
}
{
String str= "return 9;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "count", "count2", "x" });
}
{
String str= "return count;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "count", "count2" });
}
}
public void testVariableDeclarations3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("public class E {\n");
buf.append(" private int fVar1, fVar2;\n");
buf.append(" public int goo(int param1) {\n");
buf.append(" Runnable run= new Runnable() {\n");
buf.append(" int fInner;\n");
buf.append(" public void run() {\n");
buf.append(" int k= 0;\n");
buf.append(" fVar1= k;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" int k= 0;\n");
buf.append(" return k;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "fVar1= k;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "k", "fInner", "param1", "run", "fVar1", "fVar2"});
}
{
String str= "return k;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "k", "param1", "run", "fVar1", "fVar2"});
}
}
public void testVariableDeclarations4() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("public class Rectangle {\n");
buf.append(" public int x;\n");
buf.append(" public int y;\n");
buf.append("}\n");
pack0.createCompilationUnit("Rectangle.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("import pack1.Rectangle;\n");
buf.append("public class E {\n");
buf.append(" private int fVar1, fVar2;\n");
buf.append(" public int goo(int param1) {\n");
buf.append(" int k= 0;\n");
buf.append(" Rectangle r= new Rectangle();\n");
buf.append(" return r.x;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "return r.x;";
int offset= buf.toString().indexOf(str) + "return r.".length();
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "x", "y"});
}
}
public void testVariableDeclarations5() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("public interface IConstants {\n");
buf.append(" public final int CONST= 1;\n");
buf.append("}\n");
pack0.createCompilationUnit("IConstants.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("public class E {\n");
buf.append(" private int fVar1, fVar2;\n");
buf.append(" private class A {\n");
buf.append(" int fCount;\n");
buf.append(" public int foo(int param1) {\n");
buf.append(" return 1;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public int goo(int param0) {\n");
buf.append(" int k= 0;\n");
buf.append(" class B extends A implements pack1.IConstants {\n");
buf.append(" int fCount2;\n");
buf.append(" public int foo(int param1) {\n");
buf.append(" return 2;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" return 3;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "return 1;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "fCount", "fVar1", "fVar2"});
}
{
String str= "return 2;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "param1", "fCount2", "fCount", "k", "param0", "fVar1", "fVar2", "CONST"});
}
}
public void testDeclarationsAfter() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("public class E {\n");
buf.append(" public int goo(final int param0) {\n");
buf.append(" int k= 0;\n");
buf.append(" try {\n");
buf.append(" for (int i= 0; i < 10; i++) {\n");
buf.append(" k += i;\n");
buf.append(" }\n");
buf.append(" } catch (Exception x) {\n");
buf.append(" return 9;\n");
buf.append(" };\n");
buf.append(" Runnable run= new Runnable() {\n");
buf.append(" int fInner;\n");
buf.append(" public void run() {\n");
buf.append(" int x1= 0;\n");
buf.append(" x1 += param0;\n");
buf.append(" {\n");
buf.append(" for (int i= 0, j= 0; i < 10; i++) {\n");
buf.append(" x1 += i;\n");
buf.append(" int x2= 0;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" return 3;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "int k= 0;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsAfter(astRoot, offset, flags);
assertVariables(res, new String[] { "k", "i", "x", "run"});
}
{
String str= "return 9;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsAfter(astRoot, offset, flags);
assertVariables(res, new String[] { });
}
{
String str= "x1 += param0;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.VARIABLES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsAfter(astRoot, offset, flags);
assertVariables(res, new String[] { "i", "j", "x2" });
}
}
public void testTypeDeclarations1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("public class E {\n");
buf.append(" public static class A {\n");
buf.append(" public class A1 {\n");
buf.append(" public int foo() {\n");
buf.append(" return 1;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public class A2 {\n");
buf.append(" }\n");
buf.append(" public int foo() {\n");
buf.append(" return 2;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("class F {\n");
buf.append(" public int goo(int param0) {\n");
buf.append(" class C extends E.A {\n");
buf.append(" A1 b;\n");
buf.append(" public int foo() {\n");
buf.append(" return 3;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" return 4;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "return 1;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.TYPES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "A1", "A", "E", "A2", "F"});
}
{
String str= "return 2;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.TYPES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "A1", "A", "E", "A2", "F"});
}
{
String str= "return 3;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.TYPES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "C", "F", "A1", "A2", "E"});
}
{
String str= "return 4;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.TYPES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "C", "F", "E"});
}
}
public void testTypeDeclarations2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("public class E {\n");
buf.append(" public static class E1 extends G {\n");
buf.append(" public static class EE1 {\n");
buf.append(" }\n");
buf.append(" public static class EE2 {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public static class E2 {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("class F extends E.E1{\n");
buf.append(" F f1;\n");
buf.append("}\n");
buf.append("class G {\n");
buf.append(" public static class G1 {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "F f1;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.TYPES;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertVariables(res, new String[] { "F", "EE1", "EE2", "G1", "G", "E"});
}
}
public void testMethodDeclarations1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append(" public void goo() {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public String toString() {\n");
buf.append(" return String.valueOf(1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "return;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.METHODS;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertMethods(res, new String[] { "goo", "foo" }, true);
}
}
public void testMethodDeclarations2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1.ae", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1.ae;\n");
buf.append("public class E {\n");
buf.append(" int fVar1, fVar2;\n");
buf.append(" public int goo(int param1) {\n");
buf.append(" Runnable run= new Runnable() {\n");
buf.append(" int fInner;\n");
buf.append(" public void run() {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" int k= 0;\n");
buf.append(" return k;\n");
buf.append(" }\n");
buf.append(" private class A extends E {\n");
buf.append(" { // initializer\n");
buf.append(" fVar1= 9; \n");
buf.append(" }\n");
buf.append(" public int foo(int param1) {\n");
buf.append(" return 1;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit compilationUnit= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(compilationUnit, true);
assertNoProblems(astRoot);
{
String str= "return;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.METHODS;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertMethods(res, new String[] { "run", "goo"}, true);
}
{
String str= "return k;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.METHODS;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertMethods(res, new String[] { "goo"}, true);
}
{
String str= "return 1;";
int offset= buf.toString().indexOf(str);
int flags= ScopeAnalyzer.METHODS;
IBinding[] res= new ScopeAnalyzer().getDeclarationsInScope(astRoot, offset, flags);
assertMethods(res, new String[] { "foo", "goo"}, true);
}
}
private static final String[] OBJ_METHODS= new String[] { "getClass",
"hashCode", "equals", "clone", "toString", "notify", "notifyAll", "wait", "wait",
"wait", "finalize" };
private void assertMethods(IBinding[] res, String[] expectedNames, boolean addObjectMethods) {
String[] names= new String[res.length];
for (int i= 0; i < res.length; i++) {
names[i]= res[i].getName();
}
String[] expected= expectedNames;
if (addObjectMethods) {
expected= new String[expectedNames.length + OBJ_METHODS.length];
System.arraycopy(OBJ_METHODS, 0, expected, 0, OBJ_METHODS.length);
System.arraycopy(expectedNames, 0, expected, OBJ_METHODS.length, expectedNames.length);
}
assertEqualStringsIgnoreOrder(names, expected);
}
private void assertVariables(IBinding[] res, String[] expectedNames) {
String[] names= new String[res.length];
for (int i= 0; i < res.length; i++) {
names[i]= res[i].getName();
}
assertEqualStringsIgnoreOrder(names, expectedNames);
}
private void assertNoProblems(CompilationUnit astRoot) {
IProblem[] problems= astRoot.getProblems();
if (problems.length > 0) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < problems.length; i++) {
buf.append(problems[i].getMessage()).append('\n');
}
assertTrue(buf.toString(), false);
}
}
}
|
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedVariablesQuickFixTest.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.correction.NewCUCompletionUsingWizardProposal;
import org.eclipse.jdt.internal.ui.text.correction.NewVariableCompletionProposal;
public class UnresolvedVariablesQuickFixTest extends QuickFixTest {
private static final Class THIS= UnresolvedVariablesQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public UnresolvedVariablesQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new UnresolvedVariablesQuickFixTest("testVarInAnonymous"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_UNUSED_IMPORT, JavaCore.IGNORE);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
CodeTemplates.getCodeTemplate(CodeTemplates.NEWTYPE).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.TYPECOMMENT).setPattern("");
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testVarInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" iter= vec.iterator();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
boolean doField= true, doParam= true, doLocal= true;
for (int i= 0; i < proposals.size(); i++) {
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(i);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
if (proposal.getVariableKind() == NewVariableCompletionProposal.FIELD) {
assertTrue("2 field proposals", doField);
doField= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" private Iterator iter;\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" iter= vec.iterator();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.LOCAL) {
assertTrue("2 local proposals", doLocal);
doLocal= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" Iterator iter = vec.iterator();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.PARAM) {
assertTrue("2 param proposals", doParam);
doParam= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec, Iterator iter) {\n");
buf.append(" iter= vec.iterator();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else {
assertTrue("unknown type", false);
}
}
}
public void testVarInForInitializer() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (i= 0;;) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
boolean doField= true, doParam= true, doLocal= true;
for (int i= 0; i < proposals.size(); i++) {
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(i);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
if (proposal.getVariableKind() == NewVariableCompletionProposal.FIELD) {
assertTrue("2 field proposals", doField);
doField= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int i;\n");
buf.append("\n");
buf.append(" void foo() {\n");
buf.append(" for (i= 0;;) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.LOCAL) {
assertTrue("2 local proposals", doLocal);
doLocal= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i = 0;;) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.PARAM) {
assertTrue("2 param proposals", doParam);
doParam= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(int i) {\n");
buf.append(" for (i= 0;;) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else {
assertTrue("unknown type", false);
}
}
}
public void testVarInInitializer() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int i= k;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int k;\n");
buf.append("\n");
buf.append(" private int i= k;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testVarInOtherType() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" void foo(E e) {\n");
buf.append(" e.var2= 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int var1;\n");
buf.append("}\n");
pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
boolean doNew= true, doChange= true;
for (int i= 0; i < proposals.size(); i++) {
Object curr= proposals.get(i);
if (curr instanceof NewVariableCompletionProposal) {
assertTrue("2 new proposals", doNew);
doNew= false;
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) curr;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int var2;\n");
buf.append("\n");
buf.append(" private int var1;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (curr instanceof CUCorrectionProposal) {
assertTrue("2 replace proposals", doChange);
doChange= false;
CUCorrectionProposal proposal= (CUCorrectionProposal) curr;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" void foo(E e) {\n");
buf.append(" e.var1= 2;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
}
public void testVarInAnonymous() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" fCount= 7;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 4);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" private int fCount;\n");
buf.append("\n");
buf.append(" public void run() {\n");
buf.append(" fCount= 7;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" protected int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" fCount= 7;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" int fCount = 7;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(3);
String preview4= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run(int fCount) {\n");
buf.append(" fCount= 7;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected4= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3, preview4 }, new String[] { expected1, expected2, expected3, expected4 });
}
public void testLongVarRef() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" void foo(E e) {\n");
buf.append(" e.var.x= 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public F var;\n");
buf.append("}\n");
pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" private int x;\n");
buf.append("\n");
buf.append(" void foo(E e) {\n");
buf.append(" e.var.x= 2;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testVarAndTypeRef() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" void foo() {\n");
buf.append(" char ch= Fixe.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("F.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 6);
assertCorrectLabels(proposals);
boolean doField= true, doParam= true, doLocal= true, doInterface= true, doClass= true, doChange= true;
for (int i= 0; i < proposals.size(); i++) {
Object curr= proposals.get(i);
if (curr instanceof NewVariableCompletionProposal) {
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(i);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
if (proposal.getVariableKind() == NewVariableCompletionProposal.FIELD) {
assertTrue("2 field proposals", doField);
doField= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" private Object Fixe;\n");
buf.append("\n");
buf.append(" void foo() {\n");
buf.append(" char ch= Fixe.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.LOCAL) {
assertTrue("2 local proposals", doLocal);
doLocal= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" void foo() {\n");
buf.append(" Object Fixe = null;\n");
buf.append(" char ch= Fixe.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.PARAM) {
assertTrue("2 param proposals", doParam);
doParam= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" void foo(Object Fixe) {\n");
buf.append(" char ch= Fixe.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else {
assertTrue("unknown type", false);
}
} else if (curr instanceof NewCUCompletionUsingWizardProposal) {
NewCUCompletionUsingWizardProposal proposal= (NewCUCompletionUsingWizardProposal) curr;
proposal.setShowDialog(false);
proposal.apply(null);
ICompilationUnit newCU= pack1.getCompilationUnit("Fixe.java");
assertTrue("Nothing created", newCU.exists());
if (proposal.isClass()) {
assertTrue("2 class proposals", doClass);
doClass= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("public class Fixe {\n");
buf.append("\n");
buf.append("}\n");
assertEqualStringIgnoreDelim(newCU.getSource(), buf.toString());
JavaProjectHelper.performDummySearch();
newCU.delete(true, null);
} else {
assertTrue("2 interface proposals", doInterface);
doInterface= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("public interface Fixe {\n");
buf.append("\n");
buf.append("}\n");
assertEqualStringIgnoreDelim(newCU.getSource(), buf.toString());
JavaProjectHelper.performDummySearch();
newCU.delete(true, null);
}
} else {
assertTrue("2 replace proposals", doChange);
doChange= false;
CUCorrectionProposal proposal= (CUCorrectionProposal) curr;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" void foo() {\n");
buf.append(" char ch= File.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
}
}
|
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
org.eclipse.jdt.ui/core
| |
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
| |
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
org.eclipse.jdt.ui/core
| |
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java
| |
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ChangeMethodSignatureProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.NamingConventions;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ArrayType;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
public class ChangeMethodSignatureProposal extends ASTRewriteCorrectionProposal {
public static interface ChangeDescription {
}
public static class SwapDescription implements ChangeDescription {
int index;
public SwapDescription(int index) {
this.index= index;
}
}
public static class RemoveDescription implements ChangeDescription {
}
public static class EditDescription implements ChangeDescription {
String name;
ITypeBinding type;
public EditDescription(ITypeBinding type, String name) {
this.type= type;
this.name= name;
}
}
public static class InsertDescription implements ChangeDescription {
String name;
ITypeBinding type;
public InsertDescription(ITypeBinding type, String name) {
this.type= type;
this.name= name;
}
}
private CompilationUnit fRoot;
private IMethodBinding fSenderBinding;
private ChangeDescription[] fParameterChanges;
public ChangeMethodSignatureProposal(String label, ICompilationUnit targetCU, CompilationUnit root, IMethodBinding binding, ChangeDescription[] changes, int relevance, Image image) {
super(label, targetCU, null, relevance, image);
fRoot= root;
fSenderBinding= binding;
fParameterChanges= changes;
}
protected ASTRewrite getRewrite() throws CoreException {
ASTNode methodDecl= fRoot.findDeclaringNode(fSenderBinding);
ASTNode newMethodDecl= null;
CompilationUnit astRoot= fRoot;
boolean isInDifferentCU;
if (methodDecl != null) {
isInDifferentCU= false;
newMethodDecl= methodDecl;
} else {
isInDifferentCU= true;
astRoot= AST.parseCompilationUnit(getCompilationUnit(), true);
newMethodDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
}
if (newMethodDecl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(newMethodDecl);
modifySignature(rewrite, (MethodDeclaration) newMethodDecl, isInDifferentCU);
return rewrite;
}
return null;
}
private final String NAME_SUGGESTION= "name_suggestion"; //$NON-NLS-1$
protected void modifySignature(ASTRewrite rewrite, MethodDeclaration methodDecl, boolean isInDifferentCU) throws CoreException {
String rewriteDesc= isInDifferentCU ? SELECTION_GROUP_DESC : null;
List parameters= methodDecl.parameters();
// create a copy to not loose the indexes
SingleVariableDeclaration[] oldParameters= (SingleVariableDeclaration[]) parameters.toArray(new SingleVariableDeclaration[parameters.size()]);
AST ast= methodDecl.getAST();
int k= 0; // index over the oldParameters
ArrayList createdVariables= new ArrayList();
ArrayList usedNames= new ArrayList();
for (int i= 0; i < fParameterChanges.length; i++) {
ChangeDescription curr= fParameterChanges[i];
if (curr == null) {
usedNames.add(oldParameters[k].getName().getIdentifier());
k++;
} else if (curr instanceof InsertDescription) {
InsertDescription desc= (InsertDescription) curr;
SingleVariableDeclaration newNode= ast.newSingleVariableDeclaration();
String type= addImport(desc.type);
newNode.setType(ASTNodeFactory.newType(ast, type));
// set name later
newNode.setProperty(NAME_SUGGESTION, desc.name);
createdVariables.add(newNode);
rewrite.markAsInserted(newNode, rewriteDesc);
parameters.add(i, newNode);
} else if (curr instanceof RemoveDescription) {
rewrite.markAsRemoved(oldParameters[k], rewriteDesc);
k++;
} else if (curr instanceof EditDescription) {
EditDescription desc= (EditDescription) curr;
SingleVariableDeclaration newNode= ast.newSingleVariableDeclaration();
String type= addImport(desc.type);
newNode.setType(ASTNodeFactory.newType(ast, type));
// set name later
newNode.setProperty(NAME_SUGGESTION, desc.name);
rewrite.markAsReplaced(oldParameters[k], newNode);
createdVariables.add(newNode);
k++;
} else if (curr instanceof SwapDescription) {
SingleVariableDeclaration decl1= oldParameters[k];
SingleVariableDeclaration decl2= oldParameters[((SwapDescription) curr).index];
rewrite.markAsReplaced(decl1, rewrite.createCopy(decl2), rewriteDesc);
rewrite.markAsReplaced(decl2, rewrite.createCopy(decl1), rewriteDesc);
usedNames.add(decl1.getName().getIdentifier());
k++;
}
}
if (!createdVariables.isEmpty()) {
// avoid take a name of a local variable inside
CompilationUnit root= (CompilationUnit) methodDecl.getRoot();
IBinding[] bindings= (new ScopeAnalyzer()).getDeclarationsAfter(root, methodDecl.getBody().getStartPosition(), ScopeAnalyzer.VARIABLES);
for (int i= 0; i < bindings.length; i++) {
usedNames.add(bindings[i].getName());
}
}
// set names for new parameters
for (int i= 0; i < createdVariables.size(); i++) {
SingleVariableDeclaration var= (SingleVariableDeclaration) createdVariables.get(i);
String suggestedName= (String) var.getProperty(NAME_SUGGESTION);
int dim= 0;
if (suggestedName == null) {
Type type= var.getType();
if (type.isArrayType()) {
dim= ((ArrayType) type).getDimensions();
type= ((ArrayType) type).getElementType();
}
suggestedName= ASTNodes.asString(type);
}
String[] excludedNames= (String[]) usedNames.toArray(new String[usedNames.size()]);
String name= NamingConventions.suggestArgumentNames(getCompilationUnit().getJavaProject(), "", suggestedName, dim, excludedNames)[0]; //$NON-NLS-1$
var.setName(ast.newSimpleName(name));
usedNames.add(name);
}
}
}
|
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/MissingReturnTypeCorrectionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class MissingReturnTypeCorrectionProposal extends ASTRewriteCorrectionProposal {
private MethodDeclaration fMethodDecl;
private ReturnStatement fExistingReturn;
public MissingReturnTypeCorrectionProposal(ICompilationUnit cu, MethodDeclaration decl, ReturnStatement existingReturn, int relevance) {
super("", cu, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); //$NON-NLS-1$
fMethodDecl= decl;
fExistingReturn= existingReturn;
}
public String getDisplayString() {
if (fExistingReturn != null) {
return CorrectionMessages.getString("MissingReturnTypeCorrectionProposal.changereturnstatement.description"); //$NON-NLS-1$
} else {
return CorrectionMessages.getString("MissingReturnTypeCorrectionProposal.addreturnstatement.description"); //$NON-NLS-1$
}
}
/*(non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
*/
protected ASTRewrite getRewrite() throws CoreException {
AST ast= fMethodDecl.getAST();
if (fExistingReturn != null) {
ASTRewrite rewrite= new ASTRewrite(fExistingReturn.getParent());
Expression expression= getReturnExpresion(ast, fExistingReturn.getStartPosition());
if (expression != null) {
fExistingReturn.setExpression(expression);
rewrite.markAsInserted(expression);
}
return rewrite;
} else {
ASTRewrite rewrite= new ASTRewrite(fMethodDecl);
Block block= fMethodDecl.getBody();
List statements= block.statements();
int offset;
if (statements.isEmpty()) {
offset= block.getStartPosition() + 1;
} else {
ASTNode lastStatement= (ASTNode) statements.get(statements.size() - 1);
offset= lastStatement.getStartPosition() + lastStatement.getLength();
}
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(getReturnExpresion(ast, offset));
statements.add(returnStatement);
rewrite.markAsInserted(returnStatement);
return rewrite;
}
}
private Expression getReturnExpresion(AST ast, int returnOffset) {
CompilationUnit root= (CompilationUnit) fMethodDecl.getRoot();
IMethodBinding methodBinding= fMethodDecl.resolveBinding();
if (methodBinding != null && methodBinding.getReturnType() != null) {
ITypeBinding returnBinding= methodBinding.getReturnType();
ScopeAnalyzer analyzer= new ScopeAnalyzer();
IBinding[] bindings= analyzer.getDeclarationsInScope(root, returnOffset, ScopeAnalyzer.VARIABLES);
for (int i= 0; i < bindings.length; i++) {
IVariableBinding curr= (IVariableBinding) bindings[i];
ITypeBinding type= curr.getType();
if (type != null && ASTResolving.canAssign(type, returnBinding) && testModifier(curr)) {
return ast.newSimpleName(curr.getName());
}
}
}
return ASTNodeFactory.newDefaultExpression(ast, fMethodDecl.getReturnType(), fMethodDecl.getExtraDimensions());
}
private boolean testModifier(IVariableBinding curr) {
int modifiers= curr.getModifiers();
int staticFinal= Modifier.STATIC | Modifier.FINAL;
if ((modifiers & staticFinal) == staticFinal) {
return false;
}
if (Modifier.isStatic(modifiers) && !Modifier.isStatic(fMethodDecl.getModifiers())) {
return false;
}
return true;
}
}
|
37,399 |
Bug 37399 Organize Imports can remove required inner interfaces [code manipulation]
|
import com.epiphany.shr.sf.ClusterSingletonStepped.SingletonStep; After organize imports, this import is turned into: import com.epiphany.shr.sf.ClusterSingletonStepped; If it is not legal to have inner interfaces I appologize and I will flog the coder. Otherwise, it appears that organize imports can potentially cause compiler errors that are hard to track down. I run it, and things look ok, but part of my import is gone. Interface definition: public abstract class ClusterSingletonStepped extends ClusterSingleton { ..... public interface SingletonStep ..... } Thanks for looking at this. Please let me know if I can add any additional information or answer any questions.
|
resolved fixed
|
12046bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-12T17:23:47Z | 2003-05-08T18:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - New class/interface with wizard
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
import org.eclipse.jdt.internal.corext.textmanipulation.SimpleTextEdit;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription;
public class UnresolvedElementsSubProcessor {
public static void getVariableProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
// type that defines the variable
ITypeBinding binding= null;
ITypeBinding declaringTypeBinding= ASTResolving.getBindingOfParentType(selectedNode);
if (declaringTypeBinding == null) {
return;
}
// possible type kind of the node
boolean suggestVariablePropasals= true;
int typeKind= 0;
Name node= null;
switch (selectedNode.getNodeType()) {
case ASTNode.SIMPLE_NAME:
node= (SimpleName) selectedNode;
ASTNode parent= node.getParent();
if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) {
typeKind= SimilarElementsRequestor.CLASSES;
} else if (parent instanceof SimpleType) {
suggestVariablePropasals= false;
typeKind= SimilarElementsRequestor.REF_TYPES;
}
break;
case ASTNode.QUALIFIED_NAME:
QualifiedName qualifierName= (QualifiedName) selectedNode;
ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding();
if (qualifierBinding != null) {
node= qualifierName.getName();
binding= qualifierBinding;
} else {
node= qualifierName.getQualifier();
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariablePropasals= node.isSimpleName();
}
if (selectedNode.getParent() instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariablePropasals= false;
}
break;
case ASTNode.FIELD_ACCESS:
FieldAccess access= (FieldAccess) selectedNode;
Expression expression= access.getExpression();
if (expression != null) {
binding= expression.resolveTypeBinding();
if (binding != null) {
node= access.getName();
}
}
break;
case ASTNode.SUPER_FIELD_ACCESS:
binding= declaringTypeBinding.getSuperclass();
node= ((SuperFieldAccess) selectedNode).getName();
break;
default:
}
if (node == null) {
return;
}
// add type proposals
if (typeKind != 0) {
int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0;
addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals);
}
if (!suggestVariablePropasals) {
return;
}
SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
addSimilarVariableProposals(cu, astRoot, simpleName, proposals);
// new variables
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding;
if (senderBinding.isFromSource() && targetCU != null && JavaModelUtil.isEditable(targetCU)) {
String label;
Image image;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", simpleName.getIdentifier()); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 2, image));
if (binding == null && senderBinding.isAnonymous()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding);
if (anonymDecl != null) {
senderBinding= ASTResolving.getBindingOfParentType(anonymDecl.getParent());
if (!senderBinding.isAnonymous()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), senderBinding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 2, image));
}
}
}
}
if (binding == null) {
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
int type= bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, 1, image));
}
if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, 3, image));
}
}
}
private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, SimpleName node, List proposals) {
IBinding[] varsInScope= (new ScopeAnalyzer()).getDeclarationsInScope(astRoot, node.getStartPosition(), ScopeAnalyzer.VARIABLES);
if (varsInScope.length > 0) {
// avoid corrections like int i= i;
String assignedName= null;
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
assignedName= ((VariableDeclarationFragment) parent).getName().getIdentifier();
}
ITypeBinding guessedType= ASTResolving.guessBindingForReference(node);
if (astRoot.getAST().resolveWellKnownType("java.lang.Object") == guessedType) { //$NON-NLS-1$
guessedType= null; // too many suggestions
}
String identifier= node.getIdentifier();
for (int i= 0; i < varsInScope.length; i++) {
IVariableBinding curr= (IVariableBinding) varsInScope[i];
String currName= curr.getName();
if (!currName.equals(assignedName)) {
int relevance= 0;
if (NameMatcher.isSimilarName(currName, identifier)) {
relevance += 3; // variable with a similar name than the unresolved variable
}
if (guessedType != null && ASTResolving.canAssign(guessedType, curr.getType())) {
relevance += 2; // unresolved variable can be assign to this variable
}
if (relevance > 0) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
}
}
}
}
}
public static void getTypeProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
int kind= SimilarElementsRequestor.ALL_TYPES;
ASTNode parent= selectedNode.getParent();
while (parent.getLength() == selectedNode.getLength()) { // get parent of type or variablefragment
parent= parent.getParent();
}
switch (parent.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
TypeDeclaration typeDeclaration=(TypeDeclaration) parent;
if (typeDeclaration.superInterfaces().contains(selectedNode)) {
kind= SimilarElementsRequestor.INTERFACES;
} else if (selectedNode.equals(typeDeclaration.getSuperclass())) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
case ASTNode.METHOD_DECLARATION:
MethodDeclaration methodDeclaration= (MethodDeclaration) parent;
if (methodDeclaration.thrownExceptions().contains(selectedNode)) {
kind= SimilarElementsRequestor.CLASSES;
} else if (selectedNode.equals(methodDeclaration.getReturnType())) {
kind= SimilarElementsRequestor.REF_TYPES | SimilarElementsRequestor.VOIDTYPE;
}
break;
case ASTNode.INSTANCEOF_EXPRESSION:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.THROW_STATEMENT:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.CLASS_INSTANCE_CREATION:
if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) {
kind= SimilarElementsRequestor.CLASSES;
} else {
kind= SimilarElementsRequestor.REF_TYPES;
}
break;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
int superParent= parent.getParent().getNodeType();
if (superParent == ASTNode.CATCH_CLAUSE) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
default:
}
Name node= null;
if (selectedNode instanceof SimpleType) {
node= ((SimpleType) selectedNode).getName();
} else if (selectedNode instanceof ArrayType) {
Type elementType= ((ArrayType) selectedNode).getElementType();
if (elementType.isSimpleType()) {
node= ((SimpleType) elementType).getName();
}
} else if (selectedNode instanceof Name) {
node= (Name) selectedNode;
} else {
return;
}
// change to simlar type proposals
addSimilarTypeProposals(kind, cu, node, 3, proposals);
// add type
addNewTypeProposals(cu, node, kind, 0, proposals);
}
private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, List proposals) throws JavaModelException {
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind);
// try to resolve type in context -> highest severity
String resolvedTypeName= null;
ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
if (binding != null) {
if (binding.isArray()) {
binding= binding.getElementType();
}
resolvedTypeName= binding.getQualifiedName();
proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2));
}
// add all similar elements
for (int i= 0; i < elements.length; i++) {
SimilarElement elem= elements[i];
if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) {
String fullName= elem.getName();
if (!fullName.equals(resolvedTypeName)) {
proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance));
}
}
}
}
private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws JavaModelException {
CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String simpleName= importEdit.addImport(fullName);
TextEdit root= proposal.getRootTextEdit();
if (!importEdit.isEmpty()) {
root.add(importEdit); //$NON-NLS-1$
}
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", fullName)); //$NON-NLS-1$
proposal.setRelevance(relevance + 20);
} else {
root.add(SimpleTextEdit.createReplace(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", simpleName)); //$NON-NLS-1$
proposal.setRelevance(relevance);
}
return proposal;
}
private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, List proposals) throws JavaModelException {
Name node= refNode;
do {
String typeName= ASTResolving.getSimpleName(node);
Name qualifier= null;
// only propose to create types for qualifiers when the name starts with upper case
boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode);
if (isPossibleName) {
IPackageFragment enclosingPackage= null;
IType enclosingType= null;
if (node.isSimpleName()) {
enclosingPackage= (IPackageFragment) cu.getParent();
// don't sugest member type, user can select it in wizard
} else {
Name qualifierName= ((QualifiedName) node).getQualifier();
// 24347
// IBinding binding= qualifierName.resolveBinding();
// if (binding instanceof ITypeBinding) {
// enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject());
IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
if (res!= null && res.length > 0 && res[0] instanceof IType) {
enclosingType= (IType) res[0];
} else {
qualifier= qualifierName;
enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName));
}
}
// new top level type
if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance));
}
}
// new member type
if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) {
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance));
}
}
}
node= qualifier;
} while (node != null);
}
public static void getMethodProposals(ICorrectionContext context, boolean needsNewName, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (!(selectedNode instanceof SimpleName)) {
return;
}
SimpleName nameNode= (SimpleName) selectedNode;
List arguments;
Expression sender;
boolean isSuperInvocation;
ASTNode invocationNode= nameNode.getParent();
if (invocationNode instanceof MethodInvocation) {
MethodInvocation methodImpl= (MethodInvocation) invocationNode;
arguments= methodImpl.arguments();
sender= methodImpl.getExpression();
isSuperInvocation= false;
} else if (invocationNode instanceof SuperMethodInvocation) {
SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode;
arguments= methodImpl.arguments();
sender= methodImpl.getQualifier();
isSuperInvocation= true;
} else {
return;
}
String methodName= nameNode.getIdentifier();
int nArguments= arguments.size();
// corrections
IBinding[] bindings= (new ScopeAnalyzer()).getDeclarationsInScope(astRoot, nameNode.getStartPosition(), ScopeAnalyzer.METHODS);
ArrayList parameterMismatchs= new ArrayList();
for (int i= 0; i < bindings.length; i++) {
IMethodBinding binding= (IMethodBinding) bindings[i];
String curr= binding.getName();
if (curr.equals(methodName) && needsNewName) {
parameterMismatchs.add(binding);
} else if (binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr)) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, context.getCompilationUnit(), context.getOffset(), context.getLength(), curr, 2));
}
}
addParameterMissmatchProposals(context, parameterMismatchs, arguments, proposals);
// new method
ITypeBinding binding= null;
if (sender != null) {
binding= sender.resolveTypeBinding();
} else {
binding= ASTResolving.getBindingOfParentType(invocationNode);
if (isSuperInvocation && binding != null) {
binding= binding.getSuperclass();
}
}
if (binding != null && binding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
if (targetCU != null) {
String label;
Image image;
String sig= getMethodSignature(methodName, arguments);
if (cu.equals(targetCU)) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", sig); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { sig, targetCU.getElementName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
}
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 1, image));
if (binding.isAnonymous() && cu.equals(targetCU)) {
ASTNode anonymDecl= astRoot.findDeclaringNode(binding);
if (anonymDecl != null) {
binding= ASTResolving.getBindingOfParentType(anonymDecl.getParent());
if (!binding.isAnonymous()) {
String[] args= new String[] { sig, binding.getName() };
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 1, image));
}
}
}
}
}
}
private static void addParameterMissmatchProposals(ICorrectionContext context, List similarElements, List arguments, List proposals) throws CoreException {
int nSimilarElements= similarElements.size();
ITypeBinding[] argTypes= getArgumentTypes(arguments);
if (argTypes == null || nSimilarElements == 0) {
return;
}
for (int i= 0; i < nSimilarElements; i++) {
IMethodBinding elem = (IMethodBinding) similarElements.get(i);
int diff= elem.getParameterTypes().length - argTypes.length;
if (diff == 0) {
int nProposals= proposals.size();
doEqualNumberOfParameters(context, arguments, argTypes, elem, proposals);
if (nProposals != proposals.size()) {
return; // only suggest for one method (avoid duplicated proposals)
}
} else if (diff > 0) {
doMoreParameters(context, arguments, argTypes, elem, proposals);
} else {
doMoreArguments(context, arguments, argTypes, elem, proposals);
}
}
}
private static void doMoreParameters(ICorrectionContext context, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, List proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int k= 0, nSkipped= 0;
int diff= paramTypes.length - argTypes.length;
int[] indexSkipped= new int[diff];
for (int i= 0; i < paramTypes.length; i++) {
if (k < argTypes.length && ASTResolving.canAssign(argTypes[k], paramTypes[i])) {
k++; // match
} else {
if (nSkipped >= diff) {
return; // too different
}
indexSkipped[nSkipped++]= i;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
// add arguments
{
ASTNode selectedNode= context.getCoveringNode();
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
for (int i= 0; i < diff; i++) {
int idx= indexSkipped[i];
Expression newArg= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), paramTypes[idx]);
rewrite.markAsInserted(newArg);
arguments.add(idx, newArg);
}
String[] arg= new String[] { getMethodSignature(methodBinding, false) };
String label;
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargument.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addarguments.description", arg); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// remove parameters
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
ITypeBinding[] changedTypes= new ITypeBinding[diff];
for (int i= diff - 1; i >= 0; i--) {
int idx= indexSkipped[i];
changeDesc[idx]= new RemoveDescription();
changedTypes[i]= paramTypes[idx];
}
String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changedTypes) };
String label;
if (methodBinding.isConstructor()) {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.constr.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.constr.description", arg); //$NON-NLS-1$
}
} else {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.description", arg); //$NON-NLS-1$
}
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, astRoot, methodBinding, changeDesc, 1, image);
proposals.add(proposal);
}
}
}
private static String getTypeNames(ITypeBinding[] types) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < types.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(types[i].getName());
}
return buf.toString();
}
private static void doMoreArguments(ICorrectionContext context, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, List proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int k= 0, nSkipped= 0;
int diff= argTypes.length - paramTypes.length;
int[] indexSkipped= new int[diff];
for (int i= 0; i < argTypes.length; i++) {
if (k < paramTypes.length && ASTResolving.canAssign(argTypes[i], paramTypes[k])) {
k++; // match
} else {
if (nSkipped >= diff) {
return; // too different
}
indexSkipped[nSkipped++]= i;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
// remove arguments
{
ASTNode selectedNode= context.getCoveringNode();
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
for (int i= diff - 1; i >= 0; i--) {
rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i]));
}
String[] arg= new String[] { getMethodSignature(methodBinding, false) };
String label;
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeargument.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removearguments.description", arg); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// add parameters
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length];
ITypeBinding[] changeTypes= new ITypeBinding[diff];
for (int i= diff - 1; i >= 0; i--) {
int idx= indexSkipped[i];
Expression arg= (Expression) arguments.get(idx);
String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
ITypeBinding newType= ASTResolving.normalizeTypeBinding(argTypes[idx]);
if (newType == null) {
newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
changeDesc[idx]= new InsertDescription(newType, name);
changeTypes[i]= newType;
}
String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changeTypes) };
String label;
if (methodBinding.isConstructor()) {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.constr.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.constr.description", arg); //$NON-NLS-1$
}
} else {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.description", arg); //$NON-NLS-1$
}
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, astRoot, methodBinding, changeDesc, 1, image);
proposals.add(proposal);
}
}
}
private static String getMethodSignature(IMethodBinding binding, boolean inOtherCU) {
StringBuffer buf= new StringBuffer();
if (inOtherCU && !binding.isConstructor()) {
buf.append(binding.getDeclaringClass().getName()).append('.');
}
buf.append(binding.getName());
return getMethodSignature(buf.toString(), binding.getParameterTypes());
}
private static String getMethodSignature(String name, List args) {
ITypeBinding[] params= new ITypeBinding[args.size()];
for (int i= 0; i < args.size(); i++) {
Expression expr= (Expression) args.get(i);
ITypeBinding curr= ASTResolving.normalizeTypeBinding(expr.resolveTypeBinding());
if (curr == null) {
curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
params[i]= curr;
}
return getMethodSignature(name, params);
}
private static String getMethodSignature(String name, ITypeBinding[] params) {
StringBuffer buf= new StringBuffer();
buf.append(name).append('(');
for (int i= 0; i < params.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(params[i].getName());
}
buf.append(')');
return buf.toString();
}
private static void doEqualNumberOfParameters(ICorrectionContext context, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, List proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int[] indexOfDiff= new int[paramTypes.length];
int nDiffs= 0;
for (int n= 0; n < argTypes.length; n++) {
if (!ASTResolving.canAssign(argTypes[n], paramTypes[n])) {
indexOfDiff[nDiffs++]= n;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
if (nDiffs == 1) { // one argument missmatching: try to fix
int idx= indexOfDiff[0];
Expression nodeToCast= (Expression) arguments.get(idx);
String castType= paramTypes[idx].getQualifiedName();
ASTRewriteCorrectionProposal proposal= LocalCorrectionsSubProcessor.getCastProposal(context, castType, nodeToCast);
if (proposal != null) { // null returned when no cast is possible
proposals.add(proposal);
String[] arg= new String[] { String.valueOf(idx + 1), castType };
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$
}
}
if (nDiffs == 2) { // try to swap
int idx1= indexOfDiff[0];
int idx2= indexOfDiff[1];
boolean canSwap= ASTResolving.canAssign(argTypes[idx1], paramTypes[idx2]) && ASTResolving.canAssign(argTypes[idx2], paramTypes[idx1]);
if (canSwap) {
Expression arg1= (Expression) arguments.get(idx1);
Expression arg2= (Expression) arguments.get(idx2);
ASTRewrite rewrite= new ASTRewrite(arg1.getParent());
rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2));
rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1));
{
String[] arg= new String[] { String.valueOf(idx1 + 1), String.valueOf(idx2 + 1) };
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swaparguments.description", arg); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
for (int i= 0; i < nDiffs; i++) {
changeDesc[idx1]= new SwapDescription(idx2);
}
ITypeBinding[] swappedTypes= new ITypeBinding[] { argTypes[idx1], paramTypes[idx2] };
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getTypeNames(swappedTypes) };
String label;
if (methodBinding.isConstructor()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.constr.description", args); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.description", args); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, astRoot, methodBinding, changeDesc, 1, image);
proposals.add(proposal);
}
}
return;
}
}
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
for (int i= 0; i < nDiffs; i++) {
int diffIndex= indexOfDiff[i];
Expression arg= (Expression) arguments.get(diffIndex);
String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
changeDesc[diffIndex]= new EditDescription(argTypes[diffIndex], name);
}
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) };
String label;
if (methodBinding.isConstructor()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.constr.description", args); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.description", args); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, astRoot, methodBinding, changeDesc, 1, image);
proposals.add(proposal);
}
}
}
private static ITypeBinding[] getArgumentTypes(List arguments) {
ITypeBinding[] res= new ITypeBinding[arguments.size()];
for (int i= 0; i < res.length; i++) {
Expression expression= (Expression) arguments.get(i);
ITypeBinding curr= expression.resolveTypeBinding();
if (curr == null) {
return null;
}
curr= ASTResolving.normalizeTypeBinding(curr);
if (curr == null) {
curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
res[i]= curr;
}
return res;
}
public static void getConstructorProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
ITypeBinding targetBinding= null;
List arguments= null;
int type= selectedNode.getNodeType();
if (type == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
IBinding binding= creation.getName().resolveBinding();
if (binding instanceof ITypeBinding) {
targetBinding= (ITypeBinding) binding;
arguments= creation.arguments();
}
} else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= ASTResolving.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding.getSuperclass();
arguments= ((SuperConstructorInvocation) selectedNode).arguments();
}
} else if (type == ASTNode.CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= ASTResolving.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding;
arguments= ((ConstructorInvocation) selectedNode).arguments();
}
}
if (targetBinding == null) {
return;
}
IMethodBinding[] methods= targetBinding.getDeclaredMethods();
ArrayList similarElements= new ArrayList();
IMethodBinding defConstructor= null;
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor()) {
if (curr.getParameterTypes().length == 0) {
defConstructor= curr;
} else {
similarElements.add(curr);
}
}
}
if (defConstructor != null) {
// default constructor could be implicit (bug 36819). Only add when we're sure its not.
// Misses the case when in other type
if (!similarElements.isEmpty() || (astRoot.findDeclaringNode(defConstructor) != null)) {
similarElements.add(defConstructor);
}
}
addParameterMissmatchProposals(context, similarElements, arguments, proposals);
if (targetBinding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding);
if (targetCU != null) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", targetBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 1, image));
}
}
}
public static void getAmbiguosTypeReferenceProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
int offset= context.getOffset();
int len= context.getLength();
IJavaElement[] elements= cu.codeSelect(offset, len);
for (int i= 0; i < elements.length; i++) {
IJavaElement curr= elements[i];
if (curr instanceof IType) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 1, image);
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
importEdit.addImport(qualifiedTypeName);
importEdit.setFindAmbiguosImports(true);
proposal.getRootTextEdit().add(importEdit);
proposals.add(proposal);
}
}
}
}
|
37,508 |
Bug 37508 Type hierarchy: render inherited members differently
|
1) in the type hierarchy enable "Show all inherited members" -> when this option is on it should be easy for the user to spot which items are inherited and which ones are not. Options: - render inherited members in grey - use a hollow icon or grey icon for inherited members
|
resolved fixed
|
584a0a1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-13T07:55:50Z | 2003-05-12T17:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HierarchyLabelProvider.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.typehierarchy;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.resource.CompositeImageDescriptor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Label provider for the hierarchy viewers. Types in the hierarchy that are not belonging to the
* input scope are rendered differntly.
*/
public class HierarchyLabelProvider extends AppearanceAwareLabelProvider {
private static class HierarchyOverrideIndicatorLabelDecorator extends OverrideIndicatorLabelDecorator {
private TypeHierarchyLifeCycle fHierarchy;
public HierarchyOverrideIndicatorLabelDecorator(TypeHierarchyLifeCycle lifeCycle) {
super(null);
fHierarchy= lifeCycle;
}
/* (non-Javadoc)
* @see OverrideIndicatorLabelDecorator#getOverrideIndicators(IMethod)
*/
protected int getOverrideIndicators(IMethod method) throws JavaModelException {
IType type= (IType) JavaModelUtil.toOriginal(method.getDeclaringType());
ITypeHierarchy hierarchy= fHierarchy.getHierarchy();
if (hierarchy != null) {
return findInHierarchy(type, hierarchy, method.getElementName(), method.getParameterTypes());
}
return 0;
}
}
private static class FocusDescriptor extends CompositeImageDescriptor {
private ImageDescriptor fBase;
public FocusDescriptor(ImageDescriptor base) {
fBase= base;
}
protected void drawCompositeImage(int width, int height) {
drawImage(fBase.getImageData(), 0, 0);
drawImage(JavaPluginImages.DESC_OVR_FOCUS.getImageData(), 0, 0);
}
protected Point getSize() {
return JavaElementImageProvider.BIG_SIZE;
}
public int hashCode() {
return fBase.hashCode();
}
public boolean equals(Object object) {
return object != null && FocusDescriptor.class.equals(object.getClass()) && ((FocusDescriptor)object).fBase.equals(fBase);
}
}
private boolean fShowDefiningType;
private TypeHierarchyLifeCycle fHierarchy;
public HierarchyLabelProvider(TypeHierarchyLifeCycle lifeCycle) {
super(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS);
fHierarchy= lifeCycle;
fShowDefiningType= false;
addLabelDecorator(new HierarchyOverrideIndicatorLabelDecorator(lifeCycle));
}
public void setShowDefiningType(boolean showDefiningType) {
fShowDefiningType= showDefiningType;
}
public boolean isShowDefiningType() {
return fShowDefiningType;
}
private boolean isDifferentScope(IType type) {
IJavaElement input= fHierarchy.getInputElement();
if (input == null || input.getElementType() == IJavaElement.TYPE) {
return false;
}
IJavaElement parent= type.getAncestor(input.getElementType());
if (input.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
if (parent == null || parent.getElementName().equals(input.getElementName())) {
return false;
}
} else if (input.equals(parent)) {
return false;
}
return true;
}
private IType getDefiningType(Object element) throws JavaModelException {
int kind= ((IJavaElement) element).getElementType();
if (kind != IJavaElement.METHOD && kind != IJavaElement.FIELD && kind != IJavaElement.INITIALIZER) {
return null;
}
IType declaringType= (IType) JavaModelUtil.toOriginal(((IMember) element).getDeclaringType());
if (kind != IJavaElement.METHOD) {
return declaringType;
}
ITypeHierarchy hierarchy= fHierarchy.getHierarchy();
if (hierarchy == null) {
return declaringType;
}
IMethod method= (IMethod) element;
int flags= method.getFlags();
if (Flags.isPrivate(flags) || Flags.isStatic(flags) || method.isConstructor()) {
return declaringType;
}
IMethod res= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, declaringType, method.getElementName(), method.getParameterTypes(), false);
if (res == null || method.equals(res)) {
return declaringType;
}
return res.getDeclaringType();
}
/* (non-Javadoc)
* @see ILabelProvider#getText
*/
public String getText(Object element) {
String text= super.getText(element);
if (fShowDefiningType) {
try {
IType type= getDefiningType(element);
if (type != null) {
StringBuffer buf= new StringBuffer(super.getText(type));
buf.append(JavaElementLabels.CONCAT_STRING);
buf.append(text);
return buf.toString();
}
} catch (JavaModelException e) {
}
}
return text;
}
/* (non-Javadoc)
* @see ILabelProvider#getImage
*/
public Image getImage(Object element) {
Image result= null;
if (element instanceof IType) {
ImageDescriptor desc= getTypeImageDescriptor((IType) element);
if (desc != null) {
if (element.equals(fHierarchy.getInputElement())) {
desc= new FocusDescriptor(desc);
}
result= JavaPlugin.getImageDescriptorRegistry().get(desc);
}
} else {
result= fImageLabelProvider.getImageLabel(element, evaluateImageFlags(element));
}
if (fLabelDecorators != null && result != null) {
for (int i= 0; i < fLabelDecorators.size(); i++) {
ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
result= decorator.decorateImage(result, element);
}
}
return result;
}
private ImageDescriptor getTypeImageDescriptor(IType type) {
ITypeHierarchy hierarchy= fHierarchy.getHierarchy();
if (hierarchy == null) {
return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_CLASS, 0, JavaElementImageProvider.BIG_SIZE);
}
IType originalType= (IType) JavaModelUtil.toOriginal(type);
int flags= hierarchy.getCachedFlags(originalType);
if (flags == -1) {
return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_CLASS, 0, JavaElementImageProvider.BIG_SIZE);
}
boolean isInterface= Flags.isInterface(flags);
boolean isInner= (type.getDeclaringType() != null);
ImageDescriptor desc;
if (isDifferentScope(type)) {
desc= isInterface ? JavaPluginImages.DESC_OBJS_INTERFACEALT : JavaPluginImages.DESC_OBJS_CLASSALT;
} else {
desc= JavaElementImageProvider.getTypeImageDescriptor(isInterface, isInner, flags);
}
int adornmentFlags= 0;
if (Flags.isFinal(flags)) {
adornmentFlags |= JavaElementImageDescriptor.FINAL;
}
if (Flags.isAbstract(flags) && !isInterface) {
adornmentFlags |= JavaElementImageDescriptor.ABSTRACT;
}
if (Flags.isStatic(flags)) {
adornmentFlags |= JavaElementImageDescriptor.STATIC;
}
return new JavaElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE);
}
}
|
37,508 |
Bug 37508 Type hierarchy: render inherited members differently
|
1) in the type hierarchy enable "Show all inherited members" -> when this option is on it should be easy for the user to spot which items are inherited and which ones are not. Options: - render inherited members in grey - use a hollow icon or grey icon for inherited members
|
resolved fixed
|
584a0a1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-05-13T07:55:50Z | 2003-05-12T17:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HierarchyOverrideIndicatorLabelDecorator.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.