how to get drop down list by type respective alphabet in ComboBoxViewerCellEditor - eclipse

In ComboBoxViewerCellEditor I want to write something and as a result I will get the matching dropdown value.
Can you suggest how to get this? Please find the code below:
public TCOperationColumnEditable(TableViewer viewer) {
super(viewer);
try
{
this.viewer = viewer;
//this.editor = new TextCellEditor(this.viewer.getTable());
OperationGSON[] allOperations = OperationAPIHandler.getInstance().getAllOperations();
ArrayList<String> opnName = new ArrayList<String>();
for(OperationGSON opn : allOperations)
{
opnName.add(opn.opnName);
}
this.editor = new ComboBoxViewerCellEditor(this.viewer.getTable(), SWT.FULL_SELECTION );
this.editor.setLabelProvider(new LabelProvider());
this.editor.setContentProvider(new ArrayContentProvide());
this.editor.setInput(opnName);
String[] stockArr = new String[opnName.size()];
stockArr = opnName.toArray(stockArr);
new AutoCompleteField(this.viewer.getControl(), new CComboContentAdapter(), stockArr);
}
catch(Exception e)
{
System.out.println("[" + getClass().getName() + " : TCOperationColumnEditable()] - Exception : " + e.getMessage());
e.printStackTrace();
}
}
enter image description here

Subclass TextCellEditor.
For a content proposal, use field assist API of JFace
(org.eclipse.jface.fieldassist). Content assist is enabled
when the cell editor is activated for the first time:
if (contentProposalAdapter == null) {
....
// enable content assist on the cell editor's text widget
contentProposalAdapter = new ContentProposalAdapter(text, new TextContentAdapter(), proposalProvider, activationKeyStroke, null);
} else {
contentProposalAdapter.setEnabled(true);
}
super.activate();
....
Make sure to also override method
TextCellEditor#dependsOnExternalFocusListener() to return false always.
Otherwise, you'll face some serious problems concerning focus.

Related

Printing to console removes hyperlinks created already

I was trying to create a feature to create hyperlinks in the console while the information is added.
While debugging, I noticed that the first hyperlink is succesfully created, but when the next line is printed to console, the hyperlink dissapears.
The code which I use to create the hyperlinks is:
String hyperLinkText = "test";
myConsole.printToConsole(test);
String myFile = new File("D:/Test/testFile.txt");
URI location = myFile.toURI();
IFile[] files = project.getWorkspace().getRoot().findFilesForLocationURI(location);
HyperlinkInformation hyperlinkInformation = new HyperlinkInformation(myConsole, myConsole.getDocument().get().length(), hyperLinkText.length());
FileHyperlink fileHyperlink = new FileHyperlink(hyperlinkInformation,
files[0], 1);
try {
hyperlinkInformation.getConsole().addHyperlink(fileHyperlink,
fileHyperlink.getOffset(), fileHyperlink.getLength());
} catch (BadLocationException e) {
//
}
The function addHyperlink:
public void addHyperlink(IHyperlink hyperlink, int offset, int length) throws BadLocationException {
IDocument document = getDocument();
ConsoleHyperlinkPosition hyperlinkPosition = new ConsoleHyperlinkPosition(hyperlink, offset, length);
try {
document.addPosition(ConsoleHyperlinkPosition.HYPER_LINK_CATEGORY, hyperlinkPosition);
fConsoleManager.refresh(this);
} catch (BadPositionCategoryException e) {
ConsolePlugin.log(e);
}
}
Is this the normal behaviour or am I missing something?

e4 Application / Menu

