comparator and conditional in Thymeleaf in one expression - spring-thymeleaf

trying to compare object to Enum and then to display proper result. I have Enum:
public enum GameStatus {
NOTPLAYED("notPlayedGame"),
PLAYED("playedGame");
private final String gameStatus;
GameStatus(String gameStatus) {
this.gameStatus = gameStatus;
}
public String toString() {
return gameStatus;
}
}
and trying like that:
<td th:text="(${g.getGameStatus()} == 'notPlayedGame')? '-' : ${g.hostScore}"></td>
but always got displayed g.hostScore result. even when adding one line earlier:
<td th:text="${g.getGameStatus()}"></td>
to compare and where the result is right one- "notPlayedGame".
so pls help me to find my oversight. how it should correctly look like???

Related

Cucumber V5-V6 - passing complex object in feature file step

So I have recently migrated to v6 and I will try to simplify my question
I have the following class
#AllArgsConstructor
public class Songs {
String title;
List<String> genres;
}
In my scenario I want to have something like:
Then The results are as follows:
|title |genre |
|happy song |romance, happy|
And the implementation should be something like:
#Then("Then The results are as follows:")
public void theResultsAreAsFollows(Songs song) {
//Some code here
}
I have the default transformer
#DefaultParameterTransformer
#DefaultDataTableEntryTransformer(replaceWithEmptyString = "[blank]")
#DefaultDataTableCellTransformer
public Object transformer(Object fromValue, Type toValueType) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.convertValue(fromValue, objectMapper.constructType(toValueType));
}
My current issue is that I get the following error: Cannot construct instance of java.util.ArrayList (although at least one Creator exists)
How can I tell cucumber to interpret specific cells as lists? but keeping all in the same step not splitting apart? Or better how can I send an object in a steps containing different variable types such as List, HashSet, etc.
If I do a change and replace the list with a String everything is working as expected
#M.P.Korstanje thank you for your idea. If anyone is trying to find a solution for this here is the way I did it as per suggestions received. Inspected to see the type fromValue has and and updated the transform method into something like:
if (fromValue instanceof LinkedHashMap) {
Map<String, Object> map = (LinkedHashMap<String, Object>) fromValue;
Set<String> keys = map.keySet();
for (String key : keys) {
if (key.equals("genres")) {
List<String> genres = Arrays.asList(map.get(key).toString().split(",", -1));
map.put("genres", genres);
}
return objectMapper.convertValue(map, objectMapper.constructType(toValueType));
}
}
It is somehow quite specific but could not find a better solution :)

ADF RichSelectOneChoice get text (label)

I'm dealing with something that seems to be a trivial task but haven't found a solution: How can I access the text on a RichSelectOneChoice? I've only found the values with richSelectOneChoice.getValue() and valueChangeEvent.getNewValue()
But, how is it possible to access the actual text?
My last attempt was this:
private RichSelectOneChoice selClaim;
public void claimTypeVCL(ValueChangeEvent ve){
Map s = selClaim.getAttributes();
Object ss = s.get(ve.getNewValue());
System.out.println(ss);
}
At the moment the console output is null for the corresponding value, no matter what the choice is.
The ADF component bound to the RichSelectOneChoice object is created as a component with inner elements.
I've also tried the solution proposed by Frank Nimphius here https://community.oracle.com/thread/1050821 with the proper object type (RichSelectOneChoice) but the if clause doesn't execute because the children are not instanceof RichSelectOneChoice as suggested but rather javax.faces.component.UISelectItem and this class doesn't include the getLabel() method and running the code actually throws a wide range of errors related either to casting an object to the target type or null pointers when trying to access the label.
Solved it using the UISelectionItem object and its getItemValue() and getItemLabel() methods instead of getLabel() or getValue(), the latter of which was available but didn't render the expected result.
The working code looks like this:
public String selectedOptionStr;
public void socClaimTypeVCL(ValueChangeEvent ve){
selectedOptionStr = "";
RichSelectOneChoice sct = (RichSelectOneChoice)ve.getSource();
List childList = sct.getChildren();
for (int i = 0; i < childList.size(); i++) {
if (childList.get(i) instanceof javax.faces.component.UISelectItem) {
javax.faces.component.UISelectItem csi = (javax.faces.component.UISelectItem) childList.get(i);
if (csi.getItemValue().toString() == ve.getNewValue().toString()) {
selectedOptionStr = csi.getItemLabel();
}
}
}
}

