Get IntelliJ to show compilation problems automatically [duplicate] - java

Yesterday I switched to IntelliJ IDEA from Eclipse.
I am using JRebel with WebSphere Server 7 as well.
Everything now seems to be working somewhat fine, except that when I modify a Java file, and hit save, IntelliJ does not re-compile the file, in order for JRebel to pick it up.
The Eclipse "Build Automatically" feature resolved this issue.
In IntelliJ IDEA, I have to hit CTRL+SHIFT+9 to re-compile the relevant class for JRebel to pick it up. If changes are done across two files, I have to do this on each and one of them and since IntelliJ uses the save all mechanism, its pretty hard to know what to recompile manually which I am not really interested in doing either.
Isn't there a way to make IntelliJ to do this on its own?

UPDATED
For IntelliJ IDEA 12+ releases we can build automatically the edited sources if we are using the external compiler option. The only thing needed is to check the option "Build project automatically", located under "Compiler" settings:
Also, if you would like to hot deploy, while the application is running or if you are using spring boot devtools you should enable the compiler.automake.allow.when.app.running from registry too. This will automatically compile your changes.
For versions greater than 2021.2, we need check 'Allow auto-make to start even id the development application is currently running' option:
For versions older than 2021.2:
Using Ctrl+Shift+A (or ⌘+Shift+A on Mac) type Registry once the registry windows is open, locate and enable compiler.automake.allow.when.app.running, see here:
For versions older than 12, you can use the *EclipseMode* plugin to make IDEA automatically compile the saved files.
For more tips see the "Migrating From Eclipse to IntelliJ IDEA" guide.

Please follow both steps:
1 - Enable Automake from the compiler
Press: ctrl + shift + A (For Mac ⌘ + shift + A)
Type: make project automatically
Hit: Enter
Enable Make Project automatically feature
2 - Enable Automake when the application is running
Press: ctrl + shift + A (For Mac ⌘ + shift + A)
Type: Registry
Find the key compiler.automake.allow.when.app.running and enable it or click the checkbox next to it
Note: Restart your application now :)
Note: This should also allow live reload with spring boot devtools.

WARNING
Eclipse Mode plug-in is obsolete and is not compatible with the recent IDEA 12+ builds. If you install it, IDE will hang on every file change and will respond extremely slow.
IntelliJ IDEA doesn't use automatic build, it detects errors on the fly, not via compiler. Similar to Eclipse mode will be available in IDEA 12:
Use Build | Make, it invokes the incremental make process that will compile only changed and dependent files (it's very fast).
There is also a FAQ entry that may help.
Update on the automatic make feature:
When run/debug configuration is running, Make project automatically has no effect. Classes on disk will change only on Build | Make. It's the core design decision as in our opinion class changes on disk should be always under user's control. Automatic make is not the copycat of Eclipse feature, it works differently and it's main purpose is to save time waiting for the classes to be ready when they are really needed (before running the app or tests). Automatic make doesn't replace the explicit compilation that you still need to trigger like in the case described in this question. If you are looking for different behavior, EclipseMode plug-in linked in the FAQ above would be a better choice.

You can keymap ctrl+s to save AND compile in one step. Go to the keymap settings and search for Compile.

There is actually no difference as both require 1 click:
Eclipse: manual Save, auto-compile.
IntelliJ: auto Save, manual compile.
Simplest solution is just to get used to it. Because when you spend most of your daytime in your IDE, then better have fast habits in one than slow habits in several of them.

I ended up recording a Macro to save and compile in one step, and keymap Ctrl+s to it.

I managed to solve this using macros.
I started recording a macro:
Click Edit - Macros - Start macro recording
Click File - Save All
Click Build - Make Project
Click Edit - Macros - Stop macro recording
Name it something useful like, "SaveAndMake".
Now just remove the Save all keybinding, and add the same keybinding to your macro!
So now, every time i save, it saves and makes a dirty compile, and jRebel now detects all changes correctly.

Please follow these steps carefully to enable it.
1) create Spring Boot project with SB V1.3 and add "Devtools" (1*) to dependencies
2) invoke Help->Find Action... and type "Registry", in the dialog search for "automake" and enable the entry "compiler.automake.allow.when.app.running", close dialog
3) enable background compilation in Settings->Build, Execution, Deployment->Compiler "Make project automatically"
4) open Spring Boot run config, you should get warning message if everything is configured correctly
5) Run your app, change your classes on-the-fly
Please report your experiences and problems as comments to this issue.
click here for more info

