Grails package change for domain class caused DuplicateMappingException - exception

While working through a tutorial to start learning Grails, I made a mistake and ran:
grails create-domain-class com.FooBar
instead of:
grails create-domain-class com.acme.FooBar
It was immediately obvious I had made an error so I tried the following:
Searched for a function that reverses the create-domain-class command, it seems there isn't one.
Searched for advice on the web and the consensus is that you can delete a domain class file, any associated views and tests, then to be safe run a text search for your class name in your project directory for any references you may have missed. I have done all this.
Then I ran the correct command to create com.acme.FooBar, which worked.
After this the app fails to run and reports the following error:
org.hibernate.DuplicateMappingException: duplicate import: FooBar refers to both com.acme.FooBar and com.FooBar (try using auto-import="false")
After adding the following code to com.acme.FooBar:
...
static mapping = {
autoImport false
}
...
The app now runs as expected.
However as an experienced Java developer who occasionally does refactor a package I would like to understand how to do that without causing a DuplicateMappingException or resorting to the "autoImport false" solution.
Thanks.

You shouldn't be doing
static mapping = {
autoImport false
}
As, by doing this you said that don't check for domain just by name and look up for package as well. Hence, once you do that you will have to use Fully qualified name of the class in your queries / hqls which may itch sometimes.
You should be removing the Domain completely i.e.
remove the Domain
remove the view folder creating by default with very same name and so do the controller
Now, do grails clean-all(Make it a thumb rule to use grails clean-all first for any issue unexpectedly occuring).
To be more accurate do remove target directory from your project and then do run grails run-app.
I had done very same thing many times and got it resolved by above steps.
Hope it helps.

Related

Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry

Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry
at http://127.0.0.1:8000/components/#polymer/polymer/lib/elements/dom-module.js:175:16
Tried deleting node-modules and package-lock and reinstalling did not work.
this error is due to a custom element tag-name being registered which is already registered; to fix simply check that an element by this name hasn't already been registered. This example solution checks to see if something is already registered using the existing API and if not, registers the given Class (inheriting from/extending HTMLElement--at some point):
customElements.get('the-element') || customElements.define('the-element', HTMLTheElement);
For more on the API see https://developer.mozilla.org/docs/Web/API/CustomElementRegistry
most/mature libraries address this problem and those that don't, or are mangled by package and build process complexities can have it pop up; in most cases either updating to a current version, migrating to Lit (https://lit.dev) or patching the problem somehow provides a path to a solution; note the simpler solutions are far easier to maintain--as can be seen in the conflation of npm, polymer over the actual error in the original question; the Polymer project became lit-html and LitElement, and recently rebranded as "Lit" (and still includes these lit-things). Professionally I'm migrating away from npm and Nodejs to Deno with the aim of generally resolve the many problems related to npm and tooling insecurity and complexity, however this answer provides a more direct solution (understand the problem and fix directly, or update to the relevant latest solution which includes this somehow).
Well, this worked for me, with no Typescript warnings,
if (!customElements.get('the-element')) { customElements.define('the-element', HTMLTheElement); }
Hope someone will find this useful.
Cheers.
It is unwise to use the answers above. You want it to fail! The reason being is that your NPM should be deduping duplicate packages, so the fact that you see a certain component being defined on the custom elements registry more than once is a crucial error that you need to debug why the same component is registered more than once.
How to debug, in short, go to your browser, inspect element, network tab, refresh, figure out which files are both registering the same element. Then check in the initiator to see which files are loading those files. Then you get a way better idea of why your app is not resolving the same import to a single place (your deduped dependency).
One reason why you might face this problem is due to semver. If you have multiple different major versions of the same dependency, NPM cannot just dedupe all of the installations to your root node_modules. How you solve this is up to you. Some people use npm-aliases for their different majors of a dependency, some people implement a plugin in their build-tool to resolve paths to a single installation, etc.
For people that can't use #jimmonts answer because the issue is in one of their dependencies you can use the following snippet:
This happens for us, because a package we are using defines an element. But this package is used by multiple apps. And these apps, wouldn't you know it, interact. So customElements.define('x-tag', className) gets called multiple times. And the second time it does, it crashes the app.
function safeDecorator(fn) {
// eslint-disable-next-line func-names
return function(...args) {
try {
return fn.apply(this, args);
} catch (error) {
if (
error instanceof DOMException &&
error.message.includes('has already been used with this registry')
) {
return false;
}
throw error;
}
};
}
customElements.define = safeDecorator(customElements.define);
I was getting the same error. You may not have the same issue as me but I thought I would drop my solution here just incase someone runs into the same issue in the future.
I had two modules that both imported the same custom element module, one of the was importing Module.js and the other module.js. Now the browser saw this as two separate files because URLs can be case sensitive, except my server saw this as one file because it is not case sensitive (express.js) or at least it was able to resolve the path to the correct file even with the incorrect case. And so the browser saw two "different" modules both defining the same custom element, but when I searched my source code only one file was defining the custom element.
I had this problem and found out that I was calling on my boundle.js file twice. Since I was using Webpack and HtmlWebpackPlugin, HtmlWebpackPlugin added the reference to my boundled file to my index.html file where I had already referenced it by hand.
I developed a solution, thats overrite the define with a precheck before define. It works fine for me, just ad the 2 lines into your index.js
customElements.defineclone = Object.assign(Object.create(Object.getPrototypeOf(customElements)).define, customElements);
customElements.define = (name, element) => customElements.get(name) || customElements.defineclone(name, element);