i try to create an eclipse 4 application but i have a problem: "Menu/New" : when i try to create a new file i receive this error message :
Internal error org.eclipse.E4.core.di.InjectionException:
java.lang.NullPointerException
this's the code:
public class OpenHandler {
#Execute
public void execute(#Named(IServiceConstants.ACTIVE_SHELL) Shell shell, EPartService partService, MApplication application,
EModelService modelService) {
FileDialog dialog = new FileDialog(shell);
String fileName = dialog.open();
if (fileName != null) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String text = scanner.useDelimiter("\\A").next();
scanner.close();
// create part
MPart part = MBasicFactory.INSTANCE.createPart();
part.setLabel(file.getName());
part.setCloseable(true);
part.getTags().add(EPartService.REMOVE_ON_HIDE_TAG);
part.setContributionURI("bundleclass://RCPTextEditor/RCPTextEditor.EditorPart");
// get part stack and show new part
List<MPartStack> stacks = modelService.findElements(application, null, MPartStack.class, null);
stacks.get(0).getChildren().add(part);
partService.showPart(part, PartState.ACTIVATE);
((EditorPart) part.getObject()).styledText.setText(text);
((EditorPart) part.getObject()).model = new EditorModel(text, text);
((EditorPart) part.getObject()).setFile(file);
part.setDirty(false);
} catch (IOException e) {
MessageDialog.openError(shell, "Error opening file", "File " + fileName + " could not be opened.");
}
}
}
}
Can someone help me ??? thanks in advance
Since you haven't show us the stack trace I am just guessing but the line
((EditorPart) part.getObject()).styledText.setText(text);
is probably accessing a styledText field before it has been created.
You need to do this in the #PostConstruct method of your EditorPart when you create the part controls.

Cascading dropdowns and control state (no AJAX, Jquery or Updated Panels)

I am having a weird post back problem. I have two dropdowns, project and charge codes. Projects selection populates the charge code drop down. I noticed that when I select a charge code, the value appears in the dropdown for a split second and then changes to the first choice in the dropdown. The Index change of that dropdown triggers and the value is the first option in the dropdown, not the one selected. I am not sure why it's doing this, but it must have something to do with postback. If it is a postback problem, is there a way to store the dropdown selection and restore the selection after re-load? Please don't suggest using AJAX or update panels, as we aren't allowed. Here is my asp code:
<p>
<asp:DropDownList ID="ddlProjects" runat="server"
onselectedindexchanged="ddlProjects_SelectedIndexChanged"
AutoPostBack="True" Visible="false" >
</asp:DropDownList>
</p>
<asp:DropDownList ID="ddlChargeCodes" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlChargeCodes_SelectedIndexChanged" Visible="false">
</asp:DropDownList>
<p>
and the C# code behind:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
LoadProjectsDropDown();
}
//Rest of Pageload Omitted....
// Initial Population of Project Dropdown
protected void LoadProjectsDropDown()
{
try
{ // Populate the Projects Drop Down from Table
ddlProjects.Items.Clear();
ddlProjects.DataSource = Time_Tracker.BLL.ProjectsManager.GetItems();
ddlProjects.DataTextField = "Project_Name";
ddlProjects.DataValueField = "Project_ID";
ddlProjects.DataBind();
ddlProjects.Items.Insert(0, new ListItem("PLEASE SELECT A PROJECT",
"PLEASE SELECT A PROJECT"));
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace,
#"Time_Tracker.txt");
}
}
// The Index Change portion of the Project Dropdown, which builds the Charge Code dropdown
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Project, Populate Charge Codes for the selected Project
ddlChargeCodes.Visible = true;
if (!string.IsNullOrEmpty(ddlProjects.SelectedValue))
{
ddlChargeCodes.Items.Clear();
ddlChargeCodes.DataSource = Time_Tracker.BLL.TasksManager.GetChargeCodes
(ddlProjects.SelectedValue);
ddlChargeCodes.DataTextField = "Description";
ddlChargeCodes.DataValueField = "Project_ID";
ddlChargeCodes.DataBind();
ddlChargeCodes.Items.Insert(0, new ListItem("PLEASE SELECT A CHARGE
CODE", "PLEASE SELECT A CHARGE CODE"));
Utilities.Project = Convert.ToInt16(ddlProjects.SelectedValue);
}
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
// The Index Change of the Charge Codes Dropdown
protected void ddlChargeCodes_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Charge Code, it shows a summary and asks for the number of hours
Utilities.Description = Convert.ToString(ddlChargeCodes.SelectedItem);
Utilities.Chargecode = Convert.ToString(ddlChargeCodes.SelectedItem);
lblHoursLabel.Visible = true;
txtHours.Visible = true;
lblConfirmation.Visible = true;
btnStarOver.Visible = true;
btnOK.Visible = true;
lblConfirmation.Text = "Hours on " + Utilities.SelectedDate + " For Charge Code " + Utilities.Description;
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
Did a lot of troubleshooting today. found that upon selecting the chargecode, it would do a pageload without triggering the "change index" event handler. Upon completion of pageload, it would trigger the index change event with the first selection (index 1) selected. Everyone I talked to said it should work the way it is. I finally wrote out the query/databind part of it to populate the dropdown instead of using the stored procedure and it now works. I have included the code change if it will help people in the future.
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Project, Populate Charge Codes for the selected Project
ddlChargeCodes.Visible = true;
if (!string.IsNullOrEmpty(ddlProjects.SelectedValue))
{
ddlChargeCodes.Items.Clear();
string strConn = Time_Tracker.DAL.DBUtils.SqlConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Charge_Code, Charge_Code + ' - ' + Description AS Description FROM [Time_Tracker].[dbo].[Tasks] WHERE Inactive = 0 AND Project_ID = " + ddlProjects.SelectedValue;
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlChargeCodes.DataSource = objDs.Tables[0];
ddlChargeCodes.DataTextField = "Description";
ddlChargeCodes.DataValueField = "Charge_Code";
ddlChargeCodes.DataBind();
ddlChargeCodes.Items.Insert(0, "PLEASE SELECT A CHARGE CODE");
}
Utilities.Project = Convert.ToInt16(ddlProjects.SelectedValue);
}
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}

