(Eclipse) Syntax Highlighting Plugin, odd issues with getting started on highlighting/validation - eclipse

I'm making a syntax highlighting plugin for my company. I'm not making a new editor, I am using an eclipse template that uses the Extensions for generic editor.
Disclaimer: I've had a lot of trouble getting XText to work consistently on 3 different machines due to versioning issues, missing files etc. so that's out of the question
org.eclipse.ui.genericeditor.presentationReconcilers
org.eclipse.ui.genericeditor.contentTypes
org.eclipse.ui.genericeditor.hoverProviders
org.eclipse.ui.genericeditor.contentAssistProcessors
org.eclipse.ui.editors
org.eclipse.core.filebuffers.documentSetup
I'm using I'm having some odd issues. Before I get started:
The plugin is detected in Help > About Eclipse > Installation Details > Plugins
Other sample plugins run using the same method i used to run this plugin
Problems:
I'm getting the following error message when placing any content in
the file except <?xml version='1.0'>:
"Content is not allowed in Prolog"
The keywords seem to be highlighted in Blue. As you can see in my
source code, they should be highlighted in red.
Click here to view what my runtime Eclipe editor looks like
when i'm trying to test my syntax rules.
Below are my classes source code.
I'm wondering:
why my keywords are being recognized in syntax coloring but are
invalid commands with that "prolog" error above
Why the prolog errors above are occurring
Why it's validating the file not to my specification or to a different specification
Point me in the right direction
Hope you can help.
Thanks :).
Reconciler Class:
package myplugin;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
public class MyReconciler extends PresentationReconciler {
public MyReconciler() {
// TODO this is logic for .project file to color tags in blue. Replace with your language logic!
MyScanner scanner = new MyScanner(new SyntaxColorProvider());
DefaultDamagerRepairer dr= new DefaultDamagerRepairer(scanner);
this.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
this.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
}
}
Scanner class:
package myplugin;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.rules.BufferedRuleBasedScanner;
import org.eclipse.jface.text.rules.EndOfLineRule;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.IWordDetector;
import org.eclipse.jface.text.rules.MultiLineRule;
import org.eclipse.jface.text.rules.PatternRule;
import org.eclipse.jface.text.rules.SingleLineRule;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WhitespaceRule;
import org.eclipse.jface.text.rules.WordRule;
public class MyScanner extends BufferedRuleBasedScanner
{
private static String[] misc = {
true",
"false",
"unsigned",
"jump",
"read",
"write",
};
// Tokens
private final IToken KEYWORD_TOKEN;
private List<IRule> basicRules;
public MyScanner(SyntaxColorProvider colorProvider)
{
super(5000);
// CREATE TOKENS
KEYWORD_TOKEN = new Token(new TextAttribute(colorProvider.getColor(SyntaxColorProvider.KEYWORD)));
// CREATE RULES
List rules = new ArrayList<IRule>();
// Add rule for strings and character constants.
rules.add(new SingleLineRule("\"", "\"", STRING_TOKEN, '\\'));
rules.add(new SingleLineRule("'", "'", STRING_TOKEN, '\\'));
// Add word rule for keywords, types, and constants.
WordRule wordRule = new WordRule(new WordDetector(), OTHER_TOKEN);
// Single-line comments
rules.add(new EndOfLineRule("//", STRING_TOKEN));
// Multi-line comments
rules.add(new MultiLineRule("/$", "$/", COMMENT_TOKEN));
// KEYWORDS
for (String misc : misc)
{
wordRule.addWord(misc, KEYWORD_TOKEN);
}
rules.add(wordRule);
IRule[] result= new IRule[rules.size()];
rules.toArray(result);
setRules(result);
}
}
ValidatorDocumentSetupParticipant:
package myplugin;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
import org.eclipse.core.filebuffers.IDocumentSetupParticipantExtension;
import org.eclipse.core.filebuffers.LocationKind;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
public class ValidatorDocumentSetupParticipant implements IDocumentSetupParticipant, IDocumentSetupParticipantExtension {
private final class DocumentValidator implements IDocumentListener {
private final IFile file;
private IMarker marker;
private DocumentValidator(IFile file) {
this.file = file;
}
#Override
public void documentChanged(DocumentEvent event) {
if (this.marker != null) {
try {
this.marker.delete();
} catch (CoreException e) {
e.printStackTrace();
}
this.marker = null;
}
try (StringReader reader = new StringReader(event.getDocument().get());) {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
documentBuilder.parse(new InputSource(reader));
} catch (Exception ex) {
try {
this.marker = file.createMarker(IMarker.PROBLEM);
this.marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
this.marker.setAttribute(IMarker.MESSAGE, ex.getMessage());
if (ex instanceof SAXParseException) {
SAXParseException saxParseException = (SAXParseException)ex;
int lineNumber = saxParseException.getLineNumber();
int offset = event.getDocument().getLineInformation(lineNumber - 1).getOffset() + saxParseException.getColumnNumber() - 1;
this.marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
this.marker.setAttribute(IMarker.CHAR_START, offset);
this.marker.setAttribute(IMarker.CHAR_END, offset + 1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void documentAboutToBeChanged(DocumentEvent event) {
}
}
#Override
public void setup(IDocument document) {
}
#Override
public void setup(IDocument document, IPath location, LocationKind locationKind) {
if (locationKind == LocationKind.IFILE) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(location);
document.addDocumentListener(new DocumentValidator(file));
}
WordDetector Class:
package myplugin;
import org.eclipse.jface.text.rules.IWordDetector;
public class WordDetector implements IWordDetector
{
public boolean isWordPart(char character) {
return Character.isJavaIdentifierPart(character);
}
public boolean isWordStart(char character) {
return Character.isJavaIdentifierStart(character);
}
}
SyntaxColorProvider Class:
package myplugin;
import java.util.HashMap;
public class SyntaxColorProvider
{
public static final RGB RED = new RGB(200, 0, 0);
public static final RGB GREEN = new RGB(0, 200, 0);
public static final RGB BLUE = new RGB(0, 0, 200);
public static final RGB COMMENT = new RGB(128, 128, 128);
public static final RGB KEYWORD = new RGB(255, 0, 0);
public static final RGB TYPE = new RGB(0, 0, 128);
public static final RGB STRING = new RGB(0, 128, 0);
public static final RGB DEFAULT = new RGB(0, 0, 0);
protected Map fColorTable = new HashMap(10);
/**
* Release all of the color resources held onto by the receiver.
*/
public void dispose()
{
Iterator e = fColorTable.values().iterator();
while (e.hasNext())
((Color) e.next()).dispose();
}
/**
* Return the Color that is stored in the Color table as rgb.
*/
public Color getColor(RGB rgb)
{
Color color = (Color) fColorTable.get(rgb);
if (color == null)
{
color = new Color(Display.getCurrent(), rgb);
fColorTable.put(rgb, color);
}
return color;
}

This looks like the sample editor with some changes - and
documentBuilder.parse(new InputSource(reader));
would be parsing XML, perhaps. It detects improper XML because the prolog is missing. Remove that line from the code, or implement something that flags up and marks issues similarly.

Ok so I've struggled with the same probelm the function that makes this problem is in this line: documentBuilder.parse(new InputSource(reader));, Im in the middle of trying to figure out a text parser by myself.

Related

Eclipse OverviewRuler not showing annotations

I created a SourceViewer as described in this link https://wiki.eclipse.org/Platform_Text
I could not get the annotation indications on the right side of the editor.
I am trying out this in a view instead of an editor.
I tried calling overViewRuler.addAnnotationType("My annotation type"); and also called the overViewRuler.update(); Nothing seems to work. Is there any way to show the marks on the right side overview ruler of a source viewer in a view?
I have found the answer.
The problem was
overviewRulerPreferenceValue="true"
was missing in the plugin.xml. I am giving the complete code below in case any one wants to try.
package sourceviewsample;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModel;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
/**
* An example of using a SourceViewer with Annotation support outside of the
* TextEditor class. This annotations can be configured in the preferences if
* the markerAnnotationSpecification is setup in the plugin.xml.
*
* To execute this, run as an Eclipse Application and then open a file using
* Open with.. -> Other, and select Sample Editor. You will see the text that
* comes in this example and the highlight.
*/
public class SampleEditor extends ViewPart
{
public static final String ANNO_TYPE = "com.mycompany.element";
public static final String ANNO_KEY_HIGHLIGHT = "annotateElemHighlight";
public static final String ANNO_KEY_OVERVIEW = "annotateElemOverviewRuler";
public static final String ANNO_KEY_VERTICAL = "annotateElemVertialRuler";
public static final String ANNO_KEY_TEXT = "annotateElemText";
public static final String ANNO_KEY_COLOR = "annotateElemColor";
protected SourceViewer _sourceViewer;
protected SourceViewerDecorationSupport _sds;
protected IDocument _document;
protected AnnotationModel _annotationModel;
protected String _docString = "this\nis\na\ntest\ndocument";
public SampleEditor()
{
super();
}
public void createPartControl(Composite parent)
{
int VERTICAL_RULER_WIDTH = 12;
int styles = SWT.V_SCROLL
| SWT.H_SCROLL
| SWT.MULTI
| SWT.BORDER
| SWT.FULL_SELECTION;
ISharedTextColors sharedColors = EditorsPlugin.getDefault()
.getSharedTextColors();
IAnnotationAccess iaccess = new IAnnotationAccess() {
#Override
public boolean isTemporary(Annotation annotation) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isMultiLine(Annotation annotation) {
// TODO Auto-generated method stub
return false;
}
#Override
public Object getType(Annotation annotation) {
// TODO Auto-generated method stub
return ANNO_TYPE;
}
};
IOverviewRuler overviewRuler = new OverviewRuler(iaccess,
VERTICAL_RULER_WIDTH,
sharedColors);
CompositeRuler ruler = new CompositeRuler(VERTICAL_RULER_WIDTH);
_document = new Document();
_document.set(_docString);
_annotationModel = new AnnotationModel();
_annotationModel.connect(_document);
_sourceViewer = new SourceViewer(parent,
ruler,
overviewRuler,
true,
styles);
_sourceViewer.configure(new SourceViewerConfiguration());
_sds = new SourceViewerDecorationSupport(_sourceViewer,
overviewRuler,
null,
sharedColors);
AnnotationPreference ap = new AnnotationPreference();
ap.setColorPreferenceKey(ANNO_KEY_COLOR);
ap.setColorPreferenceValue(new RGB(150, 200, 250));
ap.setHighlightPreferenceKey(ANNO_KEY_HIGHLIGHT);
ap.setVerticalRulerPreferenceKey(ANNO_KEY_VERTICAL);
ap.setOverviewRulerPreferenceKey(ANNO_KEY_OVERVIEW);
ap.setOverviewRulerPreferenceValue(true);
ap.setTextPreferenceKey(ANNO_KEY_TEXT);
ap.setAnnotationType(ANNO_TYPE);
_sds.setAnnotationPreference(ap);
_sds.install(EditorsPlugin.getDefault().getPreferenceStore());
_sourceViewer.setDocument(_document, _annotationModel);
_sourceViewer.getControl().setLayoutData(new GridData(SWT.FILL,
SWT.FILL,
true,
true));
ruler.addDecorator(0, new LineNumberRulerColumn());
overviewRuler.addAnnotationType(ANNO_TYPE);
overviewRuler.getControl().setBackground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK));
Annotation annotation = new Annotation(false);
annotation.setType(ANNO_TYPE);
Position position = new Position(0, 4);
_annotationModel.addAnnotation(annotation, position);
try {
_document.addPosition(position);
} catch (BadLocationException e) {
e.printStackTrace();
}
overviewRuler.setModel(_annotationModel);
}
public void dispose()
{
// The _sourceViewer goes away automatically when the editor goes
// away because it's hooked to the controls
_sds.dispose();
}
//
// This stuff below is just needed to make the EditorPart happy
//
public void doSave(IProgressMonitor monitor)
{
}
public void doSaveAs()
{
}
// public void init(IEditorSite site, IEditorInput input)
// throws PartInitException
// {
// setSite(site);
// setInput(input);
// }
//
// public boolean isDirty()
// {
// return false;
// }
public boolean isSaveAsAllowed()
{
return false;
}
public void setFocus()
{
}
}
Here is the plugin.xml as well
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
<extension
point="org.eclipse.ui.editors.annotationTypes">
<type
markerSeverity="0"
name="com.mycompany.element">
</type>
</extension>
<extension
point="org.eclipse.ui.editors.markerAnnotationSpecification">
<specification
annotationType="com.mycompany.element"
colorPreferenceKey="annotateElemColor"
colorPreferenceValue="255,255,0"
highlightPreferenceKey="annotateElemHighlight"
highlightPreferenceValue="true"
includeOnPreferencePage="true"
label="Sample Annotation"
overviewRulerPreferenceKey="annotateElemOverviewRuler"
overviewRulerPreferenceValue="true"
textPreferenceKey="annotateElemText"
verticalRulerPreferenceKey="annotateElemVerticalRuler"
verticalRulerPreferenceValue="true">
</specification>
</extension>
<extension
point="org.eclipse.ui.views">
<view id="sourceviewsample.SampleEditor"
name="Source Viewer"
class="sourceviewsample.SampleEditor"/>
</extension>
</plugin>

Getting user data in NewProjectCreationPage in Eclipse Plugin

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
}
}

windowbuilder tutorial not functioning

I am trying to do a tutorial that allows one to Add and Remove stocks and witness their price and change. This tutorial demonstrates how to use the GUI builder, GWT Designer, to create and design a Stock Watcher application based on the GWT tutorial.
http://code.google.com/webtoolkit/tools/gwtdesigner/tutorials/stockwatcher.html#design_ui
So far I have SW.java:
package edu.gatech.client;
import java.util.ArrayList;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class SW implements EntryPoint {
private RootPanel rootPanel;
private FlexTable stocksFlexTable;
private HorizontalPanel addPanel;
private VerticalPanel mainWindow;
private TextBox newSymbolTextBox;
private Button addButton;
private Label lastUpdatedLabel;
private ArrayList <String> stocks = new ArrayList<String>(); //Add this line
public void onModuleLoad() {
rootPanel = RootPanel.get();
mainWindow = new VerticalPanel();
rootPanel.add(mainWindow, 10, 10);
mainWindow.setSize("267px", "175px");
FlexTable stocksFlexTable = new FlexTable();
//Add these lines
stocksFlexTable.setText(0, 0, "Symbol");
stocksFlexTable.setText(0, 1, "Price");
stocksFlexTable.setText(0, 2, "Change");
stocksFlexTable.setText(0, 3, "Remove");
mainWindow.add(stocksFlexTable);
addPanel = new HorizontalPanel();
rootPanel.add(addPanel, 10, 200);
addPanel.setSize("267px", "68px");
newSymbolTextBox = new TextBox();
newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER){
addStock();
}
}
});
addPanel.add(newSymbolTextBox);
newSymbolTextBox.setWidth("211px");
addButton = new Button("Add");
addButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
addStock();
}
});
addPanel.add(addButton);
lastUpdatedLabel = new Label("New Label");
rootPanel.add(lastUpdatedLabel, 48, 274);
}
private void addStock() {
final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + symbol + "' is not a valid symbol.");
newSymbolTextBox.selectAll();
return;
}
newSymbolTextBox.setText("");
// don't add the stock if it's already in the watch list
if (stocks.contains(symbol))
return;
// add the stock to the list
int row = stocksFlexTable.getRowCount();
stocks.add(symbol);
stocksFlexTable.setText(row, 0, symbol);
// add button to remove this stock from the list
Button removeStock = new Button("x");
removeStock.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
int removedIndex = stocks.indexOf(symbol);
stocks.remove(removedIndex);
stocksFlexTable.removeRow(removedIndex + 1);
}
});
stocksFlexTable.setWidget(row, 3, removeStock);
}
}
When I run the web application, I cannot Add a stock. The program does, however, distinguish between bad stock names and acceptable ones. Instead I get an "uncaught exception escaped" error and the program doesn't really do anything. How do I troubleshoot this?
Use the debugger and single step through the code. Set a breakpoint on addStock's first line and find which line crashes. Once you find which line you then instrument the line to find out what aspect is causing the problem - assuming you can't deduce the problem by looking at the line.

