Could you please help me to solve my problem with GWT Generator? Let me explain.
I wish to generate a widget (ListBox with pre-defined values) during the compilation time and I use GWT Generator for that. My solution works as expected in DevMode (when I run the project with mvn gwt:run) and I see the generated listbox on the screen. But when I compile the code and run it in the "Production mode" (using command mvn clean gwt:compile jetty:run-war) I see the dumb listbox with only one item "no-value" instead.
I have one idea about the issue reason. I use GIN in my project. Despite the fact, that I substitute my empty listbox with generated one using Deferred Binding but not GIN Injection, it probably somehow prevents the substitution during the runtime. I tried my listbox on an empty testing project - everything worked as desired in both Dev Mode and Production Mode. But it fails on my working project.
Here is my realisation:
package com.test.generated;
import com.google.gwt.user.client.ui.IsWidget;
public interface IMySelectBox extends IsWidget {}
My empty selectbox:
package com.test.generated;
import com.google.gwt.user.client.ui.ListBox;
/**
* <p>Dumb listbox. It should be replaced with generated file.</p>
*
*/
public class MySelectBox implements IMySelectBox {
#Override
public ListBox asWidget() {
ListBox listBox = new ListBox();
listBox.addItem("no-value","no-value");
return listBox;
}
}
My Generator:
package com.test.generated;
import java.io.PrintWriter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
/**
* Generates the ListBox and populates it
*
*/
public class SelectBoxGenerator extends Generator {
/**
* {#inheritDoc}
*/
#Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
try {
JClassType classType = context.getTypeOracle().getType(typeName);
return this.getSourceWriter(classType, context, logger);
} catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* Generates the source code of the List box.
*/
private String getSourceWriter(JClassType classType, GeneratorContext context, TreeLogger logger) {
final String packageName = classType.getPackage().getName();
final String className = classType.getSimpleSourceName() + "GeneratedImpl";
PrintWriter printWriter = context.tryCreate(logger, packageName, className);
if (printWriter == null) {
// source code has already been generated, abort
return null;
}
ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
// Extends
composer.setSuperclass(classType.getName());
// Implements interface IMySelectBox
composer.addImplementedInterface(IMySelectBox.class.getSimpleName());
// Imports
composer.addImport(ListBox.class.getName());
// Class body
SourceWriter src = composer.createSourceWriter(context, printWriter);
src.println("#Override");
src.println("public ListBox asWidget() {");
src.println("ListBox sb = new ListBox();");
// ...here I generate values for the selectbox during compilation time.
src.println("return sb;");
src.println("}");
src.commit(logger);
System.out.println("Generating for: " + className);
// return the fully qualifed name of the generated class
return packageName + "." + className;
}
}
This is how I declare the substitution in my module.gwt.xml file:
<generate-with class="com.test.generated.SelectBoxGenerator">
<when-type-assignable class="com.test.generated.IMySelectBox" />
</generate-with>
And I use my generated ListBox as usually:
IMySelectBox mySelectBox = GWT.create(MySelectBox.class);
anyPanel.add(mySelectBox);
As you can see, I don't touch GIN stuff here at all. I use GIN to inject my modules and views. I found Issue 95 in GIN website, probably it is related to my case.
I will be really glad to get any help. Any explanations, hints, workarounds, suggestions are welcome!
Thank you very much in advance!
Related
I'm using a MenuContribution to feed a menu entry, implementing a feature like the "switch workspace" in E3.
In a dynamic menu contribution, i'm building a 3 item list of most recent opened projects followed by the "Other.." entry.
graphically, i'm done, the 3 list, separator and "other.." menu elements are showing up.
But in the case of most recent project, i have to dynamically pass the project name/Path to the handler which consume the selection event.
below is a code similar to what i have in the menu contribution that creates one of the 3 recent project item :
#AboutToShow
public void aboutToShow(List<MMenuElement> items, MApplication application) {
MHandledMenuItem dynamicItem = modelService.createModelElement(MHandledMenuItem.class);
dynamicItem.setLabel(projectName);
dynamicItem.setContributorURI("platform:/plugin/com.acme");
MCommand command = modelService.createModelElement(MCommand.class);
command.setElementId(LOAD_PROJECT_COMMAND_ID);
MCommandParameter commandParam = modelService.createModelElement(MCommandParameter.class);
commandParam.setElementId(PROJECT_NAME_PARAMETER_ID);
commandParam.setName(PROJECT_NAME_PARAMETER_ID);
command.getParameters().add(commandParam);
// one of the 3 last used projects
String projectName = "foo";
dynamicItem.setCommand(command);
items.add(dynamicItem);
}
where LOAD_PROJECT_COMMAND_ID and PROJECT_NAME_PARAMETER_ID are e4xmi command and command parameter id.
I wonder how i can put projectName in the command to be able to get it back in the associated handler, which contains something like :
#Execute
public void execute(ParameterizedCommand command) {
[...]
}
Note : I read Lars tutorial about menus but did not found solution in there
--- EDIT : full contribution code ---
import java.util.Collections;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.e4.core.commands.ECommandService;
import org.eclipse.e4.ui.di.AboutToShow;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.commands.MCommand;
import org.eclipse.e4.ui.model.application.commands.MParameter;
import org.eclipse.e4.ui.model.application.ui.menu.MDirectMenuItem;
import org.eclipse.e4.ui.model.application.ui.menu.MHandledMenuItem;
import org.eclipse.e4.ui.model.application.ui.menu.MMenuElement;
import org.eclipse.e4.ui.model.application.ui.menu.MMenuSeparator;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import com.acme.model.platypus.extractionresult.CampaignResultProvider;
#SuppressWarnings("restriction")
public class SwitchProjectMenuContribution {
private static final String NEW_PROJECT = "Other...";
private static final String LOAD_PROJECT_COMMAND_ID = "gui.rcp4.command.loadProjectCommand";
private static final String PROJECT_NAME_PARAMETER_ID = "gui.rcp4.command.loadProjectCommand.projectName";
#Inject
CampaignResultProvider campaignResultProvider;
#Inject
private EModelService modelService;
#Inject
ECommandService commandService;
private MDirectMenuItem otherProjectItem;
private MMenuSeparator separatorItem;
private MCommand loadProjectCommand;
#SuppressWarnings("unchecked")
#PostConstruct
public void initialize(MApplication application) {
loadProjectCommand = (MCommand) modelService
.findElements(application, LOAD_PROJECT_COMMAND_ID, MCommand.class, Collections.EMPTY_LIST).get(0);
otherProjectItem = modelService.createModelElement(MDirectMenuItem.class);
otherProjectItem.setLabel(NEW_PROJECT);
otherProjectItem.setContributorURI("platform:/plugin/com.acme.gui.rcp4");
otherProjectItem.setContributionURI(
"bundleclass://com.acme.gui.rcp4/com.acme.gui.rcp4.handlers.OtherProjecthandler");
separatorItem = modelService.createModelElement(MMenuSeparator.class);
}
#AboutToShow
public void aboutToShow(List<MMenuElement> items, MApplication application) {
String[] lastProject = campaignResultProvider.getLastUsed();
MMenuElement newEntry;
for (String projectName : lastProject) {
newEntry = createExistingProjectEntry(projectName);
items.add(newEntry);
}
if (lastProject.length > 0) {
items.add(separatorItem);
}
items.add(otherProjectItem);
}
private MHandledMenuItem createExistingProjectEntry(String projectPath) {
MHandledMenuItem dynamicItem = modelService.createModelElement(MHandledMenuItem.class);
dynamicItem.setLabel(projectPath);
dynamicItem.setContributorURI("platform:/plugin/com.acme.gui.rcp4");
MParameter commandParam = modelService.createModelElement(MParameter.class);
commandParam.setName("projectName");
commandParam.setElementId(PROJECT_NAME_PARAMETER_ID);
commandParam.setValue(projectPath);
dynamicItem.getParameters().add(commandParam);
dynamicItem.setCommand(loadProjectCommand);
return dynamicItem;
}
}
You add the parameter value to the MHandledMenuItem not the command.
Use a MParameter and call the setName and setValue methods to set the name (must match the parameter name in the command) and value (the project name in your case).
Add the MParameter to the MHandledMenuItem.getParameters() list.
Note: You should only define the command and command parameter once, not every time aboutToShow is called (so that should probably be in the e4xmi file).
I want to create my own SonarQube Plugin for the RPG language. I have the following problem.
I start by created the RpgLanguage class that extends to AbstractLanguage. In this class, I defined my new language "Rpg". You can see my class in the following code :
public class RpgLanguage extends AbstractLanguage{
public static final String KEY = "rpg";
private Settings settings;
public RpgLanguage(Settings settings) {
super(KEY, "Rpg");
this.settings = settings;
}
public String[] getFileSuffixes() {
String[] suffixes = settings.getStringArray("");
if (suffixes == null || suffixes.length == 0) {
suffixes = StringUtils.split(".RPG", ",");
}
return suffixes;
}
}
After, I have created my RpgRulesDefinition class that implements RulesDefinition. In this class, I create a new repository for the language RPG and I want to add a rule in this repository (empty rules). The code is like below :
public static final String REPOSITORY_KEY = "rpg_repository_mkoza";
public void define(Context context) {
NewRepository repo = context.createRepository(REPOSITORY_KEY, "rpg");
repo.setName("Mkoza Analyser rules RPG");
// We could use a XML or JSON file to load all rule metadata, but
// we prefer use annotations in order to have all information in a single place
RulesDefinitionAnnotationLoader annotationLoader = new RulesDefinitionAnnotationLoader();
annotationLoader.load(repo, RpgFileCheckRegistrar.checkClasses());
repo.done();
}
My class RpgFileCheckRegistrar that call my Rules :
/**
* Register the classes that will be used to instantiate checks during analysis.
*/
public void register(RegistrarContext registrarContext) {
// Call to registerClassesForRepository to associate the classes with the correct repository key
registrarContext.registerClassesForRepository(RpgRulesDefinition.REPOSITORY_KEY, Arrays.asList(checkClasses()), Arrays.asList(testCheckClasses()));
}
/**
* Lists all the checks provided by the plugin
*/
public static Class<? extends JavaCheck>[] checkClasses() {
return new Class[] {
RulesExampleCheck.class
};
}
/**
* Lists all the test checks provided by the plugin
*/
public static Class<? extends JavaCheck>[] testCheckClasses() {
return new Class[] {};
}
My Rule class (still empty):
#Rule(
key = "Rule1",
name = "Rule that make nothing",
priority = Priority.MAJOR,
tags = {"example"}
)
public class RulesExampleCheck extends BaseTreeVisitor{
/**
* Right in java code your rule
*/
}
And the class SonarPlugin that call all these extensions :
public final class RpgSonarPlugin extends SonarPlugin
{
// This is where you're going to declare all your Sonar extensions
public List getExtensions() {
return Arrays.asList(
RpgLanguage.class,
RpgRulesDefinition.class,
RpgFileCheckRegistrar.class
);
}
}
The problem when I want to start the server sonar, I obtain this error stack :
Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener
java.lang.IllegalStateException: One of HTML description or Markdown description must be defined for rule [repository=rpg_repository_mkoza, key=Rule1]
I try different things but I don't understand why there are these error.
Of course I want that my repository "rpg_repository_mkoza" is display in the RPG's repository in SonarQube with the Rules : RulesExampleCheck.
My sonar-plugin-version is the 3.7.1
I find my problem. There are need to add the field 'description' in #Rule.
For example :
#Rule(
key = "Rule1",
name = "RuleExampleCheck",
description = "This rule do nothing",
priority = Priority.INFO,
tags = {"try"}
)
I have been successful in making a plugin. However now i need that on project creation page i add some more textboxes to get the user information. Also i need to use this information to add into the auto generated .php files made in project directory.
I want to know how can i override the WizardNewProjectCreationPage to add some more textboxes to the already given layout. I am pretty new to plugin development. Here is the code for my custom wizard.
import java.net.URI;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;
import rudraxplugin.pages.MyPageOne;
import rudraxplugin.projects.RudraxSupport;
public class CustomProjectNewWizard extends Wizard implements INewWizard, IExecutableExtension {
private WizardNewProjectCreationPage _pageOne;
protected MyPageOne one;
private IConfigurationElement _configurationElement;
public CustomProjectNewWizard() {
// TODO Auto-generated constructor stub
setWindowTitle("RudraX");
}
#Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
// TODO Auto-generated method stub
}
#Override
public void addPages() {
super.addPages();
_pageOne = new WizardNewProjectCreationPage("From Scratch Project Wizard");
_pageOne.setTitle("From Scratch Project");
_pageOne.setDescription("Create something from scratch.");
addPage(one);
addPage(_pageOne);
}
#Override
public boolean performFinish() {
String name = _pageOne.getProjectName();
URI location = null;
if (!_pageOne.useDefaults()) {
location = _pageOne.getLocationURI();
System.err.println("location: " + location.toString()); //$NON-NLS-1$
} // else location == null
RudraxSupport.createProject(name, location);
// Add this
BasicNewProjectResourceWizard.updatePerspective(_configurationElement);
return true;
}
#Override
public void setInitializationData(IConfigurationElement config,
String propertyName, Object data) throws CoreException {
_configurationElement = config;
// TODO Auto-generated method stub
}
}
Ask for any other code required. Any help is appreciated. Thank You.
Instead of using WizardNewProjectCreationPage directly create a new class extending WizardNewProjectCreationPage and override the createControl method to create new controls:
class MyNewProjectCreationPage extends WizardNewProjectCreationPage
{
#Override
public void createControl(Composite parent)
{
super.createControl(parent);
Composite body = (Composite)getControl();
... create new controls here
}
}
I am looking to read xls file using the gwt RPC and when I am using the code which excecuted fine in normal file it is unable to load the file and giving me null pointer exception.
Following is the code
{
{
import com.arosys.readExcel.ReadXLSX;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.Preview.client.GWTReadXL;
import java.io.InputStream;
import com.arosys.customexception.FileNotFoundException;
import com.arosys.logger.LoggerFactory;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author Amandeep
*/
public class GWTReadXLImpl extends RemoteServiceServlet implements GWTReadXL
{
private String fileName;
private String[] Header=null;
private String[] RowData=null;
private int sheetindex;
private String sheetname;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private static Logger logger=null;
public void loadXlsxFile() throws Exception
{
logger.info("inside loadxlsxfile:::"+fileName);
InputStream resourceAsStream =ClassLoader.getSystemClassLoader().getSystemResourceAsStream("c:\\test2.xlsx");
logger.info("resourceAsStream-"+resourceAsStream);
if(resourceAsStream==null)
throw new FileNotFoundException("unable to locate give file");
else
{
try
{
workbook = new XSSFWorkbook(resourceAsStream);
sheet = workbook.getSheetAt(sheetindex);
}
catch (Exception ex)
{
logger.error(ex.getMessage());
}
}
}// end loadxlsxFile
public String getNumberOfColumns() throws Exception
{
int NO_OF_Column=0; XSSFCell cell = null;
loadXlsxFile();
Iterator rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator cellIter = firstRow.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
return NO_OF_Column+"";
}
}
}
I am calling it in client program by this code:
final AsyncCallback<String> callback1 = new AsyncCallback<String>() {
public void onSuccess(String result) {
RootPanel.get().add(new Label("In success"));
if(result==null)
{
RootPanel.get().add(new Label("result is null"));
}
RootPanel.get().add(new Label("result is"+result));
}
public void onFailure(Throwable caught) {
RootPanel.get().add(new Label("In Failure"+caught));
}
};
try{
getService().getNumberOfColumns(callback1);
}catch(Exception e){}
}
Pls tell me how can I resolve this issue as the code runs fine when run through the normal java file.
Why are using using the system classloader, rather than the normal one?
But, If you still want to use then look at this..
As you are using like a web application. In that case, you need to use the ClassLoader which is obtained as follows:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
This one has access to the all classpath paths tied to the webapplication in question and you're not anymore dependent on which parent classloader (a webapp has more than one!) has loaded your class.
Then, on this classloader, you need to just call getResourceAsStream() to get a classpath resource as stream, not the getSystemResourceAsStream() which is dependent on how the webapplication is started. You don't want to be dependent on that as well since you have no control over it at external hosting:
InputStream input = classLoader.getResourceAsStream("filename.extension");
The location of file should in your CLASSPATH.
I'm developing a javadesktop application in Netbeans 6.9 and everything is perfect but...it gives me an error on this :
#Action
public void showAboutBox()
{
if (aboutBox == null) {
JFrame mainFrame = Mp4App.getApplication().getMainFrame();
aboutBox = new mp4AboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
and this is the error :
Compiling 1 source file to Q:\Mp3 App\mp4-beta\mp4\build\classes
Q:\Mp3 App\mp4-beta\mp4\src\mp4\Mp4View.java:223: cannot find symbol
symbol : class mp4AboutBox
location: class mp4.Mp4View
aboutBox = new mp4AboutBox(mainFrame);
1 error
Q:\Mp3 App\mp4-beta\mp4\nbproject\build-impl.xml:603:
The following error occurred while executing this line:
Q:\Mp3 App\mp4-beta\mp4\nbproject\build-impl.xml:284: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 8 seconds)
the real problem is that this is the code generated from netbeans...also if you create a new Project->java->Destop Application and you leave it there without adding nothing,it gives always me the same problem... what to do ????????????
netbeans version: 6.9.1
jdk version: 7
O.S : Windows 7 32 bit
You shouldn't create your GUI using Netbeans because it generates unreadable code. The Swing-Package is pretty straight forward, so you should use it.
To the Error: Do you have a mp4AboutBox-class and what is in it?
You might be missing an import. Provide your imports in that file.
I had a similar question that I got the solution to by re-installing netbeans 6.9.1.
This is the solution I came up with from that:
TestProject class:
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
public class TestProject extends SingleFrameApplication {
#Override protected void startup() {
show(new AppView(this));
}
#Override protected void configureWindow(java.awt.Window root) { }
public static TestProject getApplication() {
return Application.getInstance(TestProject.class);
}
public static void main(String[] args) {
launch(TestProject.class, args);
}
}
AppView JFrame:
import org.jdesktop.application.FrameView;
import org.jdesktop.application.SingleFrameApplication;
public class AppView extends FrameView {
public AppView(SingleFrameApplication app) {
super(app);
JFrame mainFrame = TestProject.getApplication().getMainFrame();
AboutBox newAboutBox = new AboutBox();
newAboutBox.setLocationRelativeTo(mainFrame);
TestProject.getApplication().show(newAboutBox);
}
}