toString() in Grails Java Domain Class Causes - grails

By default, grails seems to return <class name>:<id> for toString() of an Java domain object. That's not at all what I want of course, so I tried to #Override
the toString() to return what I want. When I tried grails generate-all Tagtype, I got the following error:
java.lang.LinkageError: loader constraint violation: loader (instance of <bootloader>) previously initiated loading for a differen
t type with name "org/w3c/dom/NamedNodeMap"
My code is below. Any help would be greatly appreciated.
#Entity
#Table(name = "tagtype", catalog = "tigger")
#SuppressWarnings("serial")
public class Tagtype implements Serializable {
/**
* Attribute id.
*/
private Integer id;
/**
* Attribute tagtype.
*/
private String tagtype;
/**
* Attribute regexpression
*/
private Regexpression regexpression;
. . .
#Override public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.tagtype);
return result.toString();
}
}

I've overriden toString() in Grails domain classes without any problems, so that can't be the reason. This blog suggests it could be a result of name collisions, either temporary (have you tried running "grails clean"?) or perhaps your class name Tagtype collides with some grails internals.
Another thing you could try is using different versions of Grails, especially the latest 1.1.1 if you aren't already using that. This ML post describes an identical error message that was apparently version dependant.

Related

How to populate parameter "defaultValue" in Maven "AbstractMojoTestCase"?

I have a Maven plugin that I am attempting to test using a subclass of the AbstractMojoTestCase. The plugin Mojo defines an outputFolder parameter with a defaultValue. This parameter is not generally expected to be provided by the user in the POM.
#Parameter(defaultValue = "${project.build.directory}/someOutputFolder")
private File outputFolder;
And if I use the plugin in a real scenario then the outputFolder gets defaulted as expected.
But if I test the Mojo using the AbstractMojoTestCase then while parameters defined in the test POM are populated, parameters with a defaultValue that are not defined in the POM are not populated.
public class MyPluginTestCase extends AbstractMojoTestCase {
public void testAssembly() throws Exception {
final File pom = getTestFile( "src/test/resources/test-pom.xml");
assertNotNull(pom);
assertTrue(pom.exists());
final MyMojo myMojo = (BaselineAssemblyMojo) lookupMojo("assemble", pom);
assertNotNull(myMojo);
myMojo.execute(); // Dies due to NullPointerException on outputFolder.
}
}
Further: if I define the outputFolder parameter in the POM like so:
<outputFolder>${project.build.directory}/someOutputFolder</outputFolder>
then ${project.build.directory} is NOT resolved within the AbstractMojoTestCase.
So what do I need to do to get the defaultvalue populated when testing?
Or is this a fault in the AbstractMojoTestCase?
This is Maven-3.2.3, maven-plugin-plugin-3.2, JDK 8
You need to use lookupConfiguredMojo.
Here's what I ended up using:
public class MyPluginTest
{
#Rule
public MojoRule mojoRule = new MojoRule();
#Test
public void noSource() throws Exception
{
// Just give the location, where the pom.xml is located
MyPlugin plugin = (MyPlugin) mojoRule.lookupConfiguredMojo(getResourcesFile("basic-test"), "myGoal");
plugin.execute();
assertThat(plugin.getSomeInformation()).isEmpty();
}
public File getResourcesFile(String filename)
{
return new File("src/test/resources", filename);
}
}
Of course you need to replace myGoal with your plugin's goal. You also need to figure out how to assert that your plugin executed successfully.
For a more complete example, check out the tests I wrote for fmt-maven-plugin

e4 dependency reinjection order: field vs. method