GWT-RPC method returns empty list on success

I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;

How to indicate a file has changed after modifying it using IFile

I've been able to successfully update the contents of a file via a popup menu extension I've created underneath the Source menu that comes up when right-clicking on a file.
I'd like to indicate that the file has been changed and needs to be saved. Right now, the file contents change and save automatically. I thought the IFile.touch method would cause the file to be in a state where it needed to be saved but I'm not seeing that happen.
Here's my code...
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
IEditorInput input = editorPart.getEditorInput();
InputStream is = null;
if (input instanceof FileEditorInput) {
IFile file = ((FileEditorInput) input).getFile();
try {
is = file.getContents();
String originalContents = convertStreamToString(is);
String newContents = originalContents + "testing changing the contents...";
InputStream newInput = new ByteArrayInputStream(newContents.getBytes());
file.setContents(newInput, false, true, null);
file.touch(null);
} catch (CoreException e) {
MessageDialog.openError(
window.getShell(),
"Generate Builder Error",
"An Exception has been thrown when interacting with file " + file.getName() +
": " + e.getMessage());
}
}
return null;
}
If you want the file's contents marked as needing to be saved, you need to be interacting with the in-memory representation you want to prompt as needing to be saved--the editor from which you're getting the input.
Based on help from nitind and this post - Replace selected code from eclipse editor thru plugin comand - I was able to update the text editor and the file shows up as modified. The key was to work with the ITextEditor and IDocumentProvider instead of a FileEditor.
Here's the updated code...
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
if (editorPart instanceof ITextEditor ) {
ITextEditor editor = (ITextEditor)editorPart;
IDocumentProvider prov = editor.getDocumentProvider();
IDocument doc = prov.getDocument( editor.getEditorInput() );
String className = getClassName(doc.get());
ISelection sel = editor.getSelectionProvider().getSelection();
if (sel instanceof TextSelection ) {
TextSelection textSel = (TextSelection)sel;
String newText = generateBuilderText(className, textSel.getText());
try {
doc.replace(textSel.getOffset(), textSel.getLength(), newText);
} catch (Exception e) {
MessageDialog.openError(
window.getShell(),
"Generate Builder Error",
"An Exception has been thrown when attempting to replace "
+ "text in editor " + editor.getTitle() +
": " + e.getMessage());
}
}
}
return null;
}