Jasper Reports, pass a list/array within a bean - java

I have to generate a report, that displays info about one object ( so the input is only one bean ).
The first problem is - this bean should contain lists of sub-beans( for example, comments, with comment type and comment date ). So I can pass them to a sub-report.
The second problem is - there is an array of 4 sub-beans, that contains few fields. I can create a separate field for each sub-bean's property ( firstSubBeanName, secondSubBeanName... ) , but it's ugly :(. Ideally, there should be a way to access these beans in a such way :
$F{test}[0].name
Please help.

If your list have a name (ie is a property of the object), you have just to pass as Data Source Expression for the subreport this property
$F{subBeansList}
The subreport should be ready to receive such kind of data. If you are using struts, it is possible you should use this class:
org.apache.struts2.views.jasperreports.ValueStackDataSource
as intermediary on your list field to be passed to the subreport.
The second question, the easy way is to use a list, so you can use this expression:
$F{test}.thelist.get(0)

Related

Can I add condition with spring data standard interface methods

Can I add condition to provided interface method like "findAll" of spring data? For example, if the table has columns "name" and "deleted" - I can create a query asfindByNameAndDeletedIsNull which will give all names which have not been deleted. I tried "findAllAndDeletedIsNull" but this does not work - is this possible?
I know it can be achieved with #query, but was curios as how can we augment the standard methods with conditions.
You can do "findByDeletedIsNull"
See here for more info on what key words can be used in a method name.
According to the documentation, there's a specific way to name the method to have it parsed into the correct SQL. Look at this section: Spring Data JPA reference - query.
If you have the query ready, you can easily reverse-engineer which method name may help you get the same result. You can compose quite complex queries by building up from those foundation bricks. However, you cannot just create a string representation of the "where" clause as a named method.
From the document, if you want to get all records where a field is null:
IsNull | findByAgeIsNull | … where x.age is null
will mean a method name such as findByDeletedIsNull.

How to parse OWL2 file with OWLAPI - AnnotationProperties

I have an OWL file (OWL2) that I need to parse and ultimately write the data into some file. The file contains AnnotationProperties, DataProperties, ObjectProperties and Classes.
My first aim is to try to list out the property information as much as possible. i.e. for AnnotationProperties to see if I can print out the name of the property and the "value".
Similarly, to be able to display the class details i.e. for each class, the name of the class, the properties i.e. data or object properties of the class. I'm not sure how to do this and any reading I've done so far is confusing because it seems to talk about instances, which I don't believe are present in the file. Also, the OWLAPI javadoc and documentation and such are not very helpful with the kind of methods I might have to be calling.
E.g. if I had the following AnnotationProperty:
<owl:AnnotationProperty rdf:about="&xxx;SOME_ID">
<ABC rdf:datatype="xsd;string">1235412</ABC>
</owl:AnnotationProperty>
ontology.getAnnotationPropertiesInSignature() would get me a set of AnnotationProperties and I can iterate and say property.getIRI().getFragment() to see the SOME_ID, but now how would I obtain and display the inner contents i.e. the ABC-1235412 ? Similarly, any help on how to obtain the information of a class i.e. display or show its properties and restrictions is appreciated.
The fragment you're showing does not create an annotation assertion axiom with property SOME_ID, it is instead an annotation on the property SOME_ID itself. The triple looks like this:
SOME_ID ABC "1235412"^^xsd:int
From your description of what you're trying to do, you /need/ instances - values for any property (annotation, object or data property) are expressed through assertions, i.e., axioms which refer to an individual (or instance - the two names refer to the same concept).
E.g.,
Ignazio hasAge "38"^^xsd:int
would be a data or annotation property assertion on the individual Ignazio with value 38.
To access these assertions, you can use
OWLIndividual ignazio = ...
ontology.getAnnotationAssertionAxioms(ignazio);
To access annotations like the one you show, i.e., on the annotatio property itself:
OWLAnnotationProperty some_id = ...
ontology.getAnnotationAssertionAxioms(some_id.getIRI());

what is session.selectOne(String arg0, Objectarg1);?

i am new to MyBatis,i am unable to find tutorials to learn,present i am going to start working on MyBatis with Spring,i had used session.selectOne(String arg0, Object arg1) but i am not able to understand how it works and what it will do with the second parameter that is Object arg1.
can any one help in this.
thank you
The second argument to selectOne and selectList is for a parameter. It can be a primitive if you have very simple needs in your query, say a single integer, or for more complicated queries requiring many values to be interpolated, a bean class instance with the values populated as needed (and containing the proper getters and setters).
In your mapper file you then define the type of the parameter via the parameter attribute, and can then interpolate either inline or with escaping (the former for things that should never be escaped, such as variable table or column names, and the latter for things which should always be escaped, such as values in a WHERE clause).
See the MyBatis doc for more detail:
http://mybatis.github.io/mybatis-3/java-api.html
Response to comments from OP:
MapBuilder must be custom code related to Map data structures. There's an ImmutableMap.Builder as part of Guava, but that doesn't seem like what this is. I don't think it's related to Mybatis per se.
It looks like that code is just building up a Map object, and then passing it off to the selectOne query for use within the query definition in the mapper (instead of a custom bean class).
What's the definition on LoginMapper.getUserByUsername in your mapper? In that definition, the contents of the map object are likely being interpolated into the query so dynamic values can be included.

JSF 2.0 validation and field highlighting

I am looking for some guidance/opinion on the best way forward to add field error highlighting in JSF 2.0. So far I have successfully implemented using Cagatay's example with a few minor adjustments to logic.
String styleClass = ( String ) uiInput.getAttributes().get("styleClass");
//Check the valid flag
if ( !uiInput.isValid() )
{
//Component already has a styleclass
if ( styleClass != null )
{
//check if it's already highlighted
if ( !styleClass.contains("ui-input-invalid") )
{
//if not add the error class to it
styleClass = styleClass + " ui-input-invalid";
//and put the new styleclass back on the component
uiInput.getAttributes().put("styleClass", styleClass);
}
} else
{
//no current style class so just add the error class
uiInput.getAttributes().put("styleClass", "ui-input-invalid");
}
} else //component is valid so we might need to remove a highlight
{
//component has a styleclass
if ( styleClass != null )
{
//check if it is already highlighted
if ( styleClass.contains("ui-input-invalid") )
{
//remove error class from the string
styleClass = styleClass.replace("ui-input-invalid", "");
//and put the new styleclass back on the component
uiInput.getAttributes().put("styleClass", styleClass);
}
}
}
I have also used the suggestion of adding el to each component's styleclass - styleClass="#{component.valid ? '' : 'ui-input-invalid'}".
Both methods work like a charm when used in conjunction with Bean Validation JSR303. However I also have 2 additional validation stages. 1 to validate the form as a whole i.e. correct combination of fields and 1 to validate our general business rules once the field and form validation is successful. In order for these stages to also add the highlighting I need to do some manual work. For both highlighting approaches I have to manually set the component(s) valid flag to false. To have access to the component I have bound it to its own object in the form vo. Now for Cagatay's example I need to add all of the components to a List and then pass this list to the highlighting method. If I use the styleclass approach I don't have to worry about a component list and passing to a highlighting method. This seems the better approach to me however I'm a little concerned that it is adding logic to the JSF page which is something I want to stay away from.
What do you feel is the best approach or is there another way I am not aware of? Also I assume there is no other way of setting the valid flags without binding to the component? At the moment I having to bind every component so I can set its valid flag.
It's been a while since I asked this and in the mean time we have actually partially implemented JSF into our enterprise app. The solution for the field highlighted was quite complicated and in order for it to work, be reusable and be customisable it really has to fit snuggly into a framework that encompasses JSF/Input Value Objects, associated Input Field objects and Bean Validation. Therefore someone stumbling here may not get the answer they are looking for. However I going to include an portion of our internal design docs which describes the mechanism. Hopefully this will help anyone else:
Field Highlighting and Error Messages Field highlighting in JSF
proved to be quite a complicated task. This is because the html
id/name is generated by jsf at runtime and can include many prefixes.
JSF will add a prefix to an id when it is inside a
form/tab/datatable/composite component. An id of ucn may end up
becoming tab1:contentForm:jsfDataTable:1:ucn. It is therefore
virtually impossible to try and predeterime what an id will be and
then to try and highlight. To resolve this issue a
preRenderComponentEventListener class is used. This is registered in
the facesConfig.xml along with an input type. This tells the JSF
lifecycle to run this class whenever that type of input is about to be
rendered. We then have access to the short and long ids of the input
which we can then save and look up later. The full procedure is as
follows:
Entry in facesConfig.xml registers a
preRenderComponentEventListener and the associated type of input.
Each time before the input is rendered the processEvent method is
called.
Entry in facesConfig.xml registers a HashMap called
componentMap which is used to store the input ids.
When the
processEvent method is called the Input element is retrieved. The
componentMap is retrieved and input’s id/clientID is added to the map.
The id of the input is the Key (this is the short id i.e. ucn) and the
ClientID is the value (this is the long JSF generated id i.e.
csn01Form:jsf454:ucn:1). To handle multiple inputs of the same name
like in DataTables the key is added with an Incrementing Index. E.g.
if ucn3 is already in the map ucn4 will then we added.
Once this
process is complete the componentMap will contain entries for every
input field. Therefore by using the short id the full clientID can be
retrieved.
In the BackingBean FormatValidationExceptions and
RuleExceptions are caught and handled.
FormatValidationExceptions. These derive from BeanValidation. A
subclass of an InputVO is created which contains subclasses of
Destin8Input (See CSN01InputVO). If format validation is needed on an
Input they should be annotated with a custom bean validation. E.g.
#StringCheck (See Bean Validation).
The FormatValidation class
has a method called validateFormats which takes in a type of InputVO
and runs it through the Bean Validator (when using a Transaction
Controller this method will automatically be run). The Bean Validator
will automatically take each annotated field and run the isValid()
method associated with the annotation. The #StringCheck for example
checks the value entered matches a regular expression and that the
number of characters entered is correct. Any failures will result in
a ConstraintViolation. At this point the error message is generated
using the Error Display Name from the Destin8Input. All validation
checks are performed and will result in a Set of ConstraintViolations.
In the validateFormats method the Set of ConstraintViolations is
looped round and each message is added to an Error Message List in the
ValidationFormatException. Each htmlID in error is also added to a
Field Error List.
The ValidationFormatException is caught in the
BackingBean. All Error messages are added as a FacesMessage to be
displayed at the top of the page.
RuleExceptions are similar
except messages and fields to highlight are manually added when
throwing an exception. The message code will be looked up from the
DB.
The List of ids in error is now looped round and is used to
retrieve the associated full ClientID from the componentMap. Each
ClientID is added to a List.
This List is passed to the
JSFUtils.highlightFields method where each ClientID is added to a ~
Delimited String.
This delimited String is then added to the
RequestMap with a key of ‘errors’ (this is a map automatically
available as per of each request).
This String is then retrieved
as part of the Destin8Template.xhtml -
A
javascript method called highlightFields in then immediately called.
This effectively loops through the delimited String, gets the full id
and then adds the Error css class using jQuery.
It is important to
note that the link between a Java Input and a JSF Input is the id. In
order to connect the 2 it is vital they have the same ID. This is
achieved by using the IDConstants class. This is an ENUM which
contains entries for different fields. An entry is also added to the
IDConstants managed bean which allows access via a facelet. This is
then added as the id attribute for the applicable input element.

Structural design pattern

I'm working with three separate classes: Group, Segment and Field. Each group is a collection of one or more segments, and each segment is a collection of one or more fields. There are different types of fields that subclass the Field base class. There are also different types of segments that are all subclasses of the Segment base class. The subclasses define the types of fields expected in the segment. In any segment, some of the fields defined must have values inputted, while some can be left out. I'm not sure where to store this metadata (whether a given field in a segment is optional or mandatory.)
What is the most clean way to store this metadata?
I'm not sure you are giving enough information about the complete application to get the best answer. However here are some possible approaches:
Define an isValid() method in your base class, which by default returns true. In your subclasses, you can code specific logic for each Segment or FieldType to return false if any requirements are missing. If you want to report an error message to say which fields are missing, you could add a List argument to the isValid method to allow each type to report the list of missing values.
Use Annotations (as AlexR said above).
The benefit of the above 2 approaches is that meta data is within the code, tied directly to the objects that require it. The disadvantage is that if you want to change the required fields, you will need to update the code and deploy a new build.
If you need something which can be changed on the fly, then Gangus suggestion of Xml is a good start, because your application could reload the Xml definition at run-time and produce different validation results.
I think, the best placement for such data will be normal XML file. And for work with such data the best structure will be also XMLDOM with XPATH. Work with classes will be too complicated.
Since java 5 is released this kind of metadata can be stored using annotations. Define your own annotation #MandatoryField and mark all mandatory fields with it. Then you can discover object field-by-field using reflection and check whether not initiated fields are mandatory and throw exception in this case.

Categories