I was quite surprised to see that there is no deterministic behavior for the order in which objects get reinjected.
public class Test {
#Inject private Boolean testBool;
#Inject
public void checkNewObject(Boolean testBoolNew) {
if (!testBoolNew.equals(this.testBool)) {
System.out.println("Out of sync!");
} else {
System.out.println("In sync!");
}
}
}
And this is how I use the class:
context.set(Boolean.class, new Boolean(true));
Test test = ContextInjectionFactory.make(Test.class, context);
context.set(Boolean.class, new Boolean(false));
So, sometimes I get the output:
In sync!
In sync!
And sometimes I get:
In sync!
Out of sync!
Is this really non deterministic or am I just overseeing something?
The documentation clearly states that the injection order should be:
Constructor injection: the public or protected constructor annotated with #Inject with the greatest number of resolvable arguments is selected
Field injection: values are injected into fields annotated with #Inject and that have a satisfying type
Method injection: values are injected into methods annotated with #Inject and that have satisfying arguments
See: https://wiki.eclipse.org/Eclipse4/RCP/Dependency_Injection#Injection_Order
I'm not sure, why this doesn't work as expected in your case.
How is equals() implemented in MyContent?
Is MyContent annotated with #Creatable and or #Singleton?
As a side note: Is this a practical or just an academic problem? Why is it necessary to inject the same instance into a field and into a method on the same target-instance? If you want to have a field variable to cache the value, you can set this from the method.
If you feel this is a bug, please file it here: https://bugs.eclipse.org/bugs/enter_bug.cgi?product=Platform

GSP Accessing domain class static field

I have a domain class which contains a Class[] array. I want the contents of that array displayed
using g:select. Although I cannot find how to access those fields. I tried <%#page import="package.path.to.PropertyDefinition" %> and then
<g:select from="${PropertyDefinition.types}" name="cust_prop_type"/>
Although I am getting a very big exception of type org.codehaus.groovy.control.MultipleCompilationErrorsException
Is it possible to access that static Array without making use of a Controller class?
I am using version 2.3.7
class PropertyDefinition {
#Transient
public static final Class[] validTypes = [Integer.getClass(), String.getClass(), RefdataValue.getClass(), BigDecimal.getClass()]
.
.
.
Exception:
Caused by: java.lang.NullPointerException at
org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodGetParameterAnnotations(ReflectiveInterceptor.java:944)
at
org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:357)
at org.codehaus.groovy.ast.ClassNode.lazyClassInit(ClassNode.java:258)
at org.codehaus.groovy.ast.ClassNode.getInterfaces(ClassNode.java:353)
at
org.codehaus.groovy.ast.ClassNode.declaresInterface(ClassNode.java:945)
at
org.codehaus.groovy.ast.ClassNode.implementsInterface(ClassNode.java:925)
at
org.codehaus.groovy.ast.ClassNode.isDerivedFromGroovyObject(ClassNode.java:915)
at
org.codehaus.groovy.classgen.AsmClassGenerator.isGroovyObject(AsmClassGenerator.java:937)
at
You've declared
public static final Class[] validTypes
in PropertyDefinition but you're accessing PropertyDefinition.types in the GSP...

Java EE Qualifier annotation not picked up

I am following a simple Java EE 6 annotations video on youtube. I have created a repo on github. There is a servlet to start with that creates a greeting string using annotation.
#WebServlet(urlPatterns = {"/HelloServlet"})
public class HelloServlet extends HttpServlet {
#Inject #Formal
String greetingMessage;
...
}
The formal qualifier is defined as follows:
#Qualifier
#Retention(RUNTIME)
#Target({TYPE, METHOD, FIELD, PARAMETER})
public #interface Formal {}
And the producer is:
public class ProduceFormalGreeting {
#Produces
#Formal
public String GetFormalGreeting(){
return "Good morning !";
}
}
At compile time I get the following message from NetBeans:
Unsatisfied Dependency: No bean matches the inject point
At runtime, the string is null in the servlet.
You have to add beans.xml file to WEB-INF. Now You have bean.xml file.
In ProduceFormalGreeting u have to use javax.enterprise.inject.Produces (not javax.ws.rs.Produces)

How to internationalize a converter or renderer in Wicket?

