Kathir jeyap

Greenhorn
+ Follow
since Jan 31, 2018
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
1
Given in last 30 days
1
Forums and Threads
Scavenger Hunt
(keep public parts private until JForum day)
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt
Moderation Tools

Recent posts by Kathir jeyap

Created enum as follows

public enum OrderStatusEnum {

ACTIVE("active"),AWAITING("awaiting_order");

private String desc;

private OrderStatusEnum(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}

}

However when i used OrderStatusEnum.valueOf("awaiting_order") i am getting the exception Exception in thread "main" java.lang.IllegalArgumentException: No enum constant com.mkyong.model.OrderStatusEnum.awaiting_order

How to resolve it..Basically

1. valueOf should work
2. not sure which string needs to be returned on toString
3. How to save the value in the database.
5 hours ago
Hi,

I insert a row in the table as follows

final SqlParameterSource namedParameters = new MapSqlParameterSource.addValue("xParam", X.getName).addValue("yParam", Y.getName).addValue("zParam", Z.getName);

I have a enum colum in the database which is of enum OrderStatusEnum

I have an enum as follows

public enum OrderStatusEnum {
    ACTIVE("A","Active Order"),
    AWAITING("I","Awaiting Order")

I want to save ACTIVE, AWAITING in the database. Also retrieve the same on query

I'm getting exception when entity is getting set as enum and saved via JdbcTemplate. Data Truncate exception

Questions

1. Do i need to save ACTIVE/AWAITING in the database or Active Order/Awaiting Order i.e enum description ??
2. How to save the enum value and not sure how to save it

If i put Types.VARCHAR as an additional parameter the value is getting saved as ACTIVE/AWAITING ORDER and seems description is getting saved

Which one is the right approach - saving enum value or description. I think saving enum value would be the right option. However unable to save the enum using the above

Thanks.
15 hours ago

Link For Reference https://www.mkyong.com/spring-boot/spring-boot-ajax-example/

1. Don't type any name and hit search button - Bad Request - It Comes to Error Function of Ajax - User Can't be Empty - Form Validation. Ajax response is error in this case.

2. Type "Somu" in name field and hit search button - Business Error - Returned with Success Function. Ajax response is success in this case.

3. Assume i have thrown a run time exception in getSearchResultViaAjax() as below

AjaxResponseBody result = new AjaxResponseBody();
       
