Formatting decimal numbers with Codename One - codenameone

Codename One does not allow me to use DecimalFormat. So how do I work around this code:
private final static DecimalFormat balanceFormatter = new DecimalFormat("0.00");
private final String GetWalletBalanceEndpoint = "wallet/balance";
public GetWalletBalance() {
super();
endpoint = GetWalletBalanceEndpoint;
}
public final Double getBalance() {
Map<String, Object> balanceMap = getResponseData();
Double balance = (Double) balanceMap.get("balance");
return balance;
}
public String getBalance2DecimalsString() {
Double balance = getBalance();
return balanceFormatter.format(balance);
}

You can format decimals in Codename One using the L10NManager
private final L10NManager lnm = L10NManager.getInstance();
private final String GetWalletBalanceEndpoint = "wallet/balance";
public GetWalletBalance() {
super();
endpoint = GetWalletBalanceEndpoint;
}
public final String getBalance() {
Map<String, Object> balanceMap = getResponseData();
return lnm.format(Double.parseDouble(balanceMap.get("balance").toString), 2);
}
Note that values will be formatted based on the device localization. Some countries write 10.34 as 10,34, this format will be followed. You can force a particular country's format by setting the localization before formatting:
lnm.setLocale("US", "EN");

Related

Cant access nested list in Json response

