java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast - spring-mvc

hey Hi so this my service layer code
BillType billType=billTypeList.get(i);
This is my dao code:
#Override
public List<BillType> getBillTypeList(BillCategory billCategoryId){
Session session = null;
List<BillType> billTypeList=null;
try {
session=sessionFactory.openSession();
String sql = "select * from BILL_TYPE where BILL_CATEGORY_ID=:billCategoryId";
Query query = session.createSQLQuery(sql);
query.setParameter("billCategoryId", billCategoryId);
billTypeList= query.list();
}
catch(Exception e)
{
e.printStackTrace();
logger.error("Error in Method getBillType "+e.getMessage());
}
finally {
if (session != null) {
if (session.isOpen())
session.close();
}
}
return billTypeList;
}
This is the error i am getting:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.mppmcl.nonpower.model.BillType
Please tell me what to do. would be of great help. thanks in advance

Just to get rid of this error, by putting #SuppressWarnings on your method will do the trick.
But you should see a proper way to handle this here

Can you show us the attributes of BillType?Also there's an error in your code
query.setParameter("billCategoryId", billCategoryId);
You cant pass an Object as hibernate parameter. This will cause an unmatching type error. Try passing Integer values, it will match the ID Type.
Try this
query.setParameter("billCategoryId", billCategoryId.getId());
To know more about mapping, check this Java type Mappings

Related

Is it possible that an ASP.NET httpContextBase ever be null? or Request? or UserAgent?

I'm getting a bug in a production server. I know which line is, but I do not know which would be the one that is complaining of a "Object reference not set to an instance of an object." Something is null:
public string GetAgentType(HttpContextBase httpContextBase)
{
try
{
string userAgent = httpContextBase.Request.UserAgent.ToLower();
/*some code to return the agent type*/
}
catch(Exception ex)
{
/*..Log exception logic..*/
}
}
The method is called with the injected parameter ControllerContext.HttpContext from a controller class.
"string userAgent = httpContextBase.Request.UserAgent.ToLower();"
As I said not pretty sure which would be null; httpContextBase? Request? or UserAgent? or in which cases one of them could be null?

Mocking java.lang.Class getDeclaredMethod(String name, ...Class args) with Mockito not working

I am trying to mock the getDeclaredMethod on a java .class object of a certain defined java type:
AccessRulesMethods accessRulesMock = mock(AccessRulesMethods.class);
Method mockMethod = mock(Method.class);
when(accessRulesMock.getClass().getDeclaredMethod(param.getValue(), String.class, BigInteger.class)).thenReturn(mockMethod);
but I get the following exception:
java.lang.NoSuchMethodException: myOwnPackage.AccessRulesMethods.methodName(java.lang.String, java.math.BigInteger)
at java.lang.Class.getDeclaredMethod(Class.java:2130)
Lokking into java.lang.Class at line 2130 it seems that the method is not mocked at all. I found in another discussion here that this is the correct way but with no examples...
Anyone knows how can I manage to get what I need?
Thanks a lot,
Saverio
Business logic:
try {
Method method = AccessRulesMethods.class.getDeclaredMethod(name, String.class, BigInteger.class);
String parameterName = Arrays.asList(method.getParameters()).get(0).getName();
Field inputField = input.getClass().getDeclaredField(parameterName);
inputField.setAccessible(true);
String parameterValueFromInput = (String) inputField.get(input);
AccessRulesMethods accessRulesInstance = beanFactory.getBean(AccessRulesMethods.class);
methodOutput = (MethodOutput) method.invoke(accessRulesInstance, parameterValueFromInput, input.getIdBp());
}catch (InvocationTargetException ite){
throw ite.getTargetException();
}catch (NoSuchMethodException | IllegalAccessException | NoSuchFieldException e) {
throw new CoreApplicationException("Errore tecnico: invocazione metodo fallita", ErrorConstant.getLocalErrorKey(ErrorConstant.LOCAL_ERROR_CODE_ERRVISREFL001), HttpStatus.INTERNAL_SERVER_ERROR);
}
I have a bean with some methods: AccessRulesMethod. I get method names from a table in a db and the I call this methods with reflection in a given order. In order to call these method, first I get the name of the required parameter (the second one is fixed) and then I pass this parameter from the input to the API, also with reflection

How to handle Internal server error (500) on spring rest API to custom the message?

