How to overcome this java syntax so that double become string? - java

I am stuck in a situation whereby my Bean class - CartItemBean is in double.
public double getTotalCost() {
return dblTotalCost;
And the SetExpressCheckOutService class requires me to put the amount in String.
String amount = "";
CartItemBean details = new CartItemBean();
amount = details.getTotalCost();
try {
//calling the service, setting up the checkoutpage
String token = setExpressCheckoutService.setExpressCheckout(userId, amount,
currencyCode, returnURL, cancelURL, paymentAction);
log.info("Url to redirect to: https://www.sandbox.paypal.com
/webscr?cmd=_express-checkout&useraction=commit&token=" + token);
} catch (PayPalException e) {
// Log the exception
log.log(Level.WARNING, "Paypal exception", e);
}
}
I hope someone can advise me how to overcome a problem like this.
Thanks.

Use the toString method of the Double object:
String string = Double.toString(double);
So in your code do this:
String token = setExpressCheckoutService.setExpressCheckout(userId, Double.toString(amount), currencyCode, returnURL, cancelURL, paymentAction);

I have found the solution:
amount = Double.toString(details.getTotalCost());

Related

IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY while using Retrofit 2

I'm trying to execute some code on some parsed JSON using Retrofit, but I am getting an Illegal State Exception. Here is my Retrofit instance:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.pro.coinbase.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
CoinbaseProAPI coinbaseProAPI = retrofit.create(CoinbaseProAPI.class);
The Coinbase Pro API interface:
#GET("products/{productId}/candles")
Call<ArrayList<HistoricRates>> getHistoricRates(#Header("CB-ACCESS-SIGN") String signature,
#Header("CB-ACCESS-TIMESTAMP") String timeStamp,
#Path("productId") String productId,
#Query("start") String intervalStart,
#Query("end") String intervalEnd,
#Query("granularity") int granularity
);
The call request to the server (this is what's causing the error):
Call<ArrayList<HistoricRates>> call = coinbaseProAPI.getHistoricRates(signature, timeStamp, productId, intervalStart, intervalEnd, granularity);
try {
//this is being executed inside a for loop; requests are rate limited so consecutive
//iterations must wait
if (i > 0) {
call.wait(1010);
}
//this is the line the debugger doesn't like:
Response<ArrayList<HistoricRates>> response = call.execute();
if (!response.isSuccessful()) {
Message eMsg = errorHandler.obtainMessage();
String e = R.string.error_header + response.toString();
eMsg.what = 2;
eMsg.obj = e;
errorHandler.sendMessage(eMsg);
} else {
ArrayList<HistoricRates> candles = response.body();
int n = 0;
double[][] aCandles = new double[3][3];
for (HistoricRates historicRates : candles) {
aCandles[n][0] = historicRates.getOpen();
aCandles[n][1] = historicRates.getClose();
aCandles[n][2] = historicRates.getVolume();
n++;
}
selectedAsset.setCandles(aCandles);
}
} catch (Exception e) {
Message eMsg = errorHandler.obtainMessage();
eMsg.what = 2;
eMsg.obj = e.getMessage();
errorHandler.sendMessage(eMsg);
e.printStackTrace();
}
And finally the class object the JSON is being parsed into:
public class HistoricRates {
private int time;
private double low;
private double high;
private double open;
private double close;
private double volume;
public double getOpen() {
return open;
}
public double getClose() {
return close;
}
public double getVolume() {
return volume;
}
}
So from what I gather from similar posts, Illegal State Exception occurs because the object I'm trying to pass to Gson is not of the correct type. But I don't understand how this could be, given that I'm using Retrofit; shouldn't the GsonConverterFactory take care of this for me? Also, even though I have this code enclosed within a try/catch block, it is not actually throwing an exception; it just fails silently. The only reason I even know about the Illegal State Exception is because of the Debug Console. How can I improve my error reporting or is there something else I'm not understanding?
EDIT TO ADD:
Tried Capps99's solution (with added accessor method included in HistoricRatesList so I can get an iterator to loop through the values) Here is what that looks like:
HistoricRatesList candles = response.body();
Iterator candleIterator = candles.getList().iterator();
int n = 0;
double[][] aCandles = new double[3][3];
while (candleIterator.hasNext()) {
HistoricRates historicRates = (HistoricRates) candleIterator.next();
aCandles[n][0] = historicRates.getOpen();
aCandles[n][1] = historicRates.getClose();
aCandles[n][2] = historicRates.getVolume();
n++;
}
Unfortunately I'm still getting an Illegal State Exception. At the request of another commenter, here is the expected JSON response from the server(apologies I should have included this to begin with):
[
//these are all decimal values except for time; which is an integer value
//representing the UNIX epoch time
[time, low, high, open, close, volume],
[time, low, high, open, close, volume],
...
]
Perhaps the trouble is that the server appears to be returning the data in the form of a 2D array, which I don't have the experience to know how to parse properly.
Try this.
Create the following class to parse the list.
public class HistoricRatesList {
List<HistoricRates> historicRates;
}
and then use like this.
#GET("products/{productId}/candles")
Call<HistoricRatesList> getHistoricRates(#Header("CB-ACCESS-SIGN") String signature,
#Header("CB-ACCESS-TIMESTAMP") String timeStamp,
#Path("productId") String productId,
#Query("start") String intervalStart,
#Query("end") String intervalEnd,
#Query("granularity") int granularity
);

NumberFormatException Spring

Below code...
#GetMapping("/brian/{number}")
public String getBrianMessage(#PathVariable int number) throws NumberFormatException {
try {
logList.add(number);
String stringList = logList.toString();
return "List is " + stringList;
} catch (NumberFormatException e){
int newCount= 999;
logList.add(newCount);
String stringList = logList.toString();
return "List is " + stringList;
}
}
When going to the url i would like the integer stored in a list. This works fine when you use a valid integer value. I want the ability to default the value to 999 when a string is supplied. So, if i go to /brian/string it should add 999 to the list and return it. This is not working and I'm getting the same error as before I added the exception handling

java.sql.SQLException: Before start of result set

I don't understand why this isn't working, I keep getting this java.sql.SQLException: Before start of result set error, ive looked online but because ive been staring at a computer screen for hours my brain is frazzling so I'm not able to find any soloutions. please can you help me?! thanks
String from = "";
String subject= "";
String to= "";
String message= "";
try
{
while(retrieveMessages().next())
{
to = retrieveMessages().getString("tblEmail.to");
from = retrieveMessages().getString("tblEmail.from");
subject = retrieveMessages().getString("tblEmail.subject");
message = retrieveMessages().getString("tblEmail.message");
MailBox.add(new Email(to, from, subject, message));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
You're calling retrieveMessages() multiple times. It doesn't help that you haven't shown us what that does, but I suspect you want to call it once and store the result in a local variable. At the moment, I suspect you're calling next() on one result set, then getString() on a different result set. For example:
try (ResultSet results = retrieveMessages()) {
while (results.next()) {
String to = results.getString("tblEmail.to");
String from = results.getString("tblEmail.from");
String subject = results.getString("tblEmail.subject");
String message = results.getString("tblEmail.message");
MailBox.add(new Email(to, from, subject, message));
}
}

Convert String to Int with Integer.parseInt don't works

I'm working with JavaEE i need to convert this: request.getParameter("id") to int. The value of request.getParameter("id") is "9" (String).
When I'm trying to convert to int I have
java.lang.NumberFormatException
I've tried java.lang.Integer.parseInt(request.getParameter("id")) and request.getParameter("id",10) but it donsen't works...
Any solutions? Thank you.
A complete full proof code would be
String idString = request.getParameter("id");
if(idString != null) {
try {
System.out.println(idString.trim()); // print to verify
int idInt = Integer.parseInt(idString.trim());
}
catch(NumberFormatException nbe) {
nbe.printStackTrace();
}
}
First you need to check whether String returned by getParameter() is null or not then check whether it is empty ("") String or not then use Integer.parseInt().
String id = request.getParameter("id");
if(null != id && !("".equals(id))) {
try {
int number = Integer.parseInt(id.trim());
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}

Java - Parsing JSON Response - Content is either String or JSONObject

I am facing a typical scenario while parsing JSON Response for one of the Service calls.
The content for one of the attributes (from below example, consider "name" as a attribute) coming as either String or JSONObject.
How to handle these kind of scenarios through code. Also, please consider that json content need not be consistent with same set of attributes.
Example:
String Response
{"name":"Adam"}
JSON Response
{"name":{"FirstName":"Adam", "MiddleName":"Don"} }
OR
{"name":{"FirstName":"Adam", "LastName":"Don"} }
OR
{"name":{"MiddleName":"Adam", "LastName":"Don"} }
You can ask the root JSONObject with the method optJSONObject(name) to return a JSONObject for the given name if it exists and is an JsonObject. Otherwise you can also test with optString(name) for a String.
So something like:
JSONObject root = new JSONObject(... data from server ... );
JSONObject obj = root.optJSONObject("name");
if (obj != null) {
// Do something with the object
} else {
String name = root.getString("name");
// Do something with the string
}
Parse your response JSON as a JSONObject, then get another JSONObject for the "name" key, if it throws a JSONException then your object is probably a String in with case you can call get String for the "name" key in your catch block.
String name = "";
JSONObject serverJSON = new JSONObject(YOUR_JSON_RESPONSE_STRING_FROM_SERVER);
try {
JSONObject nameObject = serverJSON.getJSONObject("name");
if (nameObject.has("first_name")) {
name = nameObject.getString("first_name") + " ";
}
if (nameObject.has("middle_name")) {
name += nameObject.getString("middle_name") + " ";
}
if (nameObject.has("last_name")) {
name += nameObject.getString("last_name");
}
name = name.trim();
} catch (JSONException e) {
// Probably a String, try again...
try {
name = serverJSON.getString("name");
catch (JSONException e) {
// Not a String or a JSONObject... figure out what's wrong...
e.printStackTrace();
}
}
I would really recommend though, that if you have any control of the server that you make sure that the name key choose one type and sticks to it; a JSONObject... You would be able to use the has(String key) member function in if statements to properly find all of your data without knowing what existed at runtime...
EDIT: Thought of a different idea... Parse the String to the first colon and see if the next non-whitespace character is a quotation mark, if it is, then your key belongs to a String, if it is a curly brace then it's a JSONObject. (If neither, then you have an error, because you aren't expecting an array or number or null or anything else...)
boolean jsonIsString = true;
String searchString = json.substring(json.indexOf(":")).trim();
if ("{".equals(searchString.charAt(0)) {
jsonIsString = false;
}
Tonity's solution is good. You can also use this solution.
In my solution, there will be no any Exception fired until JSON is wrong. What I am doing is following.
Search for number of ":" in string.
If it returns 1, then we sure that there is "name" value.
Otherwise, we need to check, whether there is "FirstName","MiddleName" or "LastName" exist in string or not.
Just go through this snippet and you will find solution for your problem.
// String str = "{\"name\":\"chintan\"}";
String str = "{\"name\":{\"FirstName\":\"Chintan\",\"LastName\":\"Rathod\"}}";
try {
//we will check how many ":" are there in string, if it is one, then
// we are going to get "name" field.
if ((str.split(":").length - 1) == 1)
{
Log.d("Home", "1");
JSONObject json = new JSONObject(str);
Log.d("Home", "Name : " + json.get("name"));
}
else
{
Log.d("Home", "more then 2");
JSONObject jName = new JSONObject(str);
JSONObject jTemp = jName.getJSONObject("name");
if (jTemp.toString().contains("FirstName"))
Log.d("Home", "FirstName :" + jTemp.getString("FirstName"));
if (jTemp.toString().contains("MiddleName"))
Log.d("Home","MiddleName :" +jTemp.getString("MiddleName"));
if (jTemp.toString().contains("LastName"))
Log.d("Home", "LastName :" + jTemp.getString("LastName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Output
08-06 11:52:34.060: D/Home(1439): more then 2
08-06 11:52:34.060: D/Home(1439): FirstName :Chintan
08-06 11:52:34.070: D/Home(1439): LastName :Rathod
I faced a problem like this as well. I didn't want to parse the JSON manually. Do this if firstName exists otherwise do that. I didn't want to mess up my structure because I only define java object and my client handles the parsing. So, I came up with following:
#Getter
#Setter
#ToString
class Response {
private Name name;
#Getter
#Setter
#NoArgsConstructor
#ToString
public static class Name {
private String name;
private String firstName;
private String middleName;
private String lastName;
public Name(String name) {
this.name = name;
}
}
}
Then, parse the json;
ObjectMapper objectMapper = new ObjectMapper();
Response response = objectMapper.readValue(json, Response.class);
Now, string response and JSON response can be parsed with the same class.

Categories