Intellij - Private final string somehow null - variables

I have the following line in my class:
public class myClass {
private final String MY_VAR = "PY-PP";
...
}
But somehow whenever I inspect my code in debug, that variable is null, it is not being used anywhere except in 1 place to read, any ideas?
I have tried invalidating caches, rebuilding whole project and redeploying the server with no luck, this is a brand new intellij install as well.

Related

IntelliJ IDEA: Unnecessary space after reformatting

I'm new to IntelliJ and need some help for some issue when I'm reformatting the code.
For example, let's say I have this code which is ,at first, written in other IDE(Eclipse).
#Service
public class TestService {
private Logger logger = LoggerFactory.getLogger(getClass());
//...
}
If I reformat code(cmd+option+L)...
#Service
public class TestService {
____private Logger logger = LoggerFactory.getLogger(getClass());
//...
}
IntelliJ somehow generates some silly empty spaces that make git to think something changed.
I'm currently using the most recent version of IntellJ on M1 Mac. I also did import Eclipse code style into IntelliJ. Is there any configuration to resolve this problem?
Probably your tab characters were auto-replaced by space characters because that is IntelliJ defaults.
Go to "Preferences | Editor | Code Style | Java" and click "Use tab character" to keep your tabs.

How to use WebApplicationFactory in .net6 (without speakable entry point)