I'm translating a web application and things are generally going smoothly with wicket:message and properties files. But Wicket always wants to have a component for looking up strings.
How can I translate converters and renderers (i.e. implementations of IConverter and IChoiceRenderer) which don't have access to any Wicket component in their methods?
So far I found one way - Application.get().getResourceSettings().getLocalizer().getString(key, null) - but I have to make the strings "global", i.e. associated with the application class. That's not nice for separation and reuse. How can I do it better?
I think you should invent you own way how to achieve this. Here in my current project we registered our own IStringResourceLoader like this:
IStringResourceLoader stringResourceLoader = new OurOwnResourceLoaderImpl();
Application.get().getResourceSettings().getStringResourceLoaders().add(stringResourceLoader);
Then for example in IChoiceRenderer we just call Application.get().getLocalizer().getString("key", null).
Inside our IStringResourceLoader we are looking for bundles (property files) with some string pattern according our own conventions.
Or you can just register localization bundle (ie. properties file) distributed inside your library's jar in Application#init through org.apache.wicket.resource.loader.BundleStringResourceLoader.
Afaik there is no standard way to do that so it's up to you what path you choose.
Updated:
I found another solution how your library/extension can register it's own localization by itself so you needn't to touch Application#init or create your own IStringResourceLoaders.
There is preregistered string resource loader org.apache.wicket.resource.loader.InitializerStringResourceLoader (see wickets default IResourceSetting implementation ie. ResourceSetting and it's constructor) which uses wicket's Initializer mechanism - see IInitializer javadoc - basically you add wicket.properties file in your jar class root (ie. it is in default/none package) and inside file there is:
initializer=i.am.robot.MyInitilizer
then i.am.robot.MyInitilizer:
public class MyInitializer implements IInitializer {
/**
* #param application
* The application loading the component
*/
void init(Application application) {
// do whatever want
}
/**
* #param application
* The application loading the component
*/
void destroy(Application application) {
}
}
and now you create your localization bundles in same package and same name as IInitializer implementation (in our example MyInitializer)
I think I found another way...
I noticed that IStringResourceLoader also has a method String loadStringResource(Class<?> clazz, String key, Locale locale, String style); (and one more parameter for variation in newer Wicket versions) which does not require a component. clazz is supposed to be a component class, but... it doesn't actually have to be :)
I was able to implement my own class MyLocalizer extends Localizer with a new method
getString(String key, Class<?> cl, IModel<?> model, Locale locale, String defaultValue)
which works in a similar way to
getString(String key, Component component, IModel<?> model, String defaultValue)
but uses the class directly instead of a component. It still uses the same properties cache and resource loaders.
Then I wrote an abstract class MyConverter implements IConverter which has a MyLocalizer getLocalizer() and a few getString methods like the Component class. Basically it does getLocalizer().getString(key, getClass(), model, locale, defaultValue), so the properties can now be attached to the converter class.
Seems to work :)
If I understand your question...
You can use package based properties that means if you put your keys/values into a property file 'package.properties' in a package. Each localized resource of any subpackage under that package returns the value associated to the requested key until you override it in another property file.
The file name is 'package.properties' in Wicket prior to 1.6.x and 'wicket-package.properties' in Wicket 1.6+
See
https://cwiki.apache.org/confluence/display/WICKET/Migration+to+Wicket+6.0#MigrationtoWicket6.0-package.propertiesrenamedtowicket-package.properties
However it works just for componet, outside the componet (when component argument is null), it is possible to use:
WicketApplication.properties (the WebApplication class is WicketApplication.class, this property file is in the same package).
applicationGlobalProperty=My Global Localized Property
wicket-package.properties (package based, place it in the same package as the page)
localText=Localized text: A local component text based on wicket-package.properties
LocalizedPage.html (markup template)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Localized Page</title>
</head>
<body xmlns:wicket="http://wicket.apache.org">
<div>
<div>
<h2>Texts</h2>
<div>
<wicket:message key="localText"/> <br/>
<span wicket:id="localizedLabel"></span>
</div>
</div>
</div>
</body>
</html>
LocalizePage.java (code)
public class LocalizedPage extends WebPage {
private static final long serialVersionUID = 1L;
public LocalizedPage() {
super();
}
#Override
protected void onInitialize() {
super.onInitialize();
add(new Label("localizedLabel", new AbstractReadOnlyModel<String>() {
private static final long serialVersionUID = 1L;
#Override
public String getObject() {
return WicketApplication.get().getResourceSettings().getLocalizer().getString("applicationGlobalProperty", null);
}
}));
}
}
See the full example on https://repo.twinstone.org/projects/WISTF/repos/wicket-examples-6.x/browse

Resources