How to get all Enum values in XMLBeans? - java

Apache XMLBeans can be used to generate Java classes and interfaces from XML Schema Definition files (XSD). It also generates Enums based on StringEnumAbstractBase and StringEnumAbstractBase.Table to represent domain values. They are handy for entering only valid values. However, I want to get all those values to generate a JCombobox, a JTable or a html table.
Is there a XMLBeans API call to get all Enum values from a generated class?
Is the only choice available some sort of Java reflection?
Thanks

This worked for me:
for (int i = 1; i <= MyEnum.Enum.table.lastInt(); i++)
{
System.out.println(MyEnum.Enum.forInt(i));
}

Here is another way to get it :
public static List<String> getEnumValueList(XmlString xmlString){
List<String> values = new ArrayList<String>();
SchemaStringEnumEntry valArr[] = xmlString.schemaType().getStringEnumEntries();
for(SchemaStringEnumEntry val : valArr){
values.add(val.getString());
}
return values;
}
So, to get the list of enum values of ModelType, I do the following :
getEnumValueList(ModelType.Factory.newInstance());

Related

Simple way to map csv-table to json with different property-names than csv-headers with gson?

I have got some csv-files, which I want to transform into a json.
Unfortunately the structure of the csv doesn't match the desired json format. a) because csv is a flat structure and the json should be of nested structure. b) because the column headers don't match the json property names.
Illustrating minimal example CSV:
ColumnNameX,ColumnNameY,ColumnNameZ
valueX,valueY,valueZ
should be transformed into this JSON:
{
"XZObject": {
"absurdlyNotNamedLikeCsvHeading": "valueX",
"AlsoNOTColumnNameZ": "valueZ" },
"YyyyyWhy": {
"ThisResemblesColumnNameY": "valueY"
}
I would naively go and make some representing POJO-classes and put in the values by position – like so (pseudocode):
class Container {Fields:XZObject,YyyyyWhy}
class XZObject {Fields:absurdlyNotNamedLikeCsvHeading,AlsoNOTColumnNameZ}
class YyyyyWhy {Fields:ThisResemblesColumnNameY}
new XZObject(absurdlyNotNamedLikeCsvHeading=csvLineElements[0],AlsoNOTColumnNameZ=csvLineElements[2])
new YyyyyWhy(ThisResemblesColumnNameY=csvLineElement[1])
new Container(XZObject,YyyyyWhy)
…then I'd transform the Container object to JSON with gson.
The problem is, when a field in the CSV gets added to the scheme, I'd have to adjust every positional mapping after the new column.
So I wonder: Is there a simple way to map CSV-columns by header to a specific JSON property? Preferably with gson-lib.
In other words: Can I i.e. map the value in column with header "ColumnNameZ" to property "XZobject.AlsoNOTColumnNameZ" in a simple way?
I think parsing the CSV file into Objects is the good way to go.
You can read the first column first, split it and calculate the index of each column at runtime. Then it doesn't matter if you add/remove or shuffle columns
Assuming you read the first line and you have
String firstRow = "ColumnNameX,ColumnNameY,ColumnNameZ";
Parse it this way:
List<String> columnList = Arrays.asList(firstRow.split(","));
int COLUMN_NAME_X_INDEX = columnList.indexOf("ColumnNameX");
int COLUMN_NAME_Y_INDEX = columnList.indexOf("ColumnNameY");
int COLUMN_NAME_Z_INDEX = columnList.indexOf("ColumnNameZ");
Than use your newly found indexes:
XZObject xzObject = new XZObject(csvLineElements[COLUMN_NAME_X_INDEX], csvLineElements[COLUMN_NAME_Z_INDEX]);
YyyyyWhy yyyyyWhy = new YyyyyWhy(csvLineElements[COLUMN_NAME_Y_INDEX]);
Container container = new Container(XZObject,YyyyyWhy);

How to use Sum SQL with Spring Data MongoDB?

I want to sum the values of a column price.value where the column validatedAt is between startDate and endDate.
So I want a BigInteger as a result (the sum value).
This is what I tried:
final List<AggregationOperation> aggregationOperations = new ArrayList<>();
aggregationOperations.add(Aggregation.match(where("validatedAt").gte(startDate).lt(endDate)));
aggregationOperations.add(Aggregation.group().sum("price.value").as("total"));
final Aggregation turnoverAggregation = Aggregation.newAggregation(OrderEntity.class, aggregationOperations);
return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, BigInteger.class).getUniqueMappedResult();
This doesn't work. I have this error:
{"exception":"com.application.CommonClient$Builder$6","path":"/api/stats/dashboard","message":"Failed to instantiate java.math.BigInteger using constructor NO_CONSTRUCTOR with arguments ","error":"Internal Server Error","timestamp":1493209463953,"status":500}
Any help?
You don`t need to add a new pojo for just for this. It is helpful when you more fields to map and you want spring to map them automatically.
The correct way to fix the problem is to use BasicDBObject because MongoDB stores all values as key value pairs.
return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, BasicDBObject.class).getUniqueMappedResult().getInt("total");
Sidenote: You should use Double/BigDecimal for monetary values.
I resolved this problem by creating a class that has a BigInteger attribute:
private class Total {
private int total;
}
return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, Total.class).getUniqueMappedResult();

Best way to save some data and then retrieve it

I have a project where I save some data coming from different channels of a Soap Service, for example:
String_Value Long_timestamp Double_value String_value String_value Int_value
I can have many lines (i.e. 200), with different values, like the one above.
I thought that I could use an ArrayList, however data can have a different structure than the one above, so an ArrayList maybe isn't a good solution in order to retrieve data from it.
For example above I have, after the first two values that are always fixed, 4 values, but in another channel I may have 3, or 5, values. What I want retrieve data, I must know how many values have a particular line, and I think that Arraylist doesn't help me.
What solution could I use?
When you have a need to uniquely identify varying length input, a HashMap usually works quite well. For example, you can have a class:
public class Record
{
private HashMap<String, String> values;
public Record()
{
// create your hashmap.
values = new HashMap<String, String>();
}
public String getData(String key)
{
return values.get(key);
}
public void addData(String key, String value)
{
values.put(key, value);
}
}
With this type of structure, you can save as many different values as you want. What I would do is loop through each value passed from Soap and simply add to the Record, then keep a list of Record objects.
Record rec = new Record();
rec.addData("timestamp", timestamp);
rec.addData("Value", value);
rec.addData("Plans for world domination", dominationPlans);
You could build your classes representing the entities and then build a parser ... If it isn't in a standard format (eg JSON, YAML, ecc...) you have no choice to develop your own parser .
Create a class with fields.
class ClassName{
int numberOfValues;
String dataString;
...
}
Now create an ArrayList of that class like ArrayList<ClassName> and for each record fill that class object with numberOfValues and dataString and add in Arraylist.

How to pass a list of values into a crystal report

I have a list of integer values(employee IDs) which i need to pass to a Crystal Report.
I am using a Action class to pass these values.
So far i have succeeded with passing a single value but i couldn't find a way to pass a list of values.
Fields fields = new Fields();
Values vals1 = new Values();
ParameterFieldDiscreteValue pfieldDV1 = new ParameterFieldDiscreteValue();
pfield1.setName("fromDate");
pfieldDV1.setValue(start_Date);
vals1.add(pfieldDV1);
pfield1.setCurrentValues(vals1);
fields.add(pfield1);
CrystalReportViewer viewer = new CrystalReportViewer();
//some code to set CrystalReportViewer settings
viewer.setParameterFields(fields);
By this way i was able to get the fromDate value into the Crystal Report.
Does any one know how to get a this kind of list
int employeeList[]
Or a
String[] empListOptions
Thanks in advance.
foreach (string in string_array)
{
param.Value = string;
report.ParameterFields[parameter].CurrentValues.Add(param);
}
Found here: http://www.logicaltrinkets.com/wordpress/?p=227

Multiple values in java.util.Properties

It seems that java.util.Properties assumes one value per propery key. That is,
foo=1
foo=2
is not expected,
Is there a class for this kind of multi-value property sheet, which also provides the load method?
Try:
foo=1,2
String[] foos = properties.getProperty("foo").split(",");
The java.util.Properties function is pretty limited. If you want support list, you might want try PropertyConfiguration from Apache Commons Configuration,
http://commons.apache.org/configuration/userguide/howto_properties.html#Using_PropertiesConfiguration
With it, you can set any delimiters to your list and it will split for you automatically. You can also do other fancy things in properties file. For example,
foo=item1, item2
bar=${foo}, item3
number=123
You can retrieve it like this,
Configuration config = new PropertiesConfiguration("your.properties");
String[] items = config.getStringArray("bar"); // return {"item1", "item2", "item3"}
int number = config.getInt("number", 456); // 456 is default value
Correct answer by Nick.
Or, if you can give a different subname to each value, you could have your properties be:
my.properties
foo.title=Foo
foo.description=This a big fat foo.
This won't provide the load method but a place to store them you could use a apache commons multivaluemap:
"A MultiValueMap decorates another map, allowing it to have more than one value for a key. "
This is often a requirement for http request parameters...
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiValueMap.html
If you have a more complex example you might use the following:
# pairs of properties
source1=foo
target1=bar
source2=anotherFoo
target2=regardingBar
source3= ...
In your code you will have to search:
Map<String, String> myMap = new HashMap<>();
for (int i=1; i<max; i++) {
String source = properties.get("source" + i);
String target = properties.get("target" + i);
if (source == null || target == null) {
break;
}
myMap.put(source, target);
}
Drawback: updating the properties file. If you remove values *2, all the following values will not be added. To improve you might want to replace the break with a continue and stick to a maximum of allowed pairs.

Categories