        if(1==1) {
              throw new RuntimeException();
        }

The same Ajax error block is getting called.

error: function (e) {

            var json = "<h4>Ajax Response Error </h4><pre>"
                + e.responseText + "</pre>";
            $('#feedback').html(json);

            console.log("ERROR pp : ", e);
            $("#btn-search").prop("disabled", false);

        }

So for Bad Request and Any Exception which comes Out side the box comes in error block

Which one is the right approach in the follow ? If both of them is incorrect, help me with the best practice

One
==
1. Throw form validation errors as as Ajax Response is ERROR with failure message to display
2. Throw Business validation errors as Ajax Response is SUCCESS with failure message to display
3. Throw any other exception as Ajax Response is ERROR with failure message to display

OR

Two
===

1. Throw form validation error as Ajax Response is ERROR with failure message to display ('User Field is Empty')
2. Throw Business validation errors as Ajax Response is FAILURE with failure message to display ('User Name doesn't exist')
3. Throw any other exception as Ajax Response is ERROR with failure message to display

Please advise with suggestions or comments.
1 week ago

Below code handles both success and failure scenarios

jQuery.ajax({

        type:"post",
        dataType:"json",
        url: myAjax.ajaxurl,
        data: {action: 'submit_data', info: info},
        success: function(data) {
            successmessage = 'Data was succesfully captured';
            $("label#successmessage").text(successmessage);
        },
        error: function(data) {
            successmessage = 'Error';
            $("label#successmessage").text(successmessage);
        },
    });

Will all the error come to the error section....RuntimeException - i.e checked and non-checked exceptions......

OR only exceptions will be caught and NOT ERRORS..In java we have both ERROR and EXCEPTION classes

Please confirm...
1 week ago
I see in the javascript in ajax call we have only success case and inside the success case we have differentiated as success or error based on the response type

If we add the failure in ajax script and handle this will it be handled ??

What should be the right way in the front-end for ajax calls ???
2 weeks ago

I used the same code...However 500 error is returned and the page got redirected to the error page

I want the same page or window or dialog should be retained..

Please advise.
2 weeks ago
1. Created @ControllerAdvice and caught few exceptions. ex: FileNotFoundException or User Defined exception
2. Translated the error message - error message + parameters and constructed the proper error message.

Now not sure how to send the response to the front-end

Currently 500 error is thrown. I have kept the return type as user defined object.

Someone please advise how to gracefully throw an error message to the front-end so that it will be displayed to the user without any issues.

2 weeks ago
Thanks for the explanation and we can close this.
2 weeks ago
Concurrency issue or user wants to know whether the attempt got failed..

Assume due to some reason the primary key got updated differently.
2 weeks ago
The problem is where i will formulate the error message text with parameters and also the message type - ERROR or EXCEPTION

Example, Assume file not found exception is thrown for the given file name

Generally, in message.properties file we will be having text as File Doesn't Exist for file {0}

The translation of error message usually happens in the presentation layer.....

Now if we need to pass the error message so that controller advice takes care of passing it to the UI....

Do we need to construct the error message in the service layer before sending ??? Where the exception and the parameters will be binded ???

for example

public void accessFile(String fileName) {
  File file = new File(fileName);
  if(!file.exists()) {
       throw new FileNotFoundException(Constants.FILE_NOT_FOUND.....);
       How to construct the error message with property key and sending with proper error message binded with exception???
      so that in controller advice we would just use exception.getMessage() which will have the translated text.

   }
}

Please let me know if you don't understand what i expect.
2 weeks ago
Paul, i am not sure how to move it..Could you please move this to Spring forum ??

Thanks.
2 weeks ago
So Paul what would be the right approach...Shall i do as below

1. create an interceptor which extends HandlerInterceptorAdapter
2. put the session variable in a thread local variable per request
3. clear the thread local variable in afterConcurrentHandlingStarted and afterCompletion method

import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionHandlerInterceptor extends HandlerInterceptorAdapter {
   /**
    * set of keys added to MDC so can be removed
    */
   private ThreadLocal<Set<String>> storedKeys = ThreadLocal.withInitial(() -> new HashSet<>());

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      addKey("sessionId", request.getHeader("X-Session-Id"));
      addKey("userId", resolveUser(request));
      return true;
   }


private void addKey(String key, String value) {
      storedKeys.get().add(key);
   }

   @Override
   public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      // request ended on current thread remove properties
      // clear the variables - key and values
removeKeys();
   }

   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
           throws Exception {
     // clear the variables - key and values
removeKeys();
   }

private void removeKeys() {
      storedKeys.remove();
   }
  
}



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class BeanConfiguration {

   @Bean
   public SessionHandlerInterceptor sessionHandlerInterceptor() {
      return new SessionHandlerInterceptor();
   }

   @Bean
   public WebMvcConfigurerAdapter webConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(sessionHandlerInterceptor());
         }
      };
   }
}
2 weeks ago
You do. DELETE must be idempotent. That means for instance, that you can not create an action like DELETE /books/last that will delete the last book added to the application. If you call it twice in succession, it will produce a new side-effect the second time, which is not good.

Shall i do as follows?

1. First time delete - delete the entity and return success
2. Second time delete - delete the entity, if entity not found or already deleted - throw an error instead of success.

The question is if the second time delete - already throws NOT_FOUND status.

Can i catch the NOT_FOUND and throws entity not found for the given id?

Usually we will throw the entity not found exception in the business layer and custom exception will be thrown.

I am not sure what will be the side effect if i follow the above, please advise
2 weeks ago
So what would be the best practice to do ??
2 weeks ago
I just come across this example -  http://veerasundar.com/blog/2010/11/java-thread-local-how-to-use-and-code-sample/

Is this is the correct approach to acess session variables in any layer - presentation, dao, service layer ???

Thanks.
2 weeks ago