GWT client "throws Exception" cause compling problem - gwt

I try to use get result from a api called j-calais, and then out put the result on a web page, i write all the code in client, but it cant compile right, dont know why??? please help. the source code like below:
there is no obvious error arise, but it cant be compile successfully..... thanks a lot:
public void onModuleLoad() {
// Create table for stock data.
stocksFlexTable.setText(0, 0, "Type");
stocksFlexTable.setText(0, 1, "Name");
// Assemble Add Stock panel.
addPanel.add(newSymbolTextBox);
addPanel.add(addStockButton);
// Assemble Main panel.
mainPanel.add(stocksFlexTable);
mainPanel.add(addPanel);
mainPanel.add(lastUpdatedLabel);
// Associate the Main panel with the HTML host page.
RootPanel.get("stockList").add(mainPanel);
// Move cursor focus to the input box.
newSymbolTextBox.setFocus(true);
// Listen for mouse events on the Add button.
addStockButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
try {
addStock();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// Listen for keyboard events in the input box.
newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
try {
addStock();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void addStock() throws Exception {
final String url_s = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
newSymbolTextBox.setText("");
int row = stocksFlexTable.getRowCount();
CalaisClient client = new CalaisRestClient("ysw5rx69jkvdnzqf6sgjduqj");
System.out.print("read success...\n");
URL url = new URL(url_s);
CalaisResponse response = client.analyze(url);
for (CalaisObject entity : response.getEntities()) {
System.out.println(entity.getField("_type") + ":"
+ entity.getField("name"));
stocks.add(entity.getField("_type"));
stocksFlexTable.setText(row, 0, entity.getField("_type"));
stocksFlexTable.setText(row, 1, entity.getField("name"));
}
for (CalaisObject topic : response.getTopics()) {
System.out.println(topic.getField("categoryName"));
}
}
}

GWT only handles unchecked exceptions so you can throw Runtime Exceptions
or write your own Exception that extends from Runtime Exception then it will not cause any compile time problem
void f() throws NullPointerException // will not cause any problem because it is Runtime exception so unchecked
void f() throws IllegalAccessException // it is checked exception so there will be problem at compile time

Related

How to pass argument in class that extends "EditorPart" from handler class to affect "createPartControl" UI creation

I have 2 problems.
1) Command handler not responding for EditorPart
2) How to pass argument to a class that extends "EditorPart" to affect "createPartControl" method for UI creation.
Please have a look below in my code for better understanding. I have created command handler for Editor but my handler is not responding as expected. I want to have the selected file path in the package explorer and pass this file path value to the class that extends EditorPart in order to create UI based on this selected file.
Handler.java
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// get the page
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
// get the selection
ISelection selection = HandlerUtil.getCurrentSelection(event);
IStructuredSelection sel = (IStructuredSelection) selection;
Object selObj = sel.getFirstElement();
if (selObj instanceof IResource) {
resource = (IResource) selObj;
project = resource.getProject();
location = project.getLocation();
}else {
IAdaptable adaptable = (IAdaptable)selObj;
Object adapter = adaptable.getAdapter(IResource.class);
resource = (IResource) adapter;
project = resource.getProject();
location = project.getLocation();
}
TaskEditorInput input = new TaskEditorInput();
try {
page.openEditor(input, "launcher.ChartEditor");
} catch (PartInitException e) {
e.printStackTrace();
}
return null;
}
class that extends EditorPart
#Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
setPartName("ChartEditor");
}
public void createPartControl(Composite _parent) {
}
public void createChart(String filePath) {
dataset = chart1.createDataset(filePath);
try {
chart = chart1.createChart(dataset);
frame = new ChartComposite(parent, SWT.NONE, chart, true);
frame.pack();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I want pass the value of selected filepath in this createChart(String filePath) method from handler class. How can i do this? Please help me.
Add the value you want to pass to your class implementing IEditorInput (TaskEditorInput in your case). The editor input is given to the editor init method so you can get the value there:
#Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
if (input instanceof TaskEditorInout) {
TaskEditorInput taskInput = (TaskEditorInput)input;
// TODO save value for createPartControl
}
setSite(site);
setInput(input);
setPartName("ChartEditor");
}
To be sure to get the resource corresponding to a selection you need to use the platform adapter manager. On modern versions of Eclipse you can use
IStructuredSelection sel = HandlerUtil.getCurrentStructuredSelection(event);
IResource resource = Adapters.adapt(sel.getFirstElement(), IResource.class);

PropertyChangeListener validation

i'm try to implemente a view from eclipse preference page and in some fields this method (performStringSubstitution) not work because the StringFieldEditor do the validation before and don't give a permission to label.setText(), i'll appreciate any help. `
public void propertyChange(PropertyChangeEvent event)
{
/*Solve Eclipse variable method (${workspace_loc},${project_loc},...)*/
String dir = Activator.getDefault().getPreferenceStore()
.getString(event.getNewValue().toString());
IStringVariableManager manager = VariablesPlugin.getDefault()
.getStringVariableManager();
try {
String solvePathUpdate = manager.performStringSubstitution(dir);
label.setText(solvePathUpdate);
}
catch (CoreException e)
{
// TODO Auto-generated catch block
/* Creating the method print console */
}
}

Launching Dialog Box with Data from TableView Row

I'm attempting to launch an Edit Customer Window with text fields filled with reference from the rows of a table. The Table and Dialog both have different controller classes.
Here's the code snippet from the table in question that gives us the required customerID when a user double clicks on a row.
Table Controller: CustomersController:
#Override
public void initialize(URL location, ResourceBundle resources) {
populateCustomerTable();
tableListeners(null);
}
void tableListeners(CustomerData customerData){
tblcustomer.setRowFactory(tr -> {
TableRow<CustomerData> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
int selectedCustomerID = row.getItem().getCustomerID();
System.out.println("A certain row: " + selectedCustomerID + " has been clicked!");
Stage stage = new Stage();
FXMLLoader loader = new FXMLLoader();
try {
Parent root = loader.load(getClass().getResource("../view/popups/edit_customer.fxml"));
stage.setScene(new Scene(root));
stage.setTitle("Editing Existing Customer's Details");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(btnEditCustomer.getScene().getWindow());
stage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
});
return row;
});
}
I want selectedCustomerID from the above piece of code to be parsed into the EditCustomerController class hence when the dialog launches, it's text fields should be prepoulated with values suppled from the select query that queries the database with the where condition being tht selectedCustomerID from the CustomersController class.
Code snippet from EditCustomerController class:
#Override
public void initialize(URL location, ResourceBundle resources) {
//populateEditCustomerFields(1);
}
void populateEditCustomerFields(int customerID){
this.customer_ID=customerID;
System.out.println(customer_ID);
try {
con = DatabaseConnection.getConnected();
stmt = con.createStatement();
rs = con.createStatement().executeQuery("SELECT * FROM `h_customers` WHERE `customerID`=" + customer_ID);
while (rs.next()) {
title.setText(rs.getString("title"));
firstName.setText(rs.getString("firstName"));
lastName.setText(rs.getString("lastName"));
nationalID.setText(String.valueOf(rs.getInt("nationalID")));
//dob.setText(rs.getString("DOB"));
mobilePhone.setText(rs.getString("mobilePhone"));
workPhone.setText(rs.getString("workPhone"));
email.setText(rs.getString("email"));
}
} catch (SQLException ex) {
Logger.getLogger(NewRoomController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
The Idea here is to parse selectedCustomerID from CustomersController into the initialize method of EditCustomerController so the Dialog can launch with the customer details that require editing. I've searched for solutions all over the web and here on StackOverflow, some come close to answering me, some are too complex for my newbie mind, but none has helped. Any solution would be highly appreciated. I will provide any further clarification required.
You can get the controller class and invoke its necessary methods. See this answer for getting controller, then do
editCustomerController.populateEditCustomerFields(selectedCustomerID);
on table row double click.
Further to improve performance, you can load the edit_customer.fxml only once and when the user double clicks, refresh its rendered data with editCustomerController.populateEditCustomerFields(selectedCustomerID).

Unable to catch STException in StringTemplate 4

I am unable to catch the STException thrown by the STGroupFile. This is a problem. I need to abort if the template is bad. To reproduce this problem, I have this incorrect template file called tmp.stg:
temp1(param1)::=<<
%if(param1)%
%param1:{%temp2(p)%}; separator"\n"%
%endif%
>>
And this groovy code to process it:
#!/usr/bin/env groovy
#Grab(group="org.antlr", module="ST4", version="4.0.8")
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.NumberRenderer;
public class Gex {
public static void main(String [] args) {
System.out.println("Processing...")
File fn = new File("tmp.stg")
STGroupFile group;
try {
group = new STGroupFile(fn.toString());
} catch (Throwable e) {
throw new Exception("Caught first exception");
}
try {
group.registerRenderer(Integer.class, new NumberRenderer());
} catch (Throwable e) {
throw new Exception("Caught second exception");
}
throw new Exception("You should not see this");
}
}
Gex.main()
When I run that script, I get an error message but I cannot catch the exception:
can't load group file file:tmp.stg
The error message comes from STGroupFile.java:
throw new STException("can't load group file "+fileName, e);
But I am unable to catch this exception. How can I catch this exception and abort?
Following the advice of The ANTLR Guy, I extended the STErrorListener to throw an exception instead of printing a message to stderr. It looks like this:
File: lib/GexListener.groovy
import org.stringtemplate.v4.STErrorListener;
import org.stringtemplate.v4.misc.STMessage;
import org.stringtemplate.v4.misc.ErrorType;
class GexListener implements STErrorListener {
#Override
public void compileTimeError(STMessage msg) {
throw new Exception(msg.toString());
}
#Override
public void runTimeError(STMessage msg) {
if ( msg.error != ErrorType.NO_SUCH_PROPERTY ) { // ignore these
throw new Exception(msg.toString());
}
}
#Override
public void IOError(STMessage msg) {
throw new Exception(msg.toString());
}
#Override
public void internalError(STMessage msg) {
throw new Exception(msg.toString());
}
public void error(String s) { error(s, null); }
public void error(String s, Throwable e) {
System.err.println(s);
if ( e!=null ) {
throw new Exception(msg.toString());
}
}
}
Then the master script bin/gex.groovy looks like this:
#!/bin/bash
//usr/bin/env groovy -cp ${0%/*}/../lib "$0" "$#"; exit $?
#Grab(group="org.antlr", module="ST4", version="4.0.8")
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.NumberRenderer;
import GexListener
public class Gex {
public static void main(String [] args) {
System.out.println("Processing...")
File fn = new File("tmp.stg")
STGroupFile group;
GexListener listener = new GexListener();
group = new STGroupFile(fn.toString());
group.setListener(listener);
group.registerRenderer(Integer.class, new NumberRenderer());
System.out.println("You should not see this line")
}
}
Gex.main()
When it executes, there is a nasty side effect where the stacktrace is printed twice, but the program aborts before printing the last sentence "You should not see this line", which is the desired behaviour.
As you pointed out in a separate email: "I discovered that the exception is actually caught and not re-thrown. This happens inside STGroup.java:"
catch (Exception e) {
errMgr.IOError(null, ErrorType.CANT_LOAD_GROUP_FILE, e, fileName);
}
Why not override the IOError function (or a function in the listener that it calls?) to just re-throw e?

Show previous instance of RCP application

I had an rcp application which runs for only first run, when a user attempts to re-execute the application, second instance behaves as a client which encodes and sends its arguments over the socket to the first instance which acts as a server and then exits silently. The first instance receives and decodes that message, then behaves as if it had been invoked with those arguments.
so far so good i made internal protocol specification for passing arguments between two instances.
I could not bring the first instance(RCP application) to front. It is in minimized state only,
this is in continuation to my previous question
the change i made to previous post is start method of application class
public Object start(IApplicationContext context) throws Exception {
if (!ApplicationInstanceManager.registerInstance()) {
return IApplication.EXIT_OK;
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
System.out.println("New instance detected...");
//Display.getCurrent().getActiveShell()
.forceActive();// this gives null
// pointer exception
// hence commented
}
});
}
});
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display,
new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART)
return IApplication.EXIT_RESTART;
else
return IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
below line is stopping me to bring Application to front
Display.getCurrent().getActiveShell().forceActive();
generates null pointer exception at getActiveShell()
how can i maximize the previous instance or bring it to front
I wrote an instance manager to restrict my RCP to a single instance.
Here's the code that goes in Application.java, in the start method:
if (!ApplicationInstanceManager.registerInstance()) {
return IApplication.EXIT_OK;
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (DEBUG)
System.out.println("New instance detected...");
Display.getCurrent().getActiveShell().forceActive();
}
});
}
});
Here's the listener interface:
public interface ApplicationInstanceListener {
public void newInstanceCreated();
}
And here's the Manager class:
public class ApplicationInstanceManager {
private static final boolean DEBUG = true;
private static ApplicationInstanceListener subListener;
/** Randomly chosen, but static, high socket number */
public static final int SINGLE_INSTANCE_NETWORK_SOCKET = 44331;
/** Must end with newline */
public static final String SINGLE_INSTANCE_SHARED_KEY = "$$RabidNewInstance$$\n";
/**
* Registers this instance of the application.
*
* #return true if first instance, false if not.
*/
public static boolean registerInstance() {
// returnValueOnError should be true if lenient (allows app to run on
// network error) or false if strict.
boolean returnValueOnError = true;
// try to open network socket
// if success, listen to socket for new instance message, return true
// if unable to open, connect to existing and send new instance message,
// return false
try {
final ServerSocket socket = new ServerSocket(
SINGLE_INSTANCE_NETWORK_SOCKET, 10, InetAddress
.getLocalHost());
if (DEBUG)
System.out
.println("Listening for application instances on socket "
+ SINGLE_INSTANCE_NETWORK_SOCKET);
Thread instanceListenerThread = new InstanceListenerThread(socket);
instanceListenerThread.start();
// listen
} catch (UnknownHostException e) {
EclipseLogging.logError(RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID, e);
return returnValueOnError;
} catch (IOException e) {
return portTaken(returnValueOnError, e);
}
return true;
}
private static boolean portTaken(boolean returnValueOnError, IOException e) {
if (DEBUG)
System.out.println("Port is already taken. "
+ "Notifying first instance.");
try {
Socket clientSocket = new Socket(InetAddress.getLocalHost(),
SINGLE_INSTANCE_NETWORK_SOCKET);
OutputStream out = clientSocket.getOutputStream();
out.write(SINGLE_INSTANCE_SHARED_KEY.getBytes());
out.close();
clientSocket.close();
System.out.println("Successfully notified first instance.");
return false;
} catch (UnknownHostException e1) {
EclipseLogging.logError(RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID, e);
return returnValueOnError;
} catch (IOException e1) {
EclipseLogging
.logError(
RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID,
"Error connecting to local port for single instance notification",
e);
return returnValueOnError;
}
}
public static void setApplicationInstanceListener(
ApplicationInstanceListener listener) {
subListener = listener;
}
private static void fireNewInstance() {
if (subListener != null) {
subListener.newInstanceCreated();
}
}
public static void main(String[] args) {
if (!ApplicationInstanceManager.registerInstance()) {
// instance already running.
System.out.println("Another instance of this application "
+ "is already running. Exiting.");
System.exit(0);
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
System.out.println("New instance detected...");
// this is where your handler code goes...
}
});
}
public static class InstanceListenerThread extends Thread {
private ServerSocket socket;
public InstanceListenerThread(ServerSocket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean socketClosed = false;
while (!socketClosed) {
if (socket.isClosed()) {
socketClosed = true;
} else {
try {
Socket client = socket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String message = in.readLine();
if (SINGLE_INSTANCE_SHARED_KEY.trim().equals(
message.trim())) {
if (DEBUG)
System.out.println("Shared key matched - "
+ "new application instance found");
fireNewInstance();
}
in.close();
client.close();
} catch (IOException e) {
socketClosed = true;
}
}
}
}
}
}
After your IApplication start up, you can also check and lock the OSGi instance location using org.eclipse.osgi.service.datalocation.Location.isSet() and org.eclipse.osgi.service.datalocation.Location.lock()
The location is usually retrieved from your Activator using code like:
public Location getInstanceLocation() {
if (locationTracker == null) {
Filter filter = null;
try {
filter = context.createFilter(Location.INSTANCE_FILTER);
} catch (InvalidSyntaxException e) {
// ignore this. It should never happen as we have tested the
// above format.
}
locationTracker = new ServiceTracker(context, filter, null);
locationTracker.open();
}
return (Location) locationTracker.getService();
}