Global Variable for Asynchronous data access in spring MVC - java

I have a below controller
#Controller
public class TestController{
public Future<ArrayList<String>> global_value = null;
#Autowired
private AsyncService asyncService;
#RequestMapping(value = "/asyncCall", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String getToken(HttpServletRequest request) {
global_value = asyncService.execute();
return "OK";
}
#RequestMapping(value = "/getAsyncData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ArrayList<String> getData() {
try {
if (global_value != null && global_value.get().size() > 0) {
return global_value.get();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
When I long poll the getAsncData endpoint, how do I maintain the global_value is just for a request. global_value must be unique for the request scope.
How can I achieve this?

Related

How can add Bearer before token

PostMan
My BaseController code
#SuppressWarnings("unused")
#Autowired
private UserService userService;
public User handleTokenAccess(String encodeString) throws Exception {
byte[] decodedBytes = Base64.getMimeDecoder().decode(encodeString);
String decodedMime = new String(decodedBytes);
ObjectMapper mapper = new ObjectMapper();
try {
UserClient map = mapper.readValue(decodedMime, UserClient.class);
User user = userService.findOne(map.getUserId());
if (user != null)
return user;
else
throw new Exception();
} catch (Exception e) {
throw new Exception("Sai token , vui lòng chim cút");
}
}
My CategoriesController code
#RestController
#RequestMapping("/api/categories")
public class CategoriesController extends BaseController {
#Autowired
private CategoriesService categoriesService;
#Autowired
UserService userService;
#RequestMapping(value = "/create-category", method = RequestMethod.POST, produces = {
MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<BaseResponse> create(#Valid #RequestBody CRUDCategories wrapper,
#RequestHeader(value = "Authorization") String token) throws Exception {
BaseResponse response = new BaseResponse();
User userToken = this.handleTokenAccess(token);
Categories category = categoriesService.spUCreateCategory(userToken.getId(), wrapper.get_name(),
wrapper.getDescpiption(), wrapper.get_sort());
response.setData(new CategoriesResponse(category));
return new ResponseEntity<BaseResponse>(response, HttpStatus.OK);
}
}

unable to call AOP is advice

Aop is unable to trigger when userData method is called.
#RequestMapping(value = "/service/userDate", method = RequestMethod.POST)
public ResponseEntity<Response> UserApp(#RequestBody UserVO userVO) {
Response res = new Response(HttpStatus.OK.value());
try {
logger.debug("UserController : </ UserApp> ");
res = userService.userApp(userVO);
return new ResponseEntity<>(res, HttpStatus.OK);
} catch (Exception e) {
logger.error("Exception in approveUser" + e.getMessage());
return new ResponseEntity<>(
new Response(ErocErrorConstants.ERROR_STRING, HttpStatus.EXPECTATION_FAILED.value()),
HttpStatus.BAD_REQUEST);
}
}
package com.gf.service
public class UserService {
#Transactional
public Response userData(User userData) {
}
}
#Aspect
public class EmailAopService {
#Pointcut("execution(* com.gf.service.UserService.userData(..)) && args(userData))")
private void selectAll() {}
#Before("selectAll()")
public void logBefore(User userData) {
//
}
}

springboot return responseentity return JSON

I want to return JSON below.
{
"name": "jackie"
}
Postman is giving me error. Stating
Unexpected 'n'
New to Spring Boot here. 1 day old. Is there a proper way to do this?
// POST method here
#RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<?> addTopic(#RequestBody Topic topic) {
if (Util.save(topicRepository, new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
return Util.createResponseEntity("Name : jackie", HttpStatus.CREATED);
}
return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
}
This is what I use:
#GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, String>> hello() {
try {
Map<String, String> body = new HashMap<>();
body.put("message", "Hello world");
return new ResponseEntity<>(body, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Create model and store value in that model and return model from controller.
Check Below code.
class User{
private String name;
//getter and setter
}
#RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<User> addTopic(#RequestBody Topic topic) {
User user=new User();
user.setName("myname");
HttpHeaders httpHeaders = new HttpHeaders();
return new ResponseEntity<User>(user, httpHeaders, HttpStatus.CREATED);
}
Try wrapping your response in object.
class Response implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And Controller can be like this:
#RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<?> addTopic(#RequestBody Topic topic) {
if (Util.save(topicRepository, new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
Response response = new Response();
response.setName("jackie");
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
}
#PostMapping("/register/service/provider")
public ResponseEntity<?> registerServiceProvider(#RequestBody ServiceProviderRequestPayload providerContext) {
try {
if (providerContext == null)
throw new BadRequestException("the request body can not be null or empty.");
if (!providerContext.isValid())
throw new BadRequestException("The request body doesn't seems to be valid");
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(new ObjectMapper().writeValueAsString(providerContext));
} catch (BadRequestException | IllegalArgumentException e) {
return ResponseEntity.badRequest().header("message", e.getMessage())
.contentType(MediaType.APPLICATION_JSON).build();
} catch (DuplicateKeyException keyException) {
return ResponseEntity.badRequest().header("message", "There seems to be farmer config" + keyException.getCause())
.contentType(MediaType.APPLICATION_JSON).build();
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}

Not able to typecast from String to a class in Spring REST

Getting following exception while hitting a Rest endpoint. How do I typecast from String to ProtectPanReplyType class?
Error:
Error - Request: http://localhost:9090/hosted-payments-webapp-1.0.0/pan/protect
raised java.lang.ClassCastException: com.gsicommerce.api.checkout.ProtectPanReplyType cannot be cast to java.lang.String
ProtectPanServiceImpl.java
#Service
public class ProtectPanServiceImpl implements ProtectPanService {
#Override
public ResponseEntity<?> sendProtectPanRequest(ProtectPan protectPan) {
String pan = protectPan.getPaymentAccountNumber();
String tenderClass = protectPan.getTenderClass();
String protectPanRequest = XMLHelper.createProtectPanRequest(pan, tenderClass);
System.out.println("protectPanRequest = " + protectPanRequest);
ResponseEntity<String> response = null;
try {
response = ApiClientUtils.callClientByEndpointandMessage(protectPanRequest, DEV_PUBLIC_API_URL,
ProtectPanReplyType.class);
System.out.println("response.getClass() = " + response.getClass());
//DOES NOT WORK
//ProtectPanReplyType protectPanReplyType = (ProtectPanReplyType)response.getBody();
//THROWS ClassCastException HERE
System.out.println(response.getBody());
} catch (JiBXException e) {
e.printStackTrace();
}
return response;
}
}
ApiClientUtils.java
public ResponseEntity<String> callClientByEndpointandMessage(String xmlRequest, String endpoint, Class<?> replyType) throws JiBXException {
HttpEntity<String> request = createRequestForUser("username", "secret",xmlRequest);
ResponseEntity<String> response = restOperations.postForEntity(endpoint, request, String.class);
ResponseEntity formattedResponse = new ResponseEntity(null, HttpStatus.BAD_REQUEST);
try {
Object jibxObject = JibxHelper.unmarshalMessage(response.getBody(), replyType);
formattedResponse = new ResponseEntity(jibxObject, HttpStatus.OK);
} catch (JiBXException e) {
FaultResponseType faultResponse = JibxHelper.unmarshalMessage(response.getBody(), FaultResponseType.class);
formattedResponse = new ResponseEntity(faultResponse, HttpStatus.BAD_REQUEST);
}
return formattedResponse;
}
ProtectPan.java
public class ProtectPan {
#JsonProperty("paymentAccountNumber")
private String paymentAccountNumber;
#JsonProperty("tenderClass")
private String tenderClass;
public String getPaymentAccountNumber() {
return paymentAccountNumber;
}
public String getTenderClass() {
return tenderClass;
}
}
ProtectPanReplyType.java
public class ProtectPanReplyType {
private String token;
private List<Element> anyList = new ArrayList<Element>();
private String sessionId;
//getters and setter removed for brevity
}
Use ResponseEntity<ProtectPanReplyType> instead ResponseEntity<String>
Build and Return ProtectPanReplyType from your restOperations.postForEntity()
Was finally able to get the object after making following changes.
ApiClientUtils.java
public ResponseEntity<?> callClientByEndpointandMessage(String xmlRequest, String endpoint, Class<?> replyType) throws JiBXException {
HttpEntity<String> request = createRequestForUser("payment", "SONitc2m8y", xmlRequest);
ResponseEntity<String> response = restOperations.postForEntity(endpoint, request, String.class);
ResponseEntity<?> formattedResponse = null;
try {
Object jibxObject = JibxHelper.unmarshalMessage(response.getBody(), replyType);
formattedResponse = new ResponseEntity(jibxObject, HttpStatus.OK);
} catch (JiBXException e) {
FaultResponseType faultResponse = JibxHelper.unmarshalMessage(response.getBody(), FaultResponseType.class);
formattedResponse = new ResponseEntity(faultResponse, HttpStatus.BAD_REQUEST);
}
return formattedResponse;
}
ProtectPanServiceImpl.java
#Override
public ResponseEntity<?> sendProtectPanRequest(ProtectPan protectPan) {
String pan = protectPan.getPaymentAccountNumber();
String tenderClass = protectPan.getTenderClass();
String protectPanRequest = XMLHelper.createProtectPanRequest(pan, tenderClass);
ResponseEntity<?> response = null;
try {
response = publicApiClientUtils.callClientByEndpointandMessage(protectPanRequest, DEV_PUBLIC_API_URL, ProtectPanReplyType.class);
ProtectPanReplyType protectPanReplyType = (ProtectPanReplyType) response.getBody();
System.out.println("protectPanReplyType = " + protectPanReplyType);
} catch (JiBXException e) {
e.printStackTrace();
}
return response;
}

How can I hide signup/ signin(login) link/button after user login.I am using httpSession

I would like to check if session not equals to null,then some button or link will be hidden.Or any other better way to do that?
This is my controller :
#RequestMapping(value = "/signin", method = RequestMethod.GET)
public Object signIn(HttpSession session) {
MemberSignIn signIn = new MemberSignIn();
signIn.setLoginId((String) session.getAttribute("loginId"));
return new ModelAndView("member/signin").addObject("signIn", signIn);
}
#RequestMapping(value = "/signin", method = RequestMethod.POST)
public Object signIn(#ModelAttribute MemberSignIn memberSignIn, HttpSession session, RedirectAttributes redirectAttributes) {
try {
Session s = memberService.signIn(memberSignIn);
session.setAttribute("loginId", memberSignIn.getLoginId());
session.setAttribute("token", s.getToken());
session.setAttribute("memberId", s.getMemberId());
MemberDetail detail = memberService.detail(s.getMemberId());
session.setAttribute("name", detail.getName());
return "redirect:/index";
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return new ModelAndView("member/signin")
.addObject("signIn", memberSignIn)
.addObject("error", e.getMessage());
}
}
HTML:
<li>Sign In</li>
<li>Sign Up</li>

Categories

Resources