I am working on spring rest api and I would like to sure everything is working fine. I would like to log abnormal behaviors database connection error among others, I'm working with couchbase database and I'm getting in the endpoint response for example for this kind of exception: CouchbaseQueryExecutionException the next message: Unable to execute query due to the following n1ql errors: \n{\"msg\":\"No index available on keyspace kids_club that matches your query. Use CREATE INDEX or CREATE PRIMARY INDEX to create an index, or check that your expected index is online.\",\"code\":4000} and a very long trace.
For this i found a solution on internet that is extend ResponseEntityExceptionHandler and override handleExceptionInternal method like this:
#ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
private static String DEFAULT_VALIDATION_ERROR_CODE = "KC-0020";
#ExceptionHandler(MiddlewareException.class)
protected ResponseEntity<ResponseBody> handleKidsClubException(MiddlewareException ex) {
return buildErrorResponse(HttpStatus.valueOf(ex.getHttpStatus()), ex.toError());
}
#ExceptionHandler(ServiceUnavailableException.class)
protected ResponseEntity<ResponseBody> handleServiceUnavailable(ServiceUnavailableException ex) {
return buildErrorResponse(INTERNAL_SERVER_ERROR, ex);
}
#ExceptionHandler(NoSuchElementException.class)
protected ResponseEntity<ResponseBody> handleNoFoundElement(NoSuchElementException ex) {
return buildErrorResponse(NOT_FOUND, ex);
}
#ExceptionHandler(CouchbaseQueryExecutionException.class)
protected ResponseEntity<ResponseBody> handleCouchbaseQueryException(ConstraintViolationException ex) {
return buildErrorResponse(BAD_REQUEST, ex);
}
}
But I'm not able to catch any kind of Internal Server Error in this way.
It seems like spring is handle and building the final message to the user.
Any ideas to resolve this?
Thanks.
#ExceptionHandler(NullPointerException.class)
public final ResponseEntity<Object> handleNullPointerException(NullPointerException ex, WebRequest request) {
LOGGER.info("Entering into the handleAllException method");
System.out.println("Exception is : " + ex.getClass());
ResponseData error = new ResponseData();
error.setRespCode(HttpStatus.NOT_FOUND.toString());
error.setRespMessage(ex.getLocalizedMessage());
error.setTimestamp(LocalDateTime.now());
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
please try this way below to check whether you are able to catch exception or not.. From the sysout you will get the exact exception. Then you can use that exception to catch any particular exception from that business logic..

Override Elmah logged error message

Is there any way of overriding the error message logged by Elmah without duplicating it?
I have a custom exception class:
public class BusinessException : Exception
{
// detailed error message used for logging / debugging
public string InternalErrorMessage { get; set; }
public BusinessException(string message, string internalMessage)
:base(message)
{
InternalErrorMessage = internalMessage;
}
}
From the code, i throw an exception like this:
string detailedErrorMessage = string.Format("User {0} does not have permissions to access CreateProduct resource", User.Identity.Name);
throw new BusinessException("Permission denied", detailedErrorMessage);
When Elmah logs the error, it only logs Permission denied message. However, i need to log the InternalErrorMessage property of the exception instead.
I've tried to create a custom HandleErrorAttribute to do this, but this duplicates the exceptions logged:
public class ErrorHandleAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled == true)
return;
Exception exception = filterContext.Exception;
BusinessException businessException = exception as BusinessException;
if (businessException != null)
{
ErrorSignal.FromCurrentContext().Raise(new Exception(businessException.InternalErrorMessage, exception));
}
}
}
I think your issue might be here:
if (businessException != null) {
ErrorSignal.FromCurrentContext().Raise(
new Exception(businessException.InternalErrorMessage, exception));
}
When you create a new exception rather than something like this:
if (businessException != null) {
ErrorSignal.FromCurrentContext().Raise(businessException));
}
I have this done the code for one of my sites and can see if I can recreate your issue later today (assuming this does not work). I think this is the SO post that helped me implement: How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?
Edit:
Re-reading your question and the other answer I realize I was trying to solve your attempted correction and not the actual problem. Have you tried something like this solution which is only a slight deviation from your current attempt:
public override void OnException(ExceptionContext filterContext) {
if (filterContext.ExceptionHandled == true) {
return;
}
Exception exception = filterContext.Exception;
BusinessException businessException = exception as BusinessException;
if (businessException != null) {
var customEx = new Exception(
businessException.InternalErrorMessage, new BusinessException());
ErrorSignal.FromCurrentContext().Raise(customEx);
return;
}
}
Check that the InternalErrormessage is returning what you expect, and I expect that forcing a return here will prevent the exception from being logged twice. Otherwise it is essentially what you had done.
I suspect you'll need to create your own errorlog implementation to log anything other than the standard properties. This shouldn't be too difficult.
Using the SqlErrorLog as an example, you only need to override the log method & put in your own logic to modify what the Error class contains before calling the base implementation.
Using what #Matthew has also said will stop you logging the exception twice.
All the source code is here

Exception Handling in classes and Code Behind with C#

I'm a little bit stuck with a asp.net project that i'm doing! I have got a class that is called from the code behind and many of its function have no return type ie, being void. How does one do exception handling then??? Also, if the function within the class does have a return type of, for instance, a dataset how would one then return an exception or indicate that an exception had occured? I have attached the following code from my class which is referenced from the code behind.
public void fnRecord(string []varList, string fnName)
{
try
{
String x;
StringBuilder SQLParameters = new StringBuilder();
SQLParameters.AppendLine("SELECT #{Function}(");
{
SQLParameters.Replace("#{Function}", fnName);
}
for (int i = 0; i < varList.Length; i++)
{
x = varList[i].ToString();
SQLParameters.Append("'" + x + "',");
}
SQLParameters.Remove((SQLParameters.Length - 1), 1);
SQLParameters.Append(")");
string SQLCMD = SQLParameters.ToString();
conn.Open();
NpgsqlCommand command = new NpgsqlCommand(SQLCMD, conn);
Object result = command.ExecuteScalar();
}
catch (NpgsqlException ne)
{
//return ne;
}
catch (Exception x)
{
//error code
}
finally
{
conn.Close();
}
}
Any help would be appreciated!
Thanks
Only catch the exceptions where you intend to handle them properly. If you want to reflect the errors in the UI, catch them at the UI. If you want to handle them and try to deal with the issue in the business logic, then catch them and handle them at that point.
By the way, your code is susceptable to SQL injection attacks. Best go learn something about parameterised queries.
You don't return exceptions. You throw them. That's the point of exceptions - you don't want exception handling cluttering your method signatures!
In your catch clauses, you don't actually do anything to handle the exceptions. Then you should not catch them at all, just let them bubble up to your code-behind, and catch them there - put a try-catch round the method call.
Alternatively, catch your SQL exceptions in your method, then throw a new exception with some sensible message, adding the SqlExceptions as the inner exception, like this
catch (NpgsqlException ne)
{
throw new Exception("Your explanatory message here", ne);
}
finally
{
...
}
Cool thanks for the answers... working with the obout library so have to try and work out their exception handling functions too.

Resources