Can parse but not evaluate xtext arithmetics example - java

I'm having a look at XText within the Eclipse framework, and have a question about the arithmetics example. I seem to be able to parse expressions but not evaluate them and wonder if this should be so. This is my workflow:
Create a new Example projext. Choose XText Simple Arithmetics Example.
Open Arithmetics.xtext and choose Run -> External Tools -> Run as -> "Generate XText artifacts".
No Error messages so far as. A bunch of info messages on the form:
119 [main] INFO lipse.emf.mwe.utils.StandaloneSetup - Registering project org.eclipse.xtext.example.arithmetics at 'file:/H:/2017/xtextworkspace/org.eclipse.xtext.example.arithmetics/'
119 [main] INFO lipse.emf.mwe.utils.StandaloneSetup - Registering project org.eclipse.xtext.example.arithmetics.tests at 'file:/H:/2017/xtextworkspace/org.eclipse.xtext.example.arithmetics.tests/'
Open plugin.xml and click "Launch an Eclipse application".
A second window now opens up and I can now create a new project and start typing expressions.
Create a new project and a new file calles a.calc with this content:
(I also seem to have to create a new Java project here which seems a bit counter-intuitive. Shouldn't it be possible in your new IDE to have a menu option here like "Create new Calc Project"?).
module A
def a:2;
def b:1;
a+b;
The editor seem to parse fine, content assist is working and it tells me if I do something wrong. But isn't it possible to actually run the program? I would like to have an option here similar to "Run -> Run as -> Calc application" Is this not included in the Arithmetics example? I feel like it should be because what else would be the purpose of the calculator.java class? How do I make it print out the value?

you get the expressions evaluated by typing "enter" inside the editor
module A
def a:2;
def b:1;
a+b;
// = 3
1+1;
// = 2
33*11;
// = 363

Related

Automatically replacing with var using IntelliJ

I'm migrating some pre Java 10 code and I'm wondering if IntelliJ offers a way to automatically refactor the code to replace the variable declarations that uses the actual type with var wherever it's possible.
The code is full of stuff like:
String status = "empty";
BigDecimal interest = BigDecimal.ZERO;
List<Future<Boolean>> results = es.invokeAll(tasks);
LocalDate start = LocalDate.of(2020, 1, 1);
And I would prefer:
var status = "empty";
var interest = BigDecimal.ZERO;
var results = es.invokeAll(tasks);
var start = LocalDate.of(2020, 1, 1);
I already looked in IntelliJ's settings (Code Style/Inspections) and couldn't find anything.
Go to File | Settings, there select Editor | Inspections, then under Java | Java language level migration aids | Java 10.
Right click on Local variable type can be omitted and select Weak Warning or similar.
Move Your cursor onto any of those warnings in Your code (highlighted grey), open quick fix context help (alt+enter), at Replace explicit type with 'var' move to the right and select Fix all 'Local variable type can be omitted' problems in file
Thanks for #olga-klisho for the idea (in comments)
I'm using IntelliJ IDEA 2021.3.2, but don't think the setting is new.
I've been struggling with this one myself.
It seems that the first time to install IntelliJ locally, by default, it will fall back to using traditional defining of variables (i.e. String s = new String();)
How I managed to change it into using var is after I declared something, for example new String(), either I pressed ⌥ Alt/Option+Enter to declare a variable for that declaration or by using ⌘ Command+⇧ Shift+V shortcut (I'm using Mac and classic Intellij key mapping, so YMMV) which activates declaration of a variable, this would show as follows:
As you see, it suggest to hit that key combination shortcut or clicking on the settings button that would open a pop up like this one:
Make sure you have Declare var type selected and you should be good to go.
Use the IntelliJ Edit -> Find -> Replace... option.
Or Ctrl + R

Creating a new Java project

I am able to create a default project in PDE just like mentioned here.
However I want to know how to create a Java project. How can I do that?
As a minimum you need to add the Java project nature to the project you create. Use something like:
private void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException
{
IProjectDescription description = proj.getDescription();
String[] prevNatures = description.getNatureIds();
String[] newNatures = new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length] = natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
The nature id for a Java project is 'org.eclipse.jdt.core.javanature' (also in the JavaCore.NATURE_ID constant).
Note that this does not add the various builders that are normally used in a Java project. The IProjectDescription.setBuildSpec method adds those in a similar way. Create a command for the build spec with:
ICommand command = description.newCommand();
command.setBuilderName(builderID);
where 'builderId' is 'org.eclipse.jdt.core.javabuilder' for the main Java builder (JavaCore.BUILDER_ID constant).
All this information is stored in the '.project' file in the project root folder. This is an XML file which you can look at to see the set up of existing projects.
Window->Open Perspective->Java
then
File->New->Java Project (you may have to go via "Project..." to get to the "Java Project" option)
Please refer to New Project Creation Wizards
On the Plug-in Project page, use com.example.helloworld as the name
for your project and check the box for Create a Java project (this
should be the default). Leave the other settings on the page with
their default settings and then click Next to accept the default
plug-in project structure.

Vim Syntastic Java Unaware of Current Project Classes

Using Vim Syntastic with an android project. (e.g. com.myproject.project) It's not aware of classes declared within my project but outside of the current file. e.g. the following flags errors:
import com.myproject.project.SomeClass;
...
SomeClass someclass = new SomeClass();
Saw this post Configure syntastic to work fine with Android projects which solve the problem:
Method 1:
Inside vim editor
:SyntasticJavacEditClasspath
Then add the following to the buffer window
/path-to-your-app/bin/classes
/path-to-your-android-sdk/platforms/android-19/*.jar
Method 2:
Add the following to the .vimrc:
let g:syntastic_java_javac_classpath = "/<path-to-your-app>/bin/classes:/<path-to-your-android-sdk>/platforms/android-19/*.jar"
Here is a summary of the various methods which worked for me in linux vim7.4 and Syntastic3.7.0-224 with credit to each.
Method 1 - manual creation of .syntastic_javac_config
1. Edit .vimrc and use this syntax:
let g:syntastic_java_javac_config_file_enabled = 1
2. Where you edit your vim files, add this to a file named .syntastic_javac_config
let g:syntastic_java_javac_classpath = '/home/davis/progs/princeton-algos/week1/libs/algs4.jar'
Method 2 - advantage no matter where you edit the class path is known.
1. Edit .vimrc and use this syntax:
let g:syntastic_java_javac_classpath = "/home/davis/progs/princeton-algos/week1/libs/algs4.jar"
This adds the jar and
Method 3 - Automatic generation of .syntastic_javac_config file
1. Edit .vimrc and use this syntax:
let g:syntastic_java_javac_config_file_enabled = 1
2. Edit a java file with vim
3. :SyntasticJavacEditClasspath
When the edit window opens, add the class path without quotes and a newline after each entry the class path. In my case, this is the entry
for the setting includes the current folder as well:
/home/davis/progs/princeton-algos/week1/libs/algs4.jar
.
4 :wq the edit setting window
5. Now the class path is set for syntastic when editing files from that location. If you edit from a new directory, you will need to repeat the process.
Besides the comments above, this post also helped.

Using Extension Points: no configurable elements found

i created an extension point for one plugin(A). Another plugin(B) is setup as an extension to the ep from the first plugin.
When trying to use the extension point eclipse in A eclipse tells me that, it is not able to find configurable elements for the this extension point. The extension point itself is found.
I'm suspecting plugin B is not started at all. How can i check this?
Here is the code, where the extension point gets called:
IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry();
IExtensionPoint[] extensionPoints = extensionRegistry.getExtensionPoints("A.extensionpoints");
//Prints both defined EP's
for (IExtensionPoint iExtensionPoint : extensionPoints) {
System.err.println(iExtensionPoint.getUniqueIdentifier());
System.err.println(iExtensionPoint.getExtensions().length);
}
IExtensionPoint extensionPoint = extensionRegistry.getExtensionPoint("A.extensionpoints.HavingProblemsWith");
System.err.println(extensionPoint.getLabel());//Prints the Label
System.err.println(extensionPoint.getConfigurationElements().length);// => 0
Fire up eclipse with the -console option. Then you have tools to view the status of the plugins and to start them, if you want so. It may give you some ideas on why the plugin hasn't been started.

Programmatically analyze java heap dump file

I want to write a program (preferably in java) that will parse and analyze a java heap dump file (created by jmap). I know there are many great tools that already do so (jhat, eclipse's MAT, and so on), but I want to analyze the heap from a specific perspective to my application.
Where can I read about the structure of the heap dump file, examples how to read it, and so on? Didn't find anything useful searching for it...
Many thanks.
The following was done with Eclipse Version: Luna Service Release 1 (4.4.1) and Eclipse Memory Analyzer Version 1.4.0
Programmatically Interfacing with the Java Heap Dump
Environment Setup
In eclipse, Help -> Install New Software -> install Eclipse Plug-in Development Environment
In eclipse, Window -> Preferences -> Plug-in Development -> Target Platform -> Add
Nothing -> Locations -> Add -> Installation
Name = MAT
Location = /path/to/MAT/installation/mat
Project Setup
File -> new -> Other -> Plug-in Project
Name: MAT Extension
Next
Disable Activator
Disable Contributions to the UI
Disable API analysis
Next
Disable template
Finish
Code Generation
Open plugin.xml
Dependencies -> Add
select org.eclipse.mat.api
Extensions -> Add
select org.eclipse.mat.report.query
right click on report.query -> New
Name: MyQuery
click "impl" to generate the class
Implementing IQuery
#CommandName("MyQuery") //for the command line interface
#Name("My Query") //display name for the GUI
#Category("Custom Queries") //list this Query will be put under in the GUI
#Help("This is my first query.") //help displayed
public class MyQuery implements IQuery
{
public MyQuery{}
#Argument //snapshot will be populated before the call to execute happens
public ISnapshot snapshot;
/*
* execute : only method overridden from IQuery
* Prints out "My first query." to the output file.
*/
#Override
public IResult execute(IProgressListener arg0) throws Exception
{
CharArrayWriter outWriter = new CharArrayWriter(100);
PrintWriter out = new PrintWriter(outWriter);
SnapshotInfo snapshotInfo = snapshot.getSnapshotInfo();
out.println("Used Heap Size: " + snapshotInfo.getUsedHeapSize());
out.println("My first query.")
return new TextResult(outWriter.toString(), false);
}
}
ctrl+shift+o will generate the correct "import" statements.
Custom queries can be accessed within the MAT GUI by accessing the toolbar's "Open Query Browser" at the top of the hprof file you have opened.
The ISnapshot interface
The most important interface one can use to extract data from a heap dump is ISnapshot. ISnapshot represents a heap dump and offers various methods for reading object and classes from it, getting the size of objects, etc…
To obtain an instance of ISnapshot one can use static methods on the SnapshotFactory class. However, this is only needed if the API is used to implement a tool independent of Memory Analyzer. If you are writing extensions to MAT, then your coding will get an instance corresponding to an already opened heap dump either by injection or as a method parameter.
Reference
Built in Command Line Utility
If you're looking to have a program generate the usual reports, there is a command line utility called ParseHeapDump available with any download of Eclipse's MAT tool. You'll be able to get useful html dumps of all the information MAT stores.
> ParseHeapDump <heap dump> org.eclipse.mat.api:suspects org.eclipse.mat.api:top_components org.eclipse.mat.api:overview #will dump out all general reports available through MAT
Hopefully this is enough information to get you started.
I'm not familiar with jhat, but Eclipse's MAT is open source. Their SVN link is available, perhaps you could look through that for their parser, perhaps even use it.

Categories