Reading xls file in gwt

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.

Control Netbeans from Commandline: attach Debugger from Shell-script

I'm using a daemon-script which is monitoring a remote server. When the remote server is up, i want that Netbeans automatically connects it's Debugger to the remote Server.
Is it possible to control this behavior from commandline?
To type Something like
netbeans --attach-debugger 192.168.178.34:9009
inside a terminal to do that? Or what other ways do i have to get access to Netbeans-internal stuff? (until now, i was just a "user" of Netbeans so i don't know the internals and how to access them very well)
Or will i have to write a Netbeans Plugin to do that? If yes, can you give me a good starting point to add that functionality?
Ok since there is no option to attach the Debugger from commandline, i wrote a Netbeans Plugin with the help of this blog entry and this thread from the NB-mailinglist. Now i'm able to call my plugin actions from the Commandline.
So build a simple NetBeans Module, which contains 2 important classes.
This is the class which gets the commandline parameters and forwards them to my Action:
import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.Action;
import org.netbeans.api.sendopts.CommandException;
import org.netbeans.spi.sendopts.Env;
import org.netbeans.spi.sendopts.OptionProcessor;
import org.netbeans.spi.sendopts.Option;
import org.openide.ErrorManager;
import org.openide.cookies.InstanceCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.lookup.ServiceProvider;
import org.openide.windows.WindowManager;
#ServiceProvider(service = OptionProcessor.class)
public class TriggerActionCommandLine extends OptionProcessor {
//Here we specify "runAction" as the new key in the command,
//but it could be any other string you like, of course:
private static Option action = Option.requiredArgument(Option.NO_SHORT_NAME, "debug");
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
#Override
public Set<org.netbeans.spi.sendopts.Option> getOptions() {
return Collections.singleton(action);
}
#Override
protected void process(Env env, Map<Option, String[]> values) throws CommandException {
final String[] args = (String[]) values.get(action);
if (args.length > 0) {
//Set the value to be the first argument from the command line,
//i.e., this is "GreetAction", for example:
final String ip = args[0];
//Wait until the UI is constructed,
//otherwise you will fail to retrieve your action:
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
#Override
public void run() {
//Then find & perform the action:
Action a = findAction(AttachDebugger.ACTION_NAME);
// forward IP address to Action
ActionEvent e = new ActionEvent(this, 1, ip);
a.actionPerformed(e);
}
});
}
}
public Action findAction(String actionName) {
FileObject myActionsFolder = FileUtil.getConfigFile("Actions/PSFActions");
FileObject[] myActionsFolderKids = myActionsFolder.getChildren();
for (FileObject fileObject : myActionsFolderKids) {
logger.info(fileObject.getName());
//Probably want to make this more robust,
//but the point is that here we find a particular Action:
if (fileObject.getName().contains(actionName)) {
try {
DataObject dob = DataObject.find(fileObject);
InstanceCookie ic = dob.getLookup().lookup(InstanceCookie.class);
if (ic != null) {
Object instance = ic.instanceCreate();
if (instance instanceof Action) {
Action a = (Action) instance;
return a;
}
}
} catch (Exception e) {
ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
return null;
}
}
}
return null;
}
}
This is my Plugin Action which attaches the Debugger to the given remote address:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.debugger.jpda.DebuggerStartException;
import org.netbeans.api.debugger.jpda.JPDADebugger;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.python.util.PythonInterpreter;
#ActionID(category = "PSFActions", id = "de.mackaz.AttachDebugger")
#ActionRegistration(displayName = "#CTL_AttachDebuggerAction")
#ActionReferences({
#ActionReference(path = "Menu/Tools", position = 1800, separatorBefore = 1750, separatorAfter = 1850)
})
public final class AttachDebugger implements ActionListener {
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
public static final String ACTION_NAME="AttachDebugger";
#Override
public void actionPerformed(ActionEvent e) {
String ip;
if (!e.getActionCommand().contains("Attach Debugger")) {
ip = e.getActionCommand();
} else {
ip = lookupIP();
}
try {
logger.log(Level.INFO, "Attaching Debugger to IP {0}", ip);
JPDADebugger.attach(
ip,
9009,
new Object[]{null});
} catch (DebuggerStartException ex) {
int msgType = NotifyDescriptor.ERROR_MESSAGE;
String msg = "Failed to connect debugger to remote IP " + ip;
NotifyDescriptor errorDescriptor = new NotifyDescriptor.Message(msg, msgType);
DialogDisplayer.getDefault().notify(errorDescriptor);
}
}
}
Now i can attach the Netbeans debugger to a specific address by calling netbeans/bin/netbeans --debug 192.168.178.79