Eclipse SourceVIew doesn't hightlight comments with JavaSourceViewerConfiguration - eclipse

I develop Eclipse plugin.
I want to show highlighted java code in my ViewPart.
I try to use integrated Eclipse classes (SourceViewer with JavaSourceViewerConfiguration). Here is my code:
#Override
public void createPartControl(Composite parent) {
String code = "int a = 5;\n" +
"//not-working comment\n" +
"/* not working single line comment */ \n" +
"not-working multi-line comment\n";
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
SourceViewer sv = new SourceViewer(parent, null, SWT.NONE);
JavaSourceViewerConfiguration config =
new JavaSourceViewerConfiguration(
tools.getColorManager(),
JavaPlugin.getDefault().getCombinedPreferenceStore(),
null,
null
);
sv.configure(config);
Document d = new Document();
d.set(code);
sv.setDocument(d);
}
It successfully highlights all code, but doesn't highlight any comments. What I do wrong?
UPD:
I'm not sure if it is important, but there is list of plugins/packages marked in manifest file as required:
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.jdt.ui,
org.eclipse.ui.workbench.texteditor,
org.eclipse.jface.text
Import-Package: org.eclipse.jface.text.source

Looks like you need to specify the partitioning parameter (last argument of the JavaSourceViewerConfiguration constructor) as IJavaPartitions.JAVA_PARTITIONING.

You have to define a partitioner for the document:
IDocumentPartitioner partitioner = new FastPartitioner(new FastJavaPartitionScanner(), new String[] {
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING, IJavaPartitions.JAVA_CHARACTER });
and then connect both of them:
d.setDocumentPartitioner(partitioner);
partitioner.connect(d);

Related

How to invoke importwizard from eclipse plugin programmatically

I need to invoke eclipse importwizard from the eclipse plugin project programmatically. i follow the example from , seems not work
https://resheim.net/2010/07/invoking-eclipse-wizard.html
then in my code , it shows wizards array is empty, do i need to register importwizard ? and how?
IWizardDescriptor[] wizards= PlatformUI.getWorkbench().getImportWizardRegistry().getPrimaryWizards();
The import dialog doesn't use 'primary' wizards. You need to know the id of the wizard you want to use and call the wizard registry findWizard method.
The Import Projects wizard id is org.eclipse.ui.wizards.import.ExternalProject so the code would look like:
String id = "org.eclipse.ui.wizards.import.ExternalProject"
IWizardDescriptor descriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(id);
IWizard wizard = descriptor.createWizard();
WizardDialog wd = new WizardDialog(display.getActiveShell(), wizard);
wd.setTitle(wizard.getWindowTitle());
wd.open();
private void openProject(String projectfolder) throws CoreException {
//TODO: check if project is already created and open, if yes do nothing or just refresh
IProjectDescription description = null;
IProject project = null;
description = ResourcesPlugin.getWorkspace().loadProjectDescription(
new Path(new File(projectfolder).getAbsolutePath()
+ "/.project"));
project = ResourcesPlugin.getWorkspace().getRoot()
.getProject(description.getName());
project.create(description, null);
project.open(null);
}

suggestBox: Suggestions aren't displayed as HTML anymore gwt 2.4 -->2.7