Not able to use built-in models i.e. "user", error: no response from server

I have created many models in loopback for my project. And use these models with the help of "http://localhost:3000/explorer" in my browser.
These model API's are working fine. But, whenever I tried to use built-in models i.e "user" from the explorer. I got the below error:
and in the terminal. I got the below error. And terminal command automatically terminates.
I am new in the loopback. Why am I not able to use built-in models "user".
Please, help me.
Thanks in advance.
To anyone else that encounters this, I ran into this today and found this question unanswered, so I will do my best to give my explanation and findings here.
The error, roleModel.isInRole is not a function, means simply that the role model does not have a function called isInRole.
In my case, this was because another model was automatically generated from an existing database table called Role, which overrode the internal Role model of Loopback.
When the internal Role model is overridden, the isInRole function is not inherited automatically and will result in the above error.

How to have class loaded without using "use" but call it as if I used it

I have studied these 2 sources, but none of those works for me.
http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html
Yii2 - How do I AutoLoad a custom class?
I have created custom helper class which I want to include in every model, controller and view in my application. I am using Yii2 advanced app version 2.0.11, IDE I am using is PHPStorm
QUESTION:
What I want to achieve is to not use use keyword at the beggining of every class but still be able to simply call AppHelper::myMethod() in models, controllers and views.
How is that possible?
Closest I got it working was using this solution https://stackoverflow.com/a/35160997/5395463
All other solutions did not work for me. I am getting errors like:
PHP Fatal Error – yii\base\ErrorException
Class 'frontend\controllers\AppHelper' not found
when I simply dont include use commons\commands\AppHelper;
or when not using namespace as they suggest there with other settings:
Fatal error: Uncaught exception 'yii\base\UnknownClassException'
with message 'Unable to find 'common\commands\AppHelper'
in file: C:\xampp\htdocs\domain.com\web\common/commands/AppHelper.php.
Namespace missing?' in ...
SOLUTION:
Thanks for your responses, I got it working finaly. https://stackoverflow.com/a/42330631/5395463 solution works best for me.
So I removed namespace from that class, but left it in common\commands folder, added require to frontend/web/index.php and backend/web/index.php files (not sure if I should add it to yii file in root too, I didnt, so far it is working good anyways), and changed calls of class from AppHelper::myMethod() to \AppHelper::myMethod() looks like eveything is working now.
In Yii2 You can use an explicit way adding \ to full namespaced name
\frontend\controllers\AppHelper
so you can sue your method
\frontend\controllers\AppHelper::yourMethod();
Solution for not lazy coders:
create component with your class so you can use it like \Yii::$app->my_component
if even this is too much and your IDE is better than Windows Notepad prepare macro that will print this for you
Solution for lazy coders:
Save your class in single PHP file without namespace.
Modify you entry script to include this class - i.e. for Basic Project Template it's /web/index.php; add there
require(__DIR__ . '/path/to/MyClass.php');
For Advanced Project Template modify it properly.
Now you can use your class by calling it like \MyClass (yes, \ is required and yes, your IDE probably will modify it anyway to MyClass with use MyClass; added at the beginning.

Yii2 class not found when moving application to live server

My application works perfectly locally however upon uploading to live server there's a couple of issues.
The first one is I get the following error on one specific page of my application but not on other that user the same class.
Class 'yii\helpers\url' not found
The above error is found even though I have the below line at the top of my view file.
use yii\helpers\url;
The other issue I get is when trying to locate a record within my Seo table using my Seo model however this error again only occurs on one part of my application but not the other part that uses the same table/model. Below is the error I get:
Class 'common\models\seo' not found
When I use the following line (I can confirm table relations work and the necessary data is their)
$seo = Seo::find()->where(['id' => $model->seo_id])->one();
use yii\helpers\url;
change to
use yii\helpers\Url;
The same way seo class name will be started using capital case
Seo

MEF: "Unable to load one or more of the requested types. Retrieve the LoaderExceptions for more information"

Scenario: I am using Managed Extensibility Framework to load plugins (exports) at runtime based on an interface contract defined in a separate dll. In my Visual Studio solution, I have 3 different projects: The host application, a class library (defining the interface - "IPlugin") and another class library implementing the interface (the export - "MyPlugin.dll").
The host looks for exports in its own root directory, so during testing, I build the whole solution and copy Plugin.dll from the Plugin class library bin/release folder to the host's debug directory so that the host's DirectoryCatalog will find it and be able to add it to the CompositionContainer. Plugin.dll is not automatically copied after each rebuild, so I do that manually each time I've made changes to the contract/implementation.
However, a couple of times I've run the host application without having copied (an updated) Plugin.dll first, and it has thrown an exception during composition:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions for more information
This is of course due to the fact that the Plugin.dll it's trying to import from implements a different version of IPlugin, where the property/method signatures don't match. Although it's easy to avoid this in a controlled and monitored environment, by simply avoiding (duh) obsolete IPlugin implementations in the plugin folder, I cannot rely on such assumptions in the production environment, where legacy plugins could be encountered.
The problem is that this exception effectively botches the whole Compose action and no exports are imported. I would have preferred that the mismatching IPlugin implementations are simply ignored, so that other exports in the catalog(s), implementing the correct version of IPlugin, are still imported.
Is there a way to accomplish this? I'm thinking either of several potential options:
There is a flag to set on the CompositionContainer ("ignore failing imports") prior to or when calling Compose
There is a similar flag to specify on the <ImportMany()> attribute
There is a way to "hook" on to the iteration process underlying Compose(), and be able to deal with each (failed) import individually
Using strong name signing to somehow only look for imports implementing the current version of IPlugin
Ideas?
I have also run into a similar problem.
If you are sure that you want to ignore such "bad" assemblies, then the solution is to call AssemblyCatalog.Parts.ToArray() right after creating each assembly catalog. This will trigger the ReflectionTypeLoadException which you mention. You then have a chance to catch the exception and ignore the bad assembly.
When you have created AssemblyCatalog objects for all the "good" assemblies, you can aggregate them in an AggregateCatalog and pass that to the CompositionContainer constructor.
This issue can be caused by several factors (any exceptions on the loaded assemblies), like the exception says, look at the ExceptionLoader to (hopefully) get some idea
Another problem/solution that I found, is when using DirectoryCatalog, if you don't specify the second parameter "searchPattern", MEF will load ALL the dlls in that folder (including third party), and start looking for export types, that can also cause this issue, a solution is to have a convention name on all the assemblies that export types, and specify that in the DirectoryCatalog constructor, I use *_Plugin.dll, that way MEF will only load assemblies that contain exported types
In my case MEF was loading a NHibernate dll and throwing some assembly version error on the LoaderException (this error can happen with any of the dlls in the directory), this approach solved the problem
Here is an example of above mentioned methods:
var di = new DirectoryInfo(Server.MapPath("../../bin/"));
if (!di.Exists) throw new Exception("Folder not exists: " + di.FullName);
var dlls = di.GetFileSystemInfos("*.dll");
AggregateCatalog agc = new AggregateCatalog();
foreach (var fi in dlls)
{
try
{
var ac = new AssemblyCatalog(Assembly.LoadFile(fi.FullName));
var parts = ac.Parts.ToArray(); // throws ReflectionTypeLoadException
agc.Catalogs.Add(ac);
}
catch (ReflectionTypeLoadException ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}
CompositionContainer cc = new CompositionContainer(agc);
_providers = cc.GetExports<IDataExchangeProvider>();