Im trying to access some list items from a json response using retrofit but cant seem to be able to access using get method. The ListQuotes seems to be saying null
#JsonPropertyOrder({
"page",
"last_page",
"quotes"
})
public class ListQuoteResponse {
#JsonProperty("quotes")
private List<Quote> quotes = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public ListQuoteResponse() {
}
#JsonProperty("quotes")
public List<Quote> getQuotes() {
return quotes;
}
#JsonProperty("quotes")
public void setQuotes(List<Quote> quotes) {
this.quotes = quotes;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
But when I open the Quote class I am unable to access any of the properties
public class Quote {
#JsonProperty("id")
private Integer id;
#JsonProperty("dialogue")
private Boolean dialogue;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public Quote() {
}
#JsonProperty("id")
public Integer getId() {
return id;
}
#JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
#JsonProperty("dialogue")
public Boolean getDialogue() {
return dialogue;
}
#JsonProperty("dialogue")
public void setDialogue(Boolean dialogue) {
this.dialogue = dialogue;
}
I tried using
listQuoteBodyResponse.body().getQuotes() but that only returned random numbers and when I tried using the Quote class for the response directly like
QuoteResponse.body.getDialogue() its just returning null

flink how to convert the result of JDBCInputFormat to DataSet of Tuple type

I am having following code to get data from jdbc:
DataSet dbData =
env.createInput(
JDBCInputFormat.buildJDBCInputFormat()
.setDrivername(bdpService.getDriver(dataSource))
.setDBUrl(dbUrl)
.setQuery(sql)
.setUsername(dataSource.getUsername())
.setPassword(dataSource.getPassword())
.setRowTypeInfo(new RowTypeInfo(getTypes(transInfo)))
.finish(), getTypes(transInfo));
then i would like to take Tuple type operation on the dataset, like groupBy, etc.
but it is of type Row, how can I convert it, or any other ways to achive this get data from jdbc into the DataSet type?
thanks you very much.
I solved it as following:
public static class RowToTupleMapper implements ResultTypeQueryable, MapFunction<Row, Tuple>{
private Class tupleClass;
private TypeInformation[] typeInformations;
public RowToTupleMapper(Class tupleClass, TypeInformation[] typeInformations){
this.tupleClass = tupleClass;
this.typeInformations = typeInformations;
}
#Override
public Tuple map(Row value) throws Exception {
Tuple tuple = (Tuple)tupleClass.getDeclaredConstructor().newInstance();
for (int i = 0; i < value.getArity(); i++) {
Object obj = value.getField(i);
tuple.setField(obj, i);
}
return tuple;
}
#Override
public TypeInformation getProducedType() {
return new TupleTypeInfo(typeInformations);
}
}
using this helper class like this:
final String tupleClassName = "org.apache.flink.api.java.tuple.Tuple" + transInfo.getSelects().size();
final Class tupleClass = Class.forName(tupleClassName);
DataSet<Tuple> ret = dbData.map(new RowToTupleMapper(tupleClass, typeInformations));

How to convert jdbc template query result to JSON Array in java?

I am converting software from Delphi to Spring boot. I have lots of queries in an existing SQL Server database, and I want to display them.
For every query, I have to create entity class, that override row mapper and create entity class.
public class PregledTroskova {
int RbrStavke;
int RbrNaloga;
String Konto;
String SifKomint;
float Duguje;
float Potrazuje;
public PregledTroskova() {
}
public int getRbrStavke() {
return RbrStavke;
}
public void setRbrStavke(int rbrStavke) {
RbrStavke = rbrStavke;
}
public int getRbrNaloga() {
return RbrNaloga;
}
public void setRbrNaloga(int rbrNaloga) {
RbrNaloga = rbrNaloga;
}
public String getKonto() {
return Konto;
}
public void setKonto(String konto) {
Konto = konto;
}
public String getSifKomint() {
return SifKomint;
}
public void setSifKomint(String sifKomint) {
SifKomint = sifKomint;
}
public float getDuguje() {
return Duguje;
}
public void setDuguje(float duguje) {
Duguje = duguje;
}
public float getPotrazuje() {
return Potrazuje;
}
public void setPotrazuje(float potrazuje) {
Potrazuje = potrazuje;
}
}
Then after that I have to write one more class for mapper
class PregledTroskovaRowMapper implements RowMapper<PregledTroskova> {
#Override
public PregledTroskova mapRow(ResultSet resultSet, int i) throws SQLException {
PregledTroskova pregledTroskova = new PregledTroskova();
pregledTroskova.setDuguje(resultSet.getFloat("Duguje"));
pregledTroskova.setPotrazuje(resultSet.getFloat("Potrazuje"));
pregledTroskova.setRbrStavke(resultSet.getInt("RbrStavke"));
pregledTroskova.setRbrNaloga(resultSet.getInt("RbrNaloga"));
pregledTroskova.setKonto(resultSet.getString("Konto"));
pregledTroskova.setSifKomint(resultSet.getString("SifKomint"));
return pregledTroskova;
}
}
Is there any way to just generate json list/array of object where property is result set name value for all rows from select?
If you don't want to create an entity class for every query, you can return a List<Map<String, Object>> which is a list of all rows, each row is represented by a Map (column / value).
Example :
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(yourQuery);
for (final Map<String, Object> row : rows) {
// do something like : row.get("yourField");
}
Example :
String sql = "select * from mytable";
result= jdbcTemplate.query(sql, new AnyObjectMapper());
Mapper (generic) :
class AnyObjectMapper implements RowMapper<Map<String, Object>> {
public AnyObjectMapper() {
// TODO Auto-generated constructor stub
}
#Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData rsMeta = rs.getMetaData();
int colCount = rsMeta.getColumnCount();
Map<String, Object> columns = new HashMap<String, Object>();
for (int i = 1; i <= colCount; i++) {
columns.put(rsMeta.getColumnLabel(i), rs.getObject(i));
}
return columns;
}
}

Camel Velocity Template - access java object properties

I have a camel route which uses Velocity template and in the body I have an object defined as following:
class MailImpl extends AbstractMail{
private BodyContext bodyContext;
public BodyContext getBodyContext() {
return bodyContext;
}
public void setBodyContext(BodyContext bodyContext) {
this.bodyContext = bodyContext;
}
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
#Override
public String toString() {
return "MailImpl{" +
"bodyContext=" + bodyContext +
'}';
}
}
class BodyContext{
private String value;
public BodyContext(String value) {
this.value = value;
}
public BodyContext() {
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "BodyContext{" +
"value='" + value + '\'' +
'}';
}
In the velocity template I would like to access the MailImpl object properties, for example I use ${body.test} and ${body.bodyContext.value} but velocity template does not transform those values (it returns as string ${body.test} and ${body.bodyContext.value}).
One solution could be creating headers for each of of the value I need to use in the template, but as my route is dynamic (I select velocity template based on header) I would like to access the body properties in the velocity context. Is this somehow possible?
You can setup a custom Velocity Context by setting the message header "CamelVelocityContext" (since Camel v2.14). From Camel's test case:
Map<String, Object> variableMap = new HashMap<String, Object>();
Map<String, Object> headersMap = new HashMap<String, Object>();
headersMap.put("name", "Willem");
variableMap.put("headers", headersMap);
variableMap.put("body", "Monday");
variableMap.put("exchange", exchange);
VelocityContext velocityContext = new VelocityContext(variableMap);
exchange.getIn().setHeader(VelocityConstants.VELOCITY_CONTEXT, velocityContext);
exchange.setProperty("item", "7");
With following template:
Dear ${headers.name}. You ordered item ${exchange.properties.item} on ${body}.
You get:
Dear Willem. You ordered item 7 on Monday.

Suggest Addresses in a SuggestBox in GWT/Java

I want to define a SuggestBox, which behaves like the search bar in Google Maps: When you begin to type, real addresses, starting with the typed letters, appear.
I think, that I need to use the Geocoder.getLocations(String address, LocationCallback callback) method, but I have no idea how to connect this with the oracle, which is needed by the suggest box to produce its suggestions.
Can you please give me ideas how do I connect the getLocations Method with the SuggestOracle?
I solved this by implementing a subclass of SuggestBox, which has it's own SuggestOracle. The AddressOracle deals as a Wrapper for the Google Maps Service, for which the class Geocoderin the Google Maps API for GWT offers abstractions.
So here is my solution:
First we implement the Widget for a SuggestBox with Google Maps suggestions
public class GoogleMapsSuggestBox extends SuggestBox {
public GoogleMapsSuggestBox() {
super(new AddressOracle());
}
}
Then we implement the SuggestOracle, which wraps the Geocoder async method abstractions:
class AddressOracle extends SuggestOracle {
// this instance is needed, to call the getLocations-Service
private final Geocoder geocoder;
public AddressOracle() {
geocoder = new Geocoder();
}
#Override
public void requestSuggestions(final Request request,
final Callback callback) {
// this is the string, the user has typed so far
String addressQuery = request.getQuery();
// look up for suggestions, only if at least 2 letters have been typed
if (addressQuery.length() > 2) {
geocoder.getLocations(addressQuery, new LocationCallback() {
#Override
public void onFailure(int statusCode) {
// do nothing
}
#Override
public void onSuccess(JsArray<Placemark> places) {
// create an oracle response from the places, found by the
// getLocations-Service
Collection<Suggestion> result = new LinkedList<Suggestion>();
for (int i = 0; i < places.length(); i++) {
String address = places.get(i).getAddress();
AddressSuggestion newSuggestion = new AddressSuggestion(
address);
result.add(newSuggestion);
}
Response response = new Response(result);
callback.onSuggestionsReady(request, response);
}
});
} else {
Response response = new Response(
Collections.<Suggestion> emptyList());
callback.onSuggestionsReady(request, response);
}
}
}
And this is a special class for the oracle suggestions, which just represent a String with the delivered address.
class AddressSuggestion implements SuggestOracle.Suggestion, Serializable {
private static final long serialVersionUID = 1L;
String address;
public AddressSuggestion(String address) {
this.address = address;
}
#Override
public String getDisplayString() {
return this.address;
}
#Override
public String getReplacementString() {
return this.address;
}
}
Now you can bind the new widget into your web page by writing the following line in the onModuleLoad()-method of your EntryPoint-class:
RootPanel.get("hm-map").add(new GoogleMapsSuggestBox());

Resources