I'm supposed to receive long integer in my web service.
long ipInt = (long) obj.get("ipInt");
When I test my program and put ipInt value = 2886872928, it give me success.
However, when I test my program and put ipInt value = 167844168, it give me error :
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
The error is point to the above code.
FYI, my data is in JSON format :
{
"uuID": "user001",
"ipInt": 16744168,
"latiTude": 0,
"longiTude": 0,
}
Is there any suggestion so that I can ensure my code able to receive both ipInteger value?
Both Integer and Long are subclasses of Number, so I suspect you can use:
long ipInt = ((Number) obj.get("ipInt")).longValue();
That should work whether the value returned by obj.get("ipInt") is an Integer reference or a Long reference. It has the downside that it will also silently continue if ipInt has been specified as a floating point number (e.g. "ipInt": 1.5) in the JSON, where you might want to throw an exception instead.
You could use instanceof instead to check for Long and Integer specifically, but it would be pretty ugly.
We don't know what obj.get() returns so it's hard to say precisely, but when I use such methods that return Number subclasses, I find it safer to cast it to Number and call the appropriate xxxValue(), rather than letting the auto-unboxing throw the ClassCastException:
long ipInt = ((Number)obj.get("ipInt")).longValue();
That way, you're doing explicit unboxing to a long, and are able to cope with data that could include a ., which would return a Float or Double instead.
Long.valueOf(jo.get("ipInt").toString());
Is ok.
in kotlin I simply use this:
val myInt: Int = 10
val myLong = myInt.toLong()
You mention the current approach works when you provide a value outside the range of integer, but fails when you are within the integer range. That is an odd behavior for an API, because it seems you need to check the return type yourself. You can do that. The usual way is with instanceof. Something like,
long ipInt;
Object o = obj.get("ipInt");
if (o instanceof Integer) {
ipInt = ((Integer) o).intValue();
} else if (o instanceof Long) {
ipInt = ((Long) o).longValue();
}
public static void main(String[] args) {
JSONObject jo = JSON.parseObject(
"{ \"uuID\": \"user001\", \"ipInt\": 16744168, \"latiTude\": 0, \"longiTude\": 0}");
System.out.println(jo);
long sellerId1 = Long.valueOf(jo.get("ipInt").toString());
//Long sellerId1 = (long)jo.get("ipInt");
System.out.println(sellerId1);
}
Related
When I ran a program, long min value is getting persisted instead of original value coming from the backend.
I am using the code:
if (columnName.equals(Fields.NOTIONAL)) {
orderData.notional(getNewValue(data));
As output of this, i am getting long min value, instead of original value.
I tried using this method to handle the scenario
public String getNewValue(Object data) {
return ((Long)data).getLong("0")==Long.MIN_VALUE?"":((Long)data).toString();
}
but doesn't work.
Please suggest
EDITED: I misread the code in the question; rereading it, I now get what the author is trying to do, and cleaned up the suggestion as a consequence.
(Long) data).getLong("0") is a silly way to write null, because that doesn't do anything. It retrieves the system property named '0', and then attempts to parse it as a Long value. As in, if you start your VM with java -D0=1234 com.foo.YourClass, that returns 1234. I don't even know what you're attempting to accomplish with this call. Obviously it is not equal to Long.MIN_VALUE, thus the method returns ((Long) data).toString(). If data is in fact a Long representing MIN_VALUE, you'll get the digits of MIN_VALUE, clearly not what you wanted.
Try this:
public String getNewValue(Object data) {
if (data instanceof Number) {
long v = ((Number) data).longValue();
return v == Long.MIN_VALUE ? "" : data.toString();
}
// what do you want to return if the input isn't a numeric object at all?
return "";
I have this block of code in OrderService.java
public void deleteOrderByUserId(int userId){
List<Long> orderIds = orderDAO.getOrderIdByUserId(userId);
int deleteOrders = orderDAO.deleteOrders(orderIds);
}
This is the code in orderDAO.java
public List getOrderIdByUserId(int userId) {
StringBuilder queryStr = new StringBuilder("select distinct u.OrderId from ");
queryStr.append("User u where ");
queryStr.append("u.UserId in (:key)");
return getHibernateTemplate().getSessionFactory()
.getCurrentSession().createSQLQuery(queryStr.toString())
.setParameter("key", userId).list();
}
public int deleteOrders(List<Long> orderIds){
final String deleteOrder = "delete from Order o where o.OrderId in (:orderIds)";
final Query hibernateQuery = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(deleteOrder);
hibernateQuery.setParameterList("orderIds", orderIds);
int count = hibernateQuery.executeUpdate();
return count;
}
I'm getting an java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long Exception while executing this step int count = hibernateQuery.executeUpdate();
What's wrong with that code and how to get rid of that exception
To get the long value of a BigDecimal object you can call the .longValue() method on it.
orderDAO.getOrderIdByUserId(userId) returns a list of BigDecimal, not of Long, I would guess. It’s hard to tell without the code for that method.
EDIT (now that the code is there): Considering https://stackoverflow.com/a/5380867/1506009, you can see that some databases (Oracle comes to mind) return BigDecimal (or rather List<BigDecimal>) when calling list() in Hibernate. Your Java code is faulty in using a raw List and just assuming some type when it is indeed another.
getOrderIdByUserId() could return List<? extends Number>, which would match both Long and BigDecimal; or it could return List<BigDecimal> if that’s the truth. To not use raw types!
setParameterList() allows a third parameter, the type of the list elements. Use that.
Instead of using hibernateQuery.setParameterList("orderIds", orderIds);, I've updated it to hibernateQuery.setBigDecimal("orderIds", orderIds);
Now it's working fine.
I have two columns in my table are which is BigInt data type (NODEID and ULNODEID) and I want to keep it that way. I am using MYSQL workbench 8.0 for these table.
I want to get the value of my nodeid using the function below:
public long get_urlnodeid(long nodeID) {
try {
String sql = "select NODEID from urllink where ULNODEID="+nodeID;
if (em == null) {
throw new Exception("could not found URL object.");
}
return (long) em.createNativeQuery(sql).getSingleResult();
} catch (Exception e) {
msg = CoreUtil.wrapMsg(CoreUtil.FUNC_ERROR,
this.getClass().getName(), "get", e.getMessage());
}
return 0;
}
It throws an exception saying Big Integer cannot be cast to java.lang.Long
Is there a way I can retrieve the value while keeping it in long?
Just look at the Java doc for BigInteger:
public long longValue()
Converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.
So you'd want something like this:
return ((BigInteger)em.createNativeQuery(sql).getSingleResult()).longValue();
I would recommend adding some type checking.
--
Another option, if you have full control of your application, and you expect values that go beyond the range of long, is to have your method return BigInteger instead of long:
public BigInteger get_urlnodeid(long nodeID) {
And:
return (BigInteger) em.createNativeQuery(sql).getSingleResult();
Of course then the rest of your application that calls this method has to work with BigInteger as well.
Please be aware that using BigInteger instead of long is much less performant, so only use this if performance is not an issue or if you are absolutely sure that values will be so big that this is absolutely necessary.
I'm writing some code in java and using the JSON Simple package. I run this code below
jsonObject.get( "last" ) ;
Unfortunately this can either be a long or a double, what is the fastest/most correct way of parsing this value?
Would it be something like the following?
long lngLast = -1;
double dblLast = -1;
if ( jsonObject.get( "last" ).getClass().getName() == "java.lang.Long" ) {
lngLast = (long) jsonObject.get( "last" ) ;
} else {
dblLast = (double) jsonObject.get("last");
}
if ( lngLast == -1)
System.out.println( dblLast );
else
System.out.println( lngLast );
This seems absurd. There must be a better way of doing this. I've attempted converting the long to a double (which I believe I am supposed to be able to do?) but I get errors every time. I'm hoping someone can educate me on the correct or better way to do this.
In reality, the "last" element should have a consistent data type in all the JSON messages you're dealing with. Without a proper spec and without wanting to test, you'd probably want to go with double over a long.
In the case you have, where the type can be either, I think testing the object type is a perfectly fine way to do it.
As a side note, your if test should really be:
if (jsonObject.get("last").getClass().equals(Long.class)) {
....
}
Using == for String comparison will not work as you'd want it to.
long orgId = (Long)request.getSession().getAttribute("orgId");
I am not able to convert the object that I am getting from request.getSession().getAttribute("orgId")
to long variable
So I need to convert it to long.
Could anyway help.
This way is not the best way to proceed, it's too prone to error (and you are assuming orgId value is present as session's attribute and unboxing, in case orgId is null/not present, will throw an exception).
final long orgId;
Object sessionValue = request.getSession().getAttribute("orgId");
if(sessionValue != null) {
if(sessionValue instanceof Long)
{
orgId = ((Long)sessionValue).longValue();
}
else if(if(sessionValue instanceof String) {
orgId = Long.parseLong((String)sessionValue);
}
else {
// you can set orgId = 0, throw exception, do custom conversion
}
}
else {
// manage missed value
}
It depends upon the type of the "orgId" attribute. If it really is a Long, your code should work. If you've for instance added it as a String, you need to convert it to a long with Long.parseLong:
long orgId = Long.parseLong((String)request.getSession().getAttribute("orgId"));
This the common way to do this
String strOrgId = (String) request.getSession().getAttribute("orgId");
Then parse this value to Long
long orgId = Long.parseLong(strOrgId);
It depends on how is your "orgId" stored in session attributes, as a String instance or a Long instance.
Following code is little bit redundant but will work for both cases:
Object attribute = request.getSession().getAttribute("orgId");
long orgId = Long.parseLong(String.valueOf(attribute));
I had a similar problem.. I stored a long in the session, and when I wanted to get the attribute it was automatically deserialized to an Integer OR Long dependent on their size. This was really annoying..
So in my case the solution was to convert to a string and than parse it to a Long:
Object orgIdObject = session.getAttribute("orgId");
Long orgId;
// first, make a null check. you'll never know
if (orgIdObject == null) {
// if value is null, set to -1 or throw and error..
orgId = -1L;
} else {
// convert to string, and then parse to long
orgId = Long.valueOf(orgIdObject.toString());
}
In this way, it does not matter if the Object is a String, Integer or Long. It works with all that types.
Happy Coding,
Kalasch