For folks using the new Intellij version and can't find compiler.automake.allow.when.app.running
https://youtrack.jetbrains.com/issue/IDEA-274903
Basically the option has now moved to Settings -> Advanced Settings -> Compiler (Check the Allow auto-make option)

The only thing that worked for me in my maven project that was affected by this is to add a "test-compile" goal to the run configuration of my unit tests. Incredibly clumsy solution, but it works.

Intellij fails quietly when it encounters compile problem in other module, and then automatic build is not performed. So check your Problems window

i had same issue and also a problem file icon in intellij, so i removed the .idea folder and re import project solved my issue.

For Intellij 2021 or later, you'll not find the registry entry
compiler.automake.allow.when.app.running
It has been moved to advanced settings as shown in the below screenshot
Source: https://youtrack.jetbrains.com/issue/IDEA-274903

I had the same issue.
I was using the "Power save mode", which prevents from compiling incrementally and showing compilation errors.

Use the Reformat and Compile plugin (inspired by the Save Actions plugin of Alexandre DuBreuil):
https://plugins.jetbrains.com/plugin/8231?pr=idea_ce
At the moment I am only offering a jar file, but this is the most important part of the code:
private final static Set<Document> documentsToProcess = new HashSet<Document>();
private static VirtualFile[] fileToCompile = VirtualFile.EMPTY_ARRAY;
// The plugin extends FileDocumentManagerAdapter.
// beforeDocumentSaving calls reformatAndCompile
private static void reformatAndCompile(
#NotNull final Project project,
#NotNull final Document document,
#NotNull final PsiFile psiFile) {
documentsToProcess.add(document);
if (storage.isEnabled(Action.compileFile) && isDocumentActive(project, document)) {
fileToCompile = isFileCompilable(project, psiFile.getVirtualFile());
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
#Override
public void run() {
if (documentsToProcess.contains(document)) {
documentsToProcess.remove(document);
if (storage.isEnabled(Action.optimizeImports)
|| storage.isEnabled(Action.reformatCode)) {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
#Override
public void run() {
if (storage.isEnabled(Action.optimizeImports)) {
new OptimizeImportsProcessor(project, psiFile)
.run();
}
if (storage.isEnabled(Action.reformatCode)) {
new ReformatCodeProcessor(
project,
psiFile,
null,
ChangeListManager
.getInstance(project)
.getChange(psiFile.getVirtualFile()) != null)
.run();
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
#Override
public void run() {
CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(psiFile);
}
});
}
});
}
}
if (fileToCompile.length > 0) {
if (documentsToProcess.isEmpty()) {
compileFile(project, fileToCompile);
fileToCompile = VirtualFile.EMPTY_ARRAY;
}
} else if (storage.isEnabled(Action.makeProject)) {
if (documentsToProcess.isEmpty()) {
makeProject(project);
}
} else {
saveFile(project, document, psiFile.getVirtualFile());
}
}
}, project.getDisposed());
}
private static void makeProject(#NotNull final Project project) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
#Override
public void run() {
CompilerManager.getInstance(project).make(null);
}
}, project.getDisposed());
}
private static void compileFile(
#NotNull final Project project,
#NotNull final VirtualFile[] files) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
#Override
public void run() {
CompilerManager.getInstance(project).compile(files, null);
}
}, project.getDisposed());
}
private static void saveFile(
#NotNull final Project project,
#NotNull final Document document,
#NotNull final VirtualFile file) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
#Override
public void run() {
final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
if (fileDocumentManager.isFileModified(file)) {
fileDocumentManager.saveDocument(document);
}
}
}, project.getDisposed());
}

Edit your Run/Debug Configuration so that Build option is selected before launching
After Build option is selected
The above solution worked for me while working on my JBehave test suite

It was not working for me due to having an unnecessary module in my project structure. The tests were executed using the other module, I suppose.
I don't know how it ended up like that but removing it solved the problem.
Make sure your Run/Debug settings are using the module you are building with the autosave.
E.g. : see the module in
You can change the modules in Project Structure - Modules

I had the same issue. I think it would be appropriate to check whether your class can be compiled or not. Click recompile (Ctrl+Shift+F9 by default). If its not working then you have to investigate why it isn't compiling.
In my case the code wasn't autocompiling because there were hidden errors with compilation (they weren't shown in logs anywhere and maven clean-install was working). The rootcause was incorrect Project Structure -> Modules configuration, so Intellij Idea wasn't able to build it according to this configuration.

I was getting error: some jars are not in classpath.So I just delete the corrupted jar and perrform below steps
1.Project > Setting>Build,Execution,Deployment>Compiler>check build project automatically
2.CTRL+SHIFT+A find/search **registry** --Check for below param
compiler.automake.allow.when.app.running
compiler.automake.trigger.delay=500---According to ur requirement
3.Add devtool in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
4.Build ,If found any probelm while building ,saying some jar in not in class path.Just delete the corrupted jar
and re-build the project angain after sync with maven lib