In ASP.NET Core 6 default template moves everything from Sturtup.cs into Program.cs, and uses top-level statements in Program.cs, so there's no more (speakable) Program class ether.
That looks awesome, but now, I need to test all of this. WebApplicationFactory<T> still expects me to pass entry-point-class, but I cannot do this (due to it's name now being unspeakable).
How integration tests are expected to be configured in ASP.NET Core 6?
Note that if you are trying to use xUnit and its IClassFixture<T> pattern, you will run into problems if you just use the InternalsVisibleTo approach. Specifically, you'll get something like this:
"Inconsistent accessibility: base class WebApplicationFactory<Program> is less accessible than class CustomWebApplicationFactory."
Of course you can solve this by making CustomWebApplicationFactory internal but it only moves the problem as now your unit test class will give the same error. When you try to change it there, you will find that xUnit requires that tests have a public constructor (not an internal one) and you'll be blocked.
The solution that avoids all of this and allows you to still use IClassFixture<Program> is to make the Program class public. You can obviously do this by getting rid of the magic no class version of Program.cs, but if you don't want to completely change that file you can just add this line:
public partial class Program { } // so you can reference it from tests
Of course once it's public you can use it from your test project and everything works.
As an aside, the reason why you typically want to prefer using IClassFixture is that it allows you to set up your WebApplicationFactory just once in the test class constructor, and grab an HttpClient instance from it that you can store as a field. This allows all of your tests to be shorter since they only need to reference the client instance, not the factory.
Example:
public class HomePage_Get : IClassFixture<CustomWebApplicationFactory>
{
private readonly HttpClient _client = new HttpClient();
public HomePage_Get(CustomWebApplicationFactory factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task IncludesWelcome()
{
HttpResponseMessage response = await _client.GetAsync("/");
response.EnsureSuccessStatusCode();
string stringResponse = await response.Content.ReadAsStringAsync();
Assert.Contains("Welcome.", stringResponse);
}
}
Finally note that Damian Edwards' MinimalAPIPlayground was updated to use this approach after we discussed the issue. See this commit
The problem is was solved on ASP.NET Core RC1, but as of now (September 20, 2021) the docs are incomplete.
The compiler generates a Program class behind the scenes that can be used with WebApplicationFactory<>. The class isn't public though so the InternalsVisibleTo project setting should be used.
Damien Edwards' Minimal API sample uses the latest nightly bits. The test web app class is declared as :
internal class PlaygroundApplication : WebApplicationFactory<Program>
{
private readonly string _environment;
public PlaygroundApplication(string environment = "Development")
{
_environment = environment;
}
protected override IHost CreateHost(IHostBuilder builder)
{
...
In the application project file,InternalsVisibleTo is used to make the Program class visible to the test project:
<ItemGroup>
<InternalsVisibleTo Include="MinimalApiPlayground.Tests" />
</ItemGroup>
RC1 is feature complete and, judging by previous major versions, it will probably be the first version to have a Go Live license, which means it's supported in production.
I tried
<InternalsVisibleTo Include="MinimalApiPlayground.Tests" />
but no cigar! Removed it and added a partial class to program.cs
#pragma warning disable CA1050 // Declare types in namespaces
public partial class Program
{
}
#pragma warning restore CA1050 // Declare types in namespaces
amazingly it worked.

How to get hold of AutomatedInstallData within IzPack 5 InstallerListener methods?

I've tried to find any info on that but failed, maybe someone here can help.
I'm using IzPack 5 since couple of weeks and that's what I started with, so I have no prior IzPack 4 experience.
What I want to do is the following:
Give the user an opportunity to select data directory via
UserInputPanel (works fine)
Validate the entry by checking if the
database already resides there (works fine)
Depending on whether
the DB already exists and if "force" flag specified on the
UserInputPanel create the database after the packs have been
installed
This last step, that's what I can't see how to do.
I hava a java class that implements InstallerListener interface:
public class IzPackInstaller implements com.izforge.izpack.api.data.DynamicInstallerRequirementValidator,
com.izforge.izpack.api.event.InstallerListener {
It's the same class I use for both data validation / db existance check on step 2 and creation on step 3, just for convinience reasons, but it shouldn't matter
I override
#Override
public void afterInstallerInitialization(AutomatedInstallData data)
throws Exception {
System.out.println("Called afterInstallerInitialization");
System.out.println("db.location=" + data.getVariable("db.location"));
System.out.println("db.force.creation=" + data.getVariable("db.force.creation"));
}
but it seems to be deprecated alltogether and is never called in runtime - checked with System.out's.
The same is valid for:
#Override
public void afterPacks(AutomatedInstallData data,
AbstractUIProgressHandler handler) throws Exception {
System.out.println("Never called!");
}
I also override
#Override
public void afterPacks(List<Pack> packs, ProgressListener listener) { }
which is called allright, but how to get hold of AutomatedInstallData within this method? Or how else can I read installer variables at this stage?
I thought of creating a singleton, which I would initialize with the variables during DynamicInstallerRequirementValidator.validateData() call and get the variables at a later point in time, but it's ugly and sounds like a nasty workaround - there should be a way to implement InstallerListener interface and be able to use the variables, shouldn't it?
I'd be really grateful for any hints...
Anton
This is not a very clean solution but there is a way to get a hold of AutomatedInstallData really anywhere in running izpack java without actually overriding some method etc. I would just not suggest it in the first place because it is a little tricky :)
public class Test {
InstallerContainer container = new ConsoleInstallerContainer();
AutomatedInstaller automatedInstaller = container.getComponent(AutomatedInstaller.class);
AutomatedInstallData installData;
public Test() throws IllegalAccessException, NoSuchFieldException {
Field f = AutomatedInstaller.class.getDeclaredField("installData");
f.setAccessible(true);
installData = (AutomatedInstallData)f.get(automatedInstaller);
}
etc...
Now you will have access to the object AutomatedInstallData and its methods.

Lombok prefix configurations in Android Studio

I'm using Lombok to generate accessor methods. I have my lombok.config file in module/src/main/java directory. The config file looks like this.
lombok.accessors.prefix += m
config.stopBubbling = true
I have the following in my code.
#Setter String mRoute;
This seems to generate the function getMRoute() instead of getRoute().
I've tried changing the location of the lombok.config file, and even installed the Lombok Plugin for IntelliJ.
Adding #Accessors(prefix = "m") before the class declaration fixes the issue.
#Accessors(prefix = "m")
public class MyClass {
#Getter private int mNum;
}
will generate getNum() instead of getMNum()
I think Android Studio is based on IntelliJ IDEA, and does not yet support lombok.config files.

MEF Child Container Module Not Initializing

I have a simple container hierarchy with a parent container which is defined in the Shell MEFBootstrapper using a Directory catalog, and child container(s) which get created off the parent with a distinct catalog.
My child containers also use DirectoryCatalog (different path than parent), and I can see that the container has assembly and part information during runtime.
However, the Initialize() method for the modules located in the child containers are never called.
My goal is to use the child containers as session constructs, allowing the user to create new sessions and toggle between them. But if I cannot get the constituent modules to initialize (and place their views into the regions), I am kind of stuck.
I had thought to raise an event from my session manager using event aggregator to allow the modules to listen for the event and self-initialize, but that doesn't seem to work either.
i. Why isn't Initialize getting called on modules loaded into a child container
ii. How can I "trigger" Initialize from the container instance (outside of the module context?) Can you iterate over the assemblies in the container and trigger Initialize that way???
[from MefBootstrapper in shell project]
protected override DependencyObject CreateShell()
{
ExportProvider ep = this.Container as ExportProvider;
this.Container.ComposeExportedValue(ep);
[from the service that manages my sessions (containers)]
[ImportingConstructor]
public SessionService(ExportProvider provider)
{
[constructor for new sessions (containers)]
private void Init(ComposablePartCatalog catalog, ExportProvider provider, string name, int callId, bool useContextProxy)
{
this._Name = name;
this._CallID = callId;
this.startTime = DateTime.Now;
this.appHost = new CompositionContainer(catalog, new ExportProvider[] { provider });
}
=====
Was asked to include my module code whose initialize method is not called (despite being loaded into the container in question...I can even lazy instantiate the module, but calling Initialize() directly causes the injection operation to fail in the method proper.
namespace Module1
{
//, InitializationMode = InitializationMode.OnDemand
[ModuleExport("Module1.ModuleInit", typeof(Module1.ModuleInit))]
public class ModuleInit : IModule
{
private readonly IRegionManager _regionManager;
public IServiceLocator _serviceLocator;
[ImportingConstructor]
public ModuleInit(IRegionManager regionManager, IServiceLocator serviceLocator)
{
_regionManager = regionManager;
_serviceLocator = serviceLocator;
}
#region IModule Members
public void Initialize()
{
// Use View Discovery to automatically display the MasterView when the TopLeft region is displayed.
_regionManager.RegisterViewWithRegion(RegionNames.TopLeftRegion, () => _serviceLocator.GetInstance<MasterView>());
}
#endregion
}
}
I downloaded your code and had a look at it. I immediately found the problem. The bootstrapper is actually getting exports thanks to a DirectoryCatalog like this:
DirectoryCatalog catalog = new DirectoryCatalog(".");
this.AggregateCatalog.Catalogs.Add(catalog);
This means that you will get the exports from the assemblies in this directory. So you simply need to copy all the the assemblies with the exported types in the directory ".", that is to say the executing directory (Debug/bin).
Just copy Module1 and Module2 in the bin directory and everthing will compose gracefully :)
Actually I found that the post-build events supposed to copy the modules in the bin directory were not working. Maybe because your renamed something. So if you want it automatically copy the assemblies after building just replace the actual post-build event by this one:
copy "$(TargetDir)\$(TargetFileName)" "$(TargetDir)\..\..\..\Shell\bin\$(ConfigurationName)\"
I already had this problem many times and resolving it is really simple.
Remove the constructor from the your module. Prism modules are not activated the same way it does for classical exported types, therefore modules cannot use ImportingConstructor to import the services you need. Instead intitialize them with the ServiceLocator within the Initialize method.
This will work:
[ModuleExport("Module1.ModuleInit", typeof(Module1.ModuleInit))]
public class ModuleInit : IModule
{
private readonly IRegionManager _regionManager;
public void Initialize()
{
_regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
_regionManager.RegisterViewWithRegion(RegionNames.TopLeftRegion, () => _serviceLocator.GetInstance<MasterView>());
}
}
I also think that this behavior is kind of disturbing.
I had this same problem where my modules Initialize() method was not being called... I realized I had left off the "override" keyword on my Initialize method that was declared virtual in the Module base class that all of my modules inherit from... added "override" and it worked!