Jackson - serialize to other than string

I am new here and this is my first post. I recently got into touch with Jackson and i would like to know if it's possible to get other values than string (or int) while serializing. Pleae be kind if I confuse parts of the terminus.
For example: I have enum
public static enum Type {A, B, C}
in a class like
public class MyClass{
private Type charCat;
public Type getCharCat(){
return this.charCat;
}
public void setCharCat(Type t){
this.charCat = t;
}
}
But if I create an Object (for example with charCat A) and write it into a file I get
...
charCat: "A"
...
How could i get
...
charCat: A
...
?
I tried several tips and solutions, but they did not work.
I am not sure exactly what you are asking for, but the only valid kind of JSON would be
{ "charCat" : "A" }
as all textual values MUST be enclosed in double-quotes. Only values that do not need that are numbers, boolean values (true and false) and null. So serializing value as
{ charCat : A }
would not be valid JSON; so there is no way to get such output.

JSF round value from string

I have a JSF 1.2 view which is kind of a report generator.
Users can select a query, configure some values, then the database is requested and data collected.
After that the data can be viewed in a dataTable and finally is exported to Excel.
Works fine so far.
Depending on the query the columns have different types, one of which is Double.
The Double values should be rounded now...
Since there are many rows (tens or hundreds of thousands) I collect all data as String
to avoid time consuming type conversions.
That's pretty ok because for the export to Excel I need Strings, too (written to Office XML).
But now the rounding comes in. In the dataTable the doubles shall be rounded.
If I had a Double I could easily use f:convertNumber, but I don't have.
My idea would be a String converter which analyzes if it is a numeric value
and then formats the String. (Performace is not so critical because there are
only 30 or so records in the paged dataTable). How would I accomplish this?
Any (other) suggestions? Thanks!
Mark
Edit:
solved for now with
public class ReportStringConverter implements Converter {
DecimalFormat f = new DecimalFormat("#0.00");
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return value;
}
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (isNumeric(value.toString())) {
return f.format(Double.parseDouble(value.toString()));
} else {
return value.toString();
}
}
private boolean isNumeric(String s) {
try {
double d = Double.parseDouble(s);
} catch (NumberFormatException e) {
return false;
}
return true;
}
}
You could use expression language to convert a string to a number by adding 0 to it (example: #{'35.75' + 0}). This allows you to simply use f:convertNumber.
<h:outputText value="#{'35.75' + 0}">
<f:convertNumber pattern="0"/>
</h:outputText>

Custom transformation function throwing error.

This is my transformation function call:
<p><%# MyFunctions.getDocumentCategory(Eval("DocumentID"))%></p>
This is the function:
public static string getDocumentCategory(int documentID)
{
string category;
StringBuilder sb = new StringBuilder();
// Get document categories
var ds = CategoryInfoProvider.GetDocumentCategories(documentID, "CategoryEnabled = 1", null);
// Check whether exists at least one category
if (!DataHelper.DataSourceIsEmpty(ds))
{
// Loop thru all categories
foreach (DataRow dr in ds.Tables[0].Rows)
{
sb.Append(Convert.ToString(dr["CategoryDisplayName"]) + ",");
}
}
string content = sb.ToString();
category = content.Split(',')[0];
return category;
}
}
This is the error:
MyFunctions.getDocumentCategory(int) has some invalid arguments.
I've tried an alternate form of the function that accepts strings rather than ints but it throws the same error. I've verified that the Eval("DocumentID") works correctly when placed by itself. Any ideas?
Eval returns an object. You either need to convert it to an int, or change the function to accept an object, and convert that object to an int.
<p><%# MyFunctions.getDocumentCategory( Convert.ToInt32( Eval("DocumentID") ) )%></p>
OR
public static string getDocumentCategory(object document)
{
int documentID = Convert.ToInt32( document );
etc...
}
Thanks to Doozer for the nice explanation and example.
The second approach - to accept the object and make the conversion inside your custom function - may be better to keep the transformation code cleaner. The result is equal.
Just to add a little bit - you can use Kentico's ValidationHelper for conversions, for example:
transformation:
<%# MyFunctions.getDocumentCategory(Eval("DocumentID"))%>
code:
public static string getDocumentCategory(object docID)
{
int documentID = ValidationHelper.GetInteger(docID, 0); //0 is the default value
...

Resources