Not enough points to comment on an existing answer, but similar to some people above, I wound up just adding a macro & keymap to Organize Imports / Format / SaveAll / FastReload(F9) / Synchronize.
The synchronize is added as it seems to be the only way I can also see updates in resources modified by external build tools / watchers (i.e., webpack).
The process is slower than eclipse - and for the external file refresh often have to run the command multiple times - but suppose I can live with it.

Related

Programmatically refresh/synchronize an IntelliJ IDEA project via a plugin

Is there a way to programmatically refresh/synchronize an IntelliJ IDEA project via a plugin?
I'm working on an IntelliJ IDEA plugin that creates a file within the active project. And I want to refresh/synchronize the project automatically via the plugin so that the user can see the changes immediately. Is this possible in IntelliJ IDEA?
After digging a bit more I came through the following solution and it worked.
public void actionPerformed(AnActionEvent e) {
// Create/Modify files
// Get the project from the ActionEvent
Project project = e.getData(PlatformDataKeys.PROJECT);
// Get the Base Dir and refresh with the following parameters
// 'asynchronous' set to false and 'recursive' set to true
project.getBaseDir().refresh(false,true);
}
You can use SyncAction for it
SyncProjectAction().actionPerformed(actionEvent)

How do I run a DropWizard / Jersey server locally without having to restart & repack to get asset file updates?

I'm working on the client side of a project that is using DropWizard. Unfortunately what I'm experiencing is that for me to make a change to assets I have to stop the server, package the assets with maven, and then rerun the server or the assets will not be updated.
I tried adding dropwizard-configurable-assets-bundle but I'm still seeing the same behavior. Here's the service after adding it:
Service.java
public void initialize(strap<ServiceConfiguration> strap) {
// Assets
strap.addBundle(new ConfiguredAssetsBundle(
"/dashboard/app/", "/dashboard/", "index.html"
));
// Redirect /dashboard to /dashboard/
strap.addBundle(new RedirectBundle(ImmutableMap.<String, String>builder()
.put("/dashboard", "/dashboard/").build()));
}
I'm currently running mvn package && java -jar target/pack.jar server config.yml. I tried using Eclipse but I was having to restart it manually and it wasn't repackaging for me so it was slowing things down even further.
This whole process is reaaaally slowing me down and I'm hoping it's just my ignorance to the world that is Java.
In my Intellij Idea, i am using JRebel plug-in for this purpose. JRebel also supports Eclipse.
If your assets are packaged under src/main/resources then they should just update automatically with Eclipse without a restart being required, so long as you're running the executable service main() from within the IDE.
You may need to check that your Maven plugin is set to "generate-resources" on changes but that is just the default setting so should be in place already.
What you're describing is definitely possible in Eclipse - I have personal experience of making resource changes (e.g. change and save an HTML asset) and then seeing an immediate update upon doing nothing more than a browser refresh.

Unable to resolve reverse routing methods in IntelliJ

