String cannot be cast to Integer session Attribute - java

Hello I am getting this error:
java.lang.ClassCastException: java.lang.String cannot be cast to
java.lang.Integer
at this line of the code:
int est;
est=(Integer) session.getAttribute("estado");
I think that the problem is that "estado" is not filled yet. I use this session-attribubute in order to see if session has been signed in and so that it doesnt need to log in again.

You cannot type-cast here, as Integer is not compatible with String.
Use Integer#parseInt to parse it as an int
est = Integer.parseInt(session.getAttribute("estado"));

The session.getAttribute("estado"); returns the session attribute held in estado, What happened here that, the JVM has found (during runtime) the returned value's type is String so when you tried to cast it into Integer it fired a ClassCastException
What you need here is to parse the result returned by the attribute estado using Integer.parseInt(session.getAttribute("estado"));, which was suggested in the answers
NOTE: you maybe questioning that you have added an integer (not a String) to that attribute, but trace your code carefully considering that request.getParameter("attrName") returns a String, just an assumption

use Integer.parseInt
int est= Integer.parseInt(session.getAttribute("estado").toString());

Related

Handle validation for non numeric characters getting passed to Integer variable

Is there an annotation that could be used to prevent the following error from getting thrown by my Java application if I send a non numerical value for year in my GET request?
I currently have this:
#NotNull
#Digits(integer = 4, fraction = 0, message = "Provide valid Year in the format YYYY")
#Min(value = 1900, message = "Year must be greater than 1900")
private Integer year;
When I pass a value with letters I get a NumberFormatException before #Digits and #Min is executed. I also tried #Pattern with a regex value but that caused a 500 error.
"Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'yearOfReg'; nested exception is java.lang.NumberFormatException: For input string: \"20c15\"
The answer is very short: no. That's because the validation is configured for the Integer year field. That means that the field must get populated before it can be validated. That population fails if you submit a value that cannot be parsed to an Integer.
The best way to handle this case is to add error handling for the mapping exception. For Jackson that's a MismatchedInputException.
An alternative is to change the field to a String. That allows you to use #Pattern, but you will need to convert yourself. That can be done in the class itself using a getter.

equals cannot convert from String to boolean

I want to compare input String from Database in tMap component in Talend Open Studio. If my String is equal to "{}", I want to put there "nodata" string. Otherwise I leave the original input as it is.
My code in expression/filter in tMap:
(row1.parameter).equals("{}")?"nodata":row1.parameter
Error I'm getting:
Detail Message: Type mismatch: cannot convert from String to boolean
Do you have any suggestions?
Try to assign the result to a String variable, like
String someVariable = row1.parameter.equals("{}") ? "nodata" : row1.parameter;
because your expression returns a String… Are you assigning it to a Boolean? If yes, that will cause / be a type mismatch.
Assuming you're keeping the "Parameter" field, it sounds like your Output field that you are assigning 'Parameter' to is not a 'String' field, and is set as 'Boolean':
So the first point of call would be to check/change the output to a type of 'String':

How to convert Attributes to String?

I want to convert Attributes to String so that I can trim and get a substring of the attribute value.
Here is my code:
Attribute attrs = match.getAttributes();
NamingEnumeration e = attrs.getAll();
System.out.println(attrs.get("cn"));
System.out.print(attrs.get("uniqueMember"));
unique_members[i] = attrs.get("uniqueMember");
I am facing an error in the last line where I want to store the value of uniqueMember to the unique_members array. Error:
Type mismatch: cannot convert from Attribute to String
I have tried the following so far:
unique_members[i] = (String)attrs.get("uniqueMember");
It doesn't solve the issue and I am getting error:
Cannot cast attribute to String.
Use unique_members[i] = attrs.get("uniqueMember").toString() to convert the attribute value to a string.
For more informationens see the javadoc of BasicAttribute or javax.naming.directory.Attribute
Have a look at the Javadoc of Attributes class. You can use getValue(String) to retrieve the value of a specific attribute.
I suggest to use null-safe Objects.toString() for getting string representation--it won't throw exception if attrs.get() returns null, which may happen if attribute is not found:
unique_members[i] = Objects.toString(attrs.get("uniqueMember"));
If you came here searching for how to convert any Object with its attributes to a string, you can consider using ReflectionToStringBuilder:
ReflectionToStringBuilder.toString(anyObject);

SharedPreferences getString NULL parameter

Will I receive an error (Exception) on some devices if I set the second parameter of SharedPreferences.getString NULL?
SharedPreferences settings = ...
String data = settings.getString(_.PREFIX , null);
Will it cause an exception or an error on at least one device? Or I have to wrap this part of code in try-catch block?
If you are asking if you will get an exception if you set the second parameter to null, the answer is no (at least not unless you reference the result without first checking it is not null). The second parameter in the getString() method is the default value (i.e. the value that will be returned if there is nothing found for your prefix. So, it is perfectly acceptable to set null as your default value, as long as you realize (and account for) the fact that the value returned by your getString() could be null.
String data = settings.getString(_.PREFIX , null/Null here is default value/);
null - u can receive when your SraredPreferences have not this item(For example if u call/get this string before setting to this field any info or user clear cash of application from settings of device). I think it's can be normal situation, and u can remove "null" with some default value if you hope to got it(some emum field).
If u don't suppose get null validate data before using.
I thin'k your app must be ready get both variant, because user can change normal workflow.

Check if there is an error in update/insert | MongoDB Java driver

I want to check if an insert fails (due to unique=True index in the collection). If there is an error do something. Bellow is an example of my code.
DBCollection user...;
BasicDBObject Doc = new BasicDBObject(... );
String user_exists = user.insert(Doc).getError(); //insert the doc get error if any
if(user_exists!=null){ //any errors?
user.update(new BasicDBObject(...)); // error exists so do smthng
}
The above as it is does not work. I believe that the String user_exists is always null. How can I make the above work?
I have seen similar SO questions and mention the WriteConcern which can be passed in the insert(). E.g.
coll.insert(dbObj, WriteConcern.SAFE);
sources: SO question
or
Mongo docs
However I do not know which one field should I pass (SAFE, ACKNOWLEDGED, UNACKNOWLEDGED etc..) in order to get the error. Maybe I'm pointed in the wrong direction.
I do not wish to raise an exception just to check if there is an error returned by the insert operation.
If you are using WriteConcern.ACKNOWLEDGED (which I think is also SAFE) you don't need to pollute your code with error checking.
For ACKNOWLEDGED, the driver will automatically issue a getLastError command automatically and raise an exception if anything got wrong, for example duplicate index violation.
Starting from v2.10 of the Java Driver, the default Write Concern is ACKNOWLEDGED
EDIT
I do not wish to raise an exception just to check if there is an error returned by the insert operation.
You shouldn't do this, but in any case:
The insert method indeed returns WriteResult. If it's getError() is null, everything is OK, otherwise it returns something such as E11000 duplicate key error index:.... For this to work, you will have to use WriteConcern.UNACKNOWLEDGED

Categories

Resources