I am not familiar with gwt and I had to upgrade from gwt 2.4 to gwt 2.7.
I have a problem with a suggestBox item:
i need to interpret HTML tag present in the MultiWordSuggestOracle:
I overrided isDisplayingStringHtml to be sure it was set to true:
private MultiWordSuggestOracle oracle = new MultiWordSuggestOracle() {
#Override
public boolean isDisplayStringHTML() {
return true;
}
};
Then I tried to insert this :
private void initOracle() {
String gogogogo= "<tt>####</tt>";
HTML html = new HTML("<tt>####2</tt>");
List<String> listeSuggeree = new ArrayList<String>();
listeSuggeree.add("<HTML><div>#####</div></HTML>");
listeSuggeree.add((gogogogo));
listeSuggeree.add(html.getHTML());
listeSuggeree.add("AAAAAH nothing work");
oracle.addAll(listeSuggeree);
oracle.setDefaultSuggestionsFromText(listeSuggeree);
HTML problem
All worked perfectly on gwt 2.4 and I didn't find a way to interpret this HTML on gwt 2.7.0, can you help me?
You should use MultiWordSuggestion.
The constructor takes two parameters:
replacementString - the string to enter into the SuggestBox's text box
if the suggestion is chosen
displayString - the display string
Basically, displayString is shown in the list, replacementString is shown in the TextBox after selection.
So, here is the proper way to prepare your suggestion list:
List<Suggestion> listeSuggeree = new ArrayList<Suggestion>();
listeSuggeree.add(new MultiWordSuggestOracle.MultiWordSuggestion("bold replacement", "<b>bold</b>"));
listeSuggeree.add(new MultiWordSuggestOracle.MultiWordSuggestion("italic replacement", "<i>italic</i>"));
listeSuggeree.add(new MultiWordSuggestOracle.MultiWordSuggestion("underline replacement", "<u>underline</u>"));
listeSuggeree.add(new MultiWordSuggestOracle.MultiWordSuggestion("SUCCESS!", "All works!"));
oracle.setDefaultSuggestions(listeSuggeree);
And the output is:
BTW: isDisplayStringHTML is true by default.

Reading sheet contents using SmartSheet Java SDK

I am trying to read data using the Smartsheet API from Java to create different formats, such as reports & labels with the data from one row.
I've set up my IDE (NetBeans) so that the API samples work for me, but they are all about creating new sheets etc and I can not figure out how to read the contents of an existing sheet.
I would have thought that I could read the entire sheet into a java object in one line of code, but it appears more complicated than that, and I can not find any applicable documentation anywhere. The Javadoc does not say where/how to get the relevant IDs, what any of the inclusion or exclusion objects actually do, or which are required or optional etc.
Are there any examples of reading the contents of a sheet from java available?
I know that this is a bit of a broad question, but I'm totally stumped.
Thanks Kim!
For others, here's what worked for me. This code gets a list of the sheets in my account and displays the contents those with names starting with "Specs - " :
import com.smartsheet.api.Smartsheet;
import com.smartsheet.api.SmartsheetBuilder;
import com.smartsheet.api.SmartsheetException;
import com.smartsheet.api.models.Cell;
import com.smartsheet.api.models.Column;
import com.smartsheet.api.models.PagedResult;
import com.smartsheet.api.models.Row;
import com.smartsheet.api.models.Sheet;
import com.smartsheet.api.oauth.Token;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SampleCode {
/*
Show the contenst of all sheets whose name starts with "Specs - "
*/
public static void main(String[] args) {
final String delimiter = ", ";
// Create a Smartsheet object with our Access Token
Token token = new Token();
token.setAccessToken(Private.TOKEN);
Smartsheet smartsheet = new SmartsheetBuilder().setAccessToken(token.getAccessToken()).build();
//get a paged list of all Sheets, using null Source Inclusion & Pagination parameters
PagedResult<Sheet> homeSheets = new PagedResult<>();
try {
homeSheets = smartsheet.sheetResources().listSheets(null, null);
} catch (SmartsheetException ex) {
Logger.getLogger(SampleCode.class.getName()).log(Level.SEVERE, null, ex);
}
// get a Java List<Sheet> from the PagedResult<Sheet>
List<Sheet> sheetInfoList = homeSheets.getData();
// Loop through each sheet in the list
for (Sheet sheetInfo : sheetInfoList) {
String sheetName = sheetInfo.getName();
// Show data for all sheets with names that match our pattern
if (sheetName.startsWith("Specs - ")) {
// get the sheet object, with no optional includes or excludes
Sheet theSheet = null;
try {
theSheet = smartsheet.sheetResources().getSheet(sheetInfo.getId(), null, null, null, null, null, null, null);
} catch (SmartsheetException ex) {
Logger.getLogger(SampleCode.class.getName()).log(Level.SEVERE, null, ex);
}
// Print the sheets name
System.out.println("\nSheet: " + theSheet.getName() + "\n");
// Print the column titles as a delimited line of text.
List<Column> columnList = theSheet.getColumns();
String columnHeader = null;
for (Column col : columnList) {
columnHeader = columnHeader == null ? col.getTitle() : columnHeader + delimiter + col.getTitle();
}
System.out.println(columnHeader);
// Print each row as a delimited line of text.
List<Row> rowList = theSheet.getRows();
for (Row row : rowList) {
List<Cell> cellList = row.getCells();
String rowOutput = null;
for (Cell cell : cellList) {
String cellOutput = Objects.toString(cell.getValue() != null ? cell.getValue() : cell.getDisplayValue());
rowOutput = rowOutput == null ? cellOutput : rowOutput + delimiter + cellOutput;
}
System.out.println(rowOutput);
}
}
}
}
}
The Smartsheet API documentation contains sample code that shows how to use the Java SDK. The Java Sample Code section in the docs describes how to establish the connection, etc. Then, each operation within in the "API Reference" section shows sample code (in the "Java" tab of the panel on the right side of the page) for executing the operation using the Java SDK.
To get Sheet data you'll use the "Get Sheet" operation. As described in the API docs, here's the Java SDK sample code for that operation:
// Get sheet (omit all parameters).
smartsheet.sheetResources().getSheet(sheetId, null, null, null, null, null, null, null);
The "sheetId" parameter should be the ID of the Sheet which you want to retrieve. You can either get this ID programmatically (i.e., by using an operation like "List Sheets", for example) -- or you can get it manually via the Smartsheet UI as described in this help article. The other parameters (all set to "null" in the sample code) represent the 7 parameters described in the API documentation for this operation. I imagine intellisense in your IDE should indicate the sequence of those parameters expected by the getSheet function, as well as valid values for each parameter (but the API docs will explain the meaning of each parameter).

How to get text from textbox of MS word document using Apache POI?

I want to get information written in Textbox in an MS word document. I am using Apache POI to parse word document.
Currently I am iterating through all the Paragraph objects but this Paragraph list does not contain information from TextBox so I am missing this information in output.
e.g.
paragraph in plain text
**<some information in text box>**
one more paragraph in plain text
what i want to extract :
<para>paragraph in plain text</para>
<text_box>some information in text box</text_box>
<para>one more paragraph in plain text</para>
what I am getting currently :
paragraph in plain text
one more paragraph in plain text
Anyone knows how to extract information from text box using Apache POI?
This worked for me,
private void printContentsOfTextBox(XWPFParagraph paragraph) {
XmlObject[] textBoxObjects = paragraph.getCTP().selectPath("
declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'
declare namespace wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape'
declare namespace v='urn:schemas-microsoft-com:vml'
.//*/wps:txbx/w:txbxContent | .//*/v:textbox/w:txbxContent");
for (int i =0; i < textBoxObjects.length; i++) {
XWPFParagraph embeddedPara = null;
try {
XmlObject[] paraObjects = textBoxObjects[i].
selectChildren(
new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "p"));
for (int j=0; j<paraObjects.length; j++) {
embeddedPara = new XWPFParagraph(
CTP.Factory.parse(paraObjects[j].xmlText()), paragraph.getBody());
//Here you have your paragraph;
System.out.println(embeddedPara.getText());
}
} catch (XmlException e) {
//handle
}
}
}
To extract all occurrences of text from Word .doc and .docx files for crgrep I used the Apache Tika source as a reference of how the Apache POI APIs should be correctly used. This is useful if you want to use POI directly and not depend on Tika.
For Word .docx files, take a look at this Tika class:
org.apache.tika.parser.microsoft.ooxml.XWPFWordExtractorDecorator
if you ignore XHTMLContentHandler and formatting code you can see how to navigate a XWPFDocument correctly using POI.
For .doc files this class is helpful:
org.apache.tika.parser.microsoft.WordExtractor
both from the tika-parsers-1.x.jar. An easy way to access the Tika code through your maven dependencies is add Tika temporarily to your pom.xml such as
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>1.7</version>
</dependency>
let your IDE resolve attached source and step into the classes above.
If you want to get text from textbox in docx file (using POI 3.10-FINAL) here is sample code:
FileInputStream fileInputStream = new FileInputStream(inputFile);
XWPFDocument document = new XWPFDocument(OPCPackage.open(fileInputStream));
for (XWPFParagraph xwpfParagraph : document.getParagraphs()) {
String text = xwpfParagraph.getParagraphText(); //here is where you receive text from textbox
}
Or you can iterate over each
XWPFRun in XWPFParagraph and invoke toString() method. Same result.

Where does Eclipse store keyboard bindings?

Where does Eclipse store its user preferences? Specifically the keyboard bindings?
When you close Eclipse, any local settings regarding key shortcuts (settings that differ from the default configuration) are saved in
</path/to/workspace>\.metadata\.plugins\org.eclipse.core.runtime\.settings\
org.eclipse.ui.workbench.prefs
You can actually just copy the whole line in the org.eclipse.ui.workbech.prefs file that starts with: org.eclipse.ui.commands=
and paste it into the other corresponding eclipse workspace prefs file you want to update - at least in Eclipse Neon, and you'll get them all at once.
You can extract the bindings using the following groovy script. I'm not a groovy developer so please excuse my hack.
Groovy Script Used (substitute in a correct path to the workbench xmi file):
workbench = new XmlSlurper().parse("<path to eclipse>/workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi")
List bindingTables
workbench.bindingTables.each
{ it->
//println "\tContributorURI: ${it.#contributorURI} | \tElementID : it.#elementId";
def command = "command";
def commandName = "commandname";
def description = "description";
def category;
def name = "name";
def keys = "keys";
it.bindings.each
{bindingIt->
//loop through every binding entry
command = bindingIt.#command;
keys = bindingIt.#keySequence;
workbench.commands.each
{commandIt->
def thisCommand = commandIt.attributes()['{http://www.omg.org/XMI}id'];
if(thisCommand.equals(command.toString()) )
{
commandName = commandIt.#commandName;
description = commandIt.#description;
category = commandIt.#category;
workbench.categories.each
{workbenchIt->
if(workbenchIt.attributes()['{http://www.omg.org/XMI}id'].equals(category.toString()) )
{
name = workbenchIt.#name;
}
}
}
}
println "\t\tKeys: ${keys}\tCommand: ${commandName}"+
"\tDescription: "+description+"\tName: "+name;
}
}