I'm following one of the play framework tutorials, but I'm getting compile errors whenever I try to use reverse routing. Firstly,
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("jsRoutes",
controllers.routes.javascript.Projects.add(),
controllers.routes.javascript.Projects.delete(),
controllers.routes.javascript.Projects.rename(),
controllers.routes.javascript.Projects.addGroup()
)
);
}
where the error shown in intelliJ is 'cannot resolve method javascriptRouter(java.lang.String, ?, ?, ?, ?)'
But also in the a unit test:
#Test
public void notAuthenticated() {
Result result = callAction(
controllers.routes.ref.Application.index(),
fakeRequest()
);
assertEquals(303, status(result));
assertEquals("/login", header("Location", result));
}
where it cannot resolve the index method.
Is this a problem with intelliJ, or am I missing something within play?
For the first part, here is the entry in my routes file:
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()
and my controller, Projects, has got the defined methods.
File -> Project Structure
Select Sources in Right Pane
Add Source folder
target/scala-XXX/classes_managed
target/scala-XXX/src_managed/main
I was running into the same problem and found the solution here: https://github.com/playframework/Play20/issues/969
In short:
Create the directories javascript and ref under the controllers package
Run activator compile and now Intellij should get it // used to be 'play compile'
If you still got the errors try to run activator idea again // used to be 'play compile'*
Pulled from a link provided by #Markus Kittig. Great temporary fix. https://github.com/playframework/playframework/issues/1784#issuecomment-26345523
Synopsis:
Add target/scala-XXX as a managed source and remove the app controllers and views sources flag inside File->Project Structure->Modules->Sources. Then recompile.
Works on IntelliJ Ultimate 12.1.{4|6}. Created the play application with the command line interface and generated a project file using play idea. Used Play 2.2.0.
With IntelliJ 14.1 and Play 2.3.8 nothing of the above worked, but the advice from this mailing list worked. (Almost) blatantly copied:
Locate the target/scala-2.11/src_managed and target/scala-2.11/twirl
directories in the project view, then right click and Mark Directory
As -> Generated Sources (Root).
I bumped the scala version and obviously in newer versions of IntelliJ the Root word has been added. Also, you cannot select this from the Project Structure window, the option is not available. It is possible only through the Project pane in the main window. If it refuses to be marked as Generated Sources, try to unmark thetarget directory (Mark Directory As -> Unmark ).
For people using Play 2.4.x or above, it seems that Play no longer produces reverse routing files for javascript in src_managed et al.
Instead, you need to include scala-2.xx/routes/main directory as Sources.
This question was asked a year ago, but to answer for future queries by other coders, the problem is easily solved by adding a "play.Routes" path like this
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
play.Routes.javascriptRouter("jsRoutes",
// Routes for Projects
controllers.routes.javascript.Projects.add(),
controllers.routes.javascript.Projects.delete(),
controllers.routes.javascript.Projects.rename(),
controllers.routes.javascript.Projects.addGroup()
)
);
}
Ensure that you have the proper imports to the class:
import play.mvc.*;
import play.data.*;
I am using Idea 14.1.4 community edition, i managed to remove the index and route not resolved errors by right clicking on the target folder and marking it as not excluded. NB i run my project using the command line i can not find any run configuration in the ide.
I didn't find that folders in my PLay 2.8 build, so as it was a problem with IntelliJ I found an easier solution:
https://stackoverflow.com/a/70339356/2367237

Eclipse can't find / load main class

My Eclipse (Indigo) was running just fine. I created a simple class Hello. It is placed in package cont in the folder ch13. However, when I try to run it from Eclipse I get info from Java Virtual Machine Launcher:
Could not find the main class: cont.Hello.
I tried to run other classes from this package and they run just fine (that is the classes that existed there before). However any new class I create in this package has these problems. Actually any new class I create in Eclipse runs into this problems. I decided to check how it works from the command line. It seems that the problem still exist - I get same error. I checked the path and it is C:\Program Files\Java\jdk1.7.0_02\bin, which is correct (note the other classes are running from Eclipse just fine). I tried to run with java -cp . Hello and there are some Errors produced starting with java.lang.NoClassDefFoundError: Hello (wrong name: cont/Hello). Code itself is simple:
package cont;
public class Hello {
public static void main(String[] args){
System.out.println("Hello");
}
}
How can I fix it so that my classes still run under Eclipse?
.metadata is corrupted.
Steps:
Warning: Deleting .metadata will delete all your Eclipse configurations, plugins, project setups. Make a backup before you attempt this!
Stop eclipse, delete .metadata in workspace and restart eclipse
Import Project
Run again
Removing the Run Configuration
Sometimes I have a similar problems in some pre-release versions of eclipse. For fix the error, I delete the Run Configuration. You can find that in menu Run, Run Configurations...
Then I launch the app with Alt+Shift+X, then J. If this don't work, Ctrl+F11.
Deleting the .metadata directory
In another way, the configuration settings for your current workspace may are corrupted. Those settings are in the .metadata directory in your current workspace 1. In that case, there is no other choice than delete the directory:
Close eclipse.
Delete the .metadata directory.
Start eclipse.
Import the projects.
Run the project again.
Notes
You will see that directory with File > Switch Workspace > Other...
I have solved the issue following way:
Go to Run Configuration (Right Click on Java File->Run->Run Configuration).
Go to ClassPath Tab:
Click on Advanced -> Add Folders -> Add bin directory (which has class file in it for Java source code)
Re run the code, now it will solve the issue. It worked for me
Note: This worked in the past and I received many up votes. Perhaps this is not a solution anymore - but it once was - as the eclipse version was indicated.
Problem
This can also be caused by a Java Build Path Problem.
In my case, I had a an error:
A cycle was detected in the build path of project {project}. The cycle consists of projects {x, y, z}.
This can occur when you include other projects in the build path of the project you wish to run. In fact, all the projects will fail to run with the error
Could not find the main class: Example.class
Solution
Open
Windows -> Preferences -> Java-> Compiler -> Building -> Build Path Problems
Uncheck the Abort build when build path errors occur toggle
This seems like a can of worms if you end up with other build path errors I image. So use with caution.
Note: This only works if you have a "cycle error". This error message can be found in the "Markers" tab
I found the solution to this here
Info
Java 1.8.0_152
Eclipse Photon (June 2018)
Renaming the main class should be enough (and easiest):
- Go to your class and set cursor to your class name;
- ALT + Shift + R and rename the class (build if not done automatically);
- You should be able to run it now;
- Rename the class to the old name if you want;
You must have main function in your class. Like
public class MyDataBase {
public static void main(String args[]) {
}
}
I had this same problem in a Maven project. After creating the src/test/java folder within the project the error went away.
Another tip: I initialized static fields in a wrong order - surprisingly it didn't bring up a Problem (NullPointerException?), instead Eclipse complained with exactly the message OP posted. Correcting the static initialization order made the class run-able. Example:
private static ScriptEngineManager factory = null;
private static ScriptEngine engine = null;
static {
engine = factory.getEngineByName("JavaScript");
// factory is supposed to initialize FIRST
factory = new ScriptEngineManager();
}
I found the way to fix this problem was to rename the project. If you give it a name with strange characters (in my case, :), it will have trouble locating your class. I don't know if this rule applies to numbers, but try renaming the project or making a new one and copying the files. Name it without any numbers or special characters.
I solved this error by closing the project, removing it from eclipse and then importing it again.
Might be a little simpler than to redo the whole workspace setup.
I had this issue after upgrading to the Eclipse 2019-12 release. Somehow the command line to launch the JVM got too long and I had to enable the jar-classpath option in the run configuration (right click on file -> run as -> run configs).
I read so many blogs and tried so many tricks but my problem not resolved. I was able to run the code but not able to generate the jar file. :( Sad..
But I tried something which might be very silly but worked for me and bought eclipse on trace. What I did was..
Just deleted the main method from the class. Saved it. Did undo to bring the main class back. Tada... Issue resolved...
Just one think would like to say, keep your eclipse in "Build Autometically" mode.
Move your file into a subdirectory called cont
Standard troubleshooting steps for Eclipse should include deleting and re-importing the project at some point, which when I have dealt with this error has worked.
I solved my issue by doing this:
cut the entire main (CTRL X) out of the class (just for a few seconds),
save the class file (CTRL S)
paste the main back exactly at the same place (CTRL V)
Strangely it started working again after that.
It is possible to have 2 groovy-xxx-all.jar files by excample in lib directory. which makes that an app is not running
I had the same problem, this is my solution:
I manually deleted the bin folder of the project
Then I refreshed the project which recompiled the whole project and created a new bin with all .class files
I did it because when I performed Clean(project->clean) my .class files were not getting deleted. the above solution works for me hope its useful to others.
I had the same problem.I solved with following command maven:
mvn eclipse:eclipse -Dwtpversion=2.0
PS: My project is WTP plugin
If you are using a pre-defined run configuration, go to classpath and try "Restore Default Entries". This will reconfigure the classpath for that configuration.
This worked for me finally :
RUN -> RUN CONFIGURATIONS -> DELETE THE RUN CONFIGURATION
CLOSE ECLIPSE
REOPEN ECLIPSE
CREATE RUN CONFIGURATION AGAIN.
Tadaaaa !! It works

Can I use Lombok with GWT in Development Mode?

I tried to follow the official instructions on running a lomboked GWT project in dev mode, but either I'm doing something wrong, or this doesn't work with current versions of GWT anymore?
The error I get is:
"The method setA(int) is undefined for the type MyData".
MyData is simple:
#Data
public class MyData {
private int a;
}
I'm specifying
-javaagent:/path/to/lombok.jar=ECJ
in my Eclipse Run Configuration (as a VM argument).
I also tried playing around with
-Xbootclasspath/p:/path/to/lombok.jar
, as well as starting dev mode from my ant file, etc.
The problem is, that I'm mostly just guessing how the whole setup should work, so instead of troubleshooting my poor attempts, I'd like to ask how a correct setup would look like?
You've probably got it working by now, but I can confirm it does work with GWT2.4 / Eclipse 3.7 . The only option needed is the -javaagent VM arg, and adding lombok.jar to the classpath/buildpath.
I think there's some issues when you first start to use it, to do with either the gwt-unitCache folder, and the war/WEB-INF/classes folder, clearing these is probably a good step when setting it up !
I think you've stumbled upon Issue 393. If that's the case you can try the latest edge release
Disclosure: I'm one of the project lombok developers.

Categories