Spring boot how to return Json if findById returns null or doesn't find it? - spring

I have an end point that returns json by its id and if it doesn't find it (id doesn't exist) then it should send a Json object saying not found. Here is my attempt.
PetController.java
#GetMapping("{id}")
public ResponseEntity<Pet> getPetById(#PathVariable("id") int petId) {
ResponseEntity<Pet> matchingPet = new ResponseEntity<Pet>(petService.getPetById(petId), HttpStatus.OK);
if(matchingPet != null) {
logger.info("pet found");
return matchingPet;
}
else {
logger.info("pet does not exist");
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
PetService.java
public interface PetService {
Pet getPetById(int petId);
}
PetServiceImpl.java
#Service
public class PetServiceImpl implements PetService {
private PetRepository petrepository;
public PetServiceImpl(PetRepository petrepository) {
this.petrepository = petrepository;
}
#Override
public Pet getPetById(int petId) {
Optional<Pet> pet = petrepository.findById(petId);
if (pet.isPresent()) {
return pet.get();
}
else {
return null;
//return new ResponseEntity<Pet>(HttpStatus.NOT_FOUND); I have tried
//this and it doesn't work either and still returns null without the notfound error.
}
}
}
It still only returns null. This seems like a logical error because I have a logger in my controller and even when I search a pet with an invalid id that does not exist, it still prints "pet found".

You are creating the instance in your Controller as follows ResponseEntity<Pet> matchingPet = new ResponseEntity<Pet>(petService.getPetById(petId), HttpStatus.OK);. Of course matchingPet will always be not null. Try the following:
#GetMapping("{id}")
public ResponseEntity<Pet> getPetById(#PathVariable("id") int petId) {
Pet matchingPet = petService.getPetById(petId);
if(matchingPet != null) {
logger.info("pet found");
return new ResponseEntity<Pet>(matchingPet, HttpStatus.OK);
}
else {
logger.info("pet does not exist");
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

Related

Return mono object from subscribe in restcontroller

I have the following rest controller which reads data from redis and then needs to return some response
#RestController
#RequestMapping("/view")
public class ViewController {
#GetMapping(value = "/{channelId}/**")
public Mono<ResponseEntity<ViewResponse>> viewObject(#PathVariable(value = "channelId") String channelId) {
redisController.getChannelData(channelInfoset, channelId).subscribe(response -> {
if (response != null)
return Mono.just(new ResponseEntity<ViewResponse>(new ViewResponse("val", "1", false), HttpStatus.OK));
else return Mono.just(new ResponseEntity<ViewResponse>(null, HttpStatus.INTERNAL_SERVER_ERROR));
});
}}
This is the redis function to get data
public Mono<Object> getChannelData(String key, String value) {
return reactiveStringRedisTemplate.opsForHash().get(key,value);
}
How can I return the ViewResponse object after subscribe?
Comments from M. Deinum helped me out and was to resolve with
#RestController
#RequestMapping("/view")
public class ViewController {
#GetMapping(value = "/{channelId}/**")
public Mono<ResponseEntity<ViewResponse>> viewObject(#PathVariable(value = "channelId") String channelId) {
return redisController.getChannelData(channelInfoset, channelId).map(response -> {
if (response != null)
return Mono.just(new ResponseEntity<ViewResponse>(new ViewResponse("val", "1", false), HttpStatus.OK));
else return Mono.just(new ResponseEntity<ViewResponse>(null, HttpStatus.INTERNAL_SERVER_ERROR));
});
}}

How to get list of objects using Mono ResponseEntity objects, as it returns single object

#RequestMapping("/api/v1")
public class RemoteActionHistoryController {
public Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>> excaliburData(#PathVariable(name = "deviceId", required = true)
String deviceId) {
return service.getRemoteActionHistory(deviceId);
}
}
public class RemoteActionHistoryServiceImpl {
#Autowired
RemoteActionHistoryRepository arrowFlightRepository;
#Override
public Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>> getRemoteActionHistory(String deviceId) throws Exception {
return (Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>>) arrowFlightRepository.getRemoteActionDetailsByDeviceId(deviceId).collectList().flatMap(mapper);
}
Function<List<RemoteActionHistory>, Mono<ResponseEntityDTO<RemoteActionHistoryDTO>>> mapper = remoteActions -> {
var remoteActionDTO = new RemoteActionHistoryDTO();
if (CollectionUtils.isEmpty(remoteActions)) {
return Mono.justOrEmpty(new ResponseEntityDTO<>(RemoteActionHistoryConstants.CODE_RET_000, null, remoteActionDTO));
}
System.out.println("Printing remoteActions"+remoteActions);
for (RemoteActionHistory excaliburData : remoteActions) {
remoteActionDTO.setStartDateTime(excaliburData.getStartDateTime());
remoteActionDTO.setEndDateTime(excaliburData.getEndDateTime());
remoteActionDTO.setRemoteActionType(excaliburData.getCommand());
remoteActionDTO.setTaskStatus(excaliburData.getStatus());
}
return Mono.justOrEmpty(new ResponseEntityDTO<>(RemoteActionHistoryConstants.CODE_RET_000, null, remoteActionDTO));
};
}
public class RemoteActionHistoryServiceImpl {
#Autowired
RemoteActionHistoryRepository arrowFlightRepository;
#Override
public Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>> getRemoteActionHistory(String deviceId) throws Exception {
return (Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>>) arrowFlightRepository.getRemoteActionDetailsByDeviceId(deviceId).collectList().flatMap(mapper);
}
Function<List<RemoteActionHistory>, Mono<ResponseEntityDTO<RemoteActionHistoryDTO>>> mapper = remoteActions -> {
var remoteActionDTO = new RemoteActionHistoryDTO();
if (CollectionUtils.isEmpty(remoteActions)) {
return Mono.justOrEmpty(new ResponseEntityDTO<>(RemoteActionHistoryConstants.CODE_RET_000, null, remoteActionDTO));
}
System.out.println("Printing remoteActions"+remoteActions);
for (RemoteActionHistory excaliburData : remoteActions) {
remoteActionDTO.setStartDateTime(excaliburData.getStartDateTime());
remoteActionDTO.setEndDateTime(excaliburData.getEndDateTime());
remoteActionDTO.setRemoteActionType(excaliburData.getCommand());
remoteActionDTO.setTaskStatus(excaliburData.getStatus());
}
return Mono.justOrEmpty(new ResponseEntityDTO<>(RemoteActionHistoryConstants.CODE_RET_000, null, remoteActionDTO));
};
}
public class RemoteActionHistoryRepositoryImpl {
#Override
public Flux<RemoteActionHistory> getRemoteActionDetailsByDeviceId(String deviceId) throws Exception {
return Flux.fromIterable(getExcaliburData(String.format(query, tableName, deviceId), true));
}
private List<RemoteActionHistory> getExcaliburData(String query, boolean retry) throws Exception {
List<RemoteActionHistory> remoteActionData = new ArrayList<>();
try (final FlightStream flightStream = adhocFlightClientConfig.createAdhocFlightClient().runQuery(query);) {
while (flightStream.next()) {
if (!flightStream.hasRoot()) {
break;
}
VectorSchemaRoot vectorSchemaRoot = flightStream.getRoot();
TimeStampMilliVector createdDateVector = (TimeStampMilliVector) vectorSchemaRoot
.getVector(RemoteActionHistoryConstants.CREATED_DATE_TIME);
TimeStampMilliVector modifiedDateVector = (TimeStampMilliVector) vectorSchemaRoot
.getVector(RemoteActionHistoryConstants.MODIFIED_DATE_TIME);
RemoteActionHistory remoteAction = null;
for (int i = 0; i < vectorSchemaRoot.getRowCount(); i++) {
remoteAction = new RemoteActionHistory();
remoteAction.setStartDateTime(createdDateVector.isNull(i)? null : new Timestamp(createdDateVector.get(i)));
remoteAction.setEndDateTime(modifiedDateVector.isNull(i)? null : new Timestamp(modifiedDateVector.get(i)));
remoteActionData.add(remoteAction);
}
} catch (Exception ex) {
log.error(String.format("Exception string : %s with retryEnabled is %s", ex.toString(),retry));
if (retry && StringUtils.containsIgnoreCase(ex.toString(), RemoteActionHistoryConstants.UNAUTHENTICATED_ERROR)) {
adhocFlightClientConfig.removeToken();
getExcaliburData(query, false);
}
throw ex;
}
return remoteActionData;
}
}
I have attached the result which I'm currently getting single record. when i debugged the code in the object i have multiple records but it shows only one record in postman

How to send a HTTP response in Zuul PRE_TYPE Filter

I want to prevent not logged user form accessing the proxy. I can throw an exception but the response is 404 instead of `401 or '403'. It it possible?
Filter code:
#Component
public class CustomZuulFilter extends ZuulFilter {
//FIXME - if 401,403 get the new token??, fallbackMethod = "fall",
#HystrixCommand(
commandProperties = {
#HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
#HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
}
)
#Override
public Object run() {
logger.debug("Adding zulu header");
String userName = getLoggedUser();
RequestContext ctx = RequestContext.getCurrentContext();
if (userName == null) {
// throw new RuntimeException("User not authenticated");
logger.info("User not authenticated");
ctx.setResponseStatusCode(401);
ctx.sendZuulResponse();
return null;
}
return null;
}
private String getLoggedUser() {
[...]
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public String filterType() {
return PRE_TYPE;
}
#Override
public int filterOrder() {
return PRE_DECORATION_FILTER_ORDER - 1;
}
}
It might be a bit late, but i think you can remove ctx.sendZuulResponse();
and add ctx.setSendZuulResponse(false);

spring data jpa dynamic query which has IN clause

I want to create dynamic query in spring data jpa. Doing many search I can implement it, but I came across a problem when I add IN operator in where clause. I need to check id IN (longlist)
Here is my entity class
#Entity
#Table(name = "view_detail")
public class ViewDetailDom {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
#Column(name = "user_id")
private Long userId;
private String description;
Here is specification builder class and specification class
public class ViewDetailSpecificationsBuilder {
private final List<SearchCriteria> params;
public ViewDetailSpecificationsBuilder() {
params = new ArrayList<SearchCriteria>();
}
public ViewDetailSpecificationsBuilder with(String key, Operation operation, Object value) {
params.add(new SearchCriteria(key, operation, value));
return this;
}
public Specification<ViewDetailDom> build() {
if (params.size() == 0) {
return null;
}
List<Specification<ViewDetailDom>> specs = new ArrayList<Specification<ViewDetailDom>>();
for (SearchCriteria param : params) {
specs.add(new ViewDetailSpecification(param));
}
Specification<ViewDetailDom> result = specs.get(0);
for (int i = 1; i < specs.size(); i++) {
result = Specifications.where(result).and(specs.get(i));
}
return result;
}
}
public class ViewDetailSpecification implements Specification<ViewDetailDom> {
private SearchCriteria criteria = new SearchCriteria();
public ViewDetailSpecification(SearchCriteria searchCriteria) {
this.criteria.setKey(searchCriteria.getKey());
this.criteria.setOperation(searchCriteria.getOperation());
this.criteria.setValue(searchCriteria.getValue());
}
#Override
public Predicate toPredicate(Root<ViewDetailDom> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
String value = criteria.getValue().toString().replaceAll(" ", "%");
if (criteria.getOperation() != null && criteria.getOperation() != Operation.DEFAULT) {
if (criteria.getOperation() == Operation.GREATHERTHANEQUALTO) {
return builder.greaterThanOrEqualTo(root.<String>get(criteria.getKey()), value);
} else if (criteria.getOperation() == Operation.LESSTHANEQUALTO) {
return builder.lessThanOrEqualTo(root.<String>get(criteria.getKey()), value);
} else if (criteria.getOperation() == Operation.EQUAL) {
return builder.equal(root.<String>get(criteria.getKey()), value);
} else if (criteria.getOperation() == Operation.IN) {
Path<Long> view = root.<Long>get(criteria.getKey());
return view.in(criteria.getValue());
}
} else {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(builder.lower(root.<String>get(criteria.getKey())),
"%" + value.toLowerCase() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), value);
}
}
return null;
}
}
This method creates specification builder:
public ViewDetailSpecificationsBuilder createSearchSpecifications(ViewSearch view) {
ViewDetailSpecificationsBuilder builder = new ViewDetailSpecificationsBuilder();
if (StringUtils.isNotBlank(view.getName())) {
builder.with("name", Operation.DEFAULT, view.getName());
}
if (StringUtils.isNotBlank(view.getDescription())) {
builder.with("description", Operation.DEFAULT, view.getDescription());
}
return builder;
}
And finally I do this:
ViewDetailSpecificationsBuilder builder = createSearchSpecifications(view);
builder.with("userId", Operation.DEFAULT, userSessionHelper.getUserId());
builder.with("id", Operation.IN, viewids);
Specification<ViewDetailDom> spec = builder.build();
viewDetailDao.findAll(spec);
But I am getting following error:
"Unaware how to convert value [[5, 7, 8] : java.util.ArrayList] to requested type [java.lang.Long]; nested exception is java.lang.IllegalArgumentException: Unaware how to convert value [[5, 7, 8] : java.util.ArrayList] to requested type [java.lang.Long]"
I have resolved this problem in this way:
ViewDetailSpecification class:
if (criteria.getOperation() == Operation.IN) {
final List<Predicate> orPredicates = new ArrayList<Predicate>();
List<Long> viewIds = (List<Long>) criteria.getValue();
for (Long viewid : viewIds) {
orPredicates.add(builder.or(builder.equal(root.<String>get(criteria.getKey()), viewid)));
}
return builder.or(orPredicates.toArray(new Predicate[orPredicates.size()]));
}
In kotlin I have the same error, I change the ArrayList to Array, with this code:
fun values(): Array<String> {
val elems = arrayListOf<String>()
return elems.toTypedArray()
}
Try you convert ArrayList to array, for java see: make arrayList.toArray() return more specific types

Trying to call code in my controller but getting Null Reference error

Don't want to over-complicate the issue, but I think I need to post all the code that's hooked into this error.
Using MvcMailer and introduced a separate Send mechanism (for use with Orchard CMS' own EMail).
The MvcMailer Code:
1) AskUsMailer.cs:
public class AskUsMailer : MailerBase, IAskUsMailer
{
public AskUsMailer()
: base()
{
//MasterName = "_Layout";
}
public virtual MvcMailMessage EMailAskUs(AskUsViewModel model)
{
var mailMessage = new MvcMailMessage { Subject = "Ask Us" };
ViewData.Model = model;
this.PopulateBody(mailMessage, viewName: "EMailAskUs");
return mailMessage;
}
}
2) IAskUsMailer.cs:
public interface IAskUsMailer : IDependency
{
MvcMailMessage EMailAskUs(AskUsViewModel model);
}
3) AskUsController.cs: (GETTING NULL REFERENCE ERROR BELOW)
[Themed]
public ActionResult Submitted()
{
//This is the new call (see new code below):
//Note: Debugging steps through eMailMessagingService,
//then shows the null reference error when continuing to
//SendAskUs
eMailMessagingService.SendAskUs(askUsData);
//Below is normal MvcMailer call:
//AskUsMailer.EMailAskUs(askUsData).Send();
return View(askUsData);
}
Note: askUsData is defined in a separate block in the controller:
private AskUsViewModel askUsData;
protected override void OnActionExecuting(ActionExecutingContext
filterContext)
{
var serialized = Request.Form["askUsData"];
if (serialized != null) //Form was posted containing serialized data
{
askUsData = (AskUsViewModel)new MvcSerializer().
Deserialize(serialized, SerializationMode.Signed);
TryUpdateModel(askUsData);
}
else
askUsData = (AskUsViewModel)TempData["askUsData"] ??
new AskUsViewModel();
TempData.Keep();
}
protected override void OnResultExecuted(ResultExecutedContext
filterContext)
{
if (filterContext.Result is RedirectToRouteResult)
TempData["askUsData"] = askUsData;
}
I did not know how to get my EMailMessagingService.cs (see below) call into the controller, so in a separate block in the controller I did this:
private IEMailMessagingService eMailMessagingService;
public AskUsController(IEMailMessagingService eMailMessagingService)
{
this.eMailMessagingService = eMailMessagingService;
}
I think this is part of my problem.
Now, the new code trying to hook into Orchard's EMail:
1) EMailMessagingServices.cs:
public class EMailMessagingService : IMessageManager
{
private IAskUsMailer askUsMailer;
private IOrchardServices orchardServices;
public EMailMessagingService(IAskUsMailer askUsMailer,
IOrchardServices orchardServices)
{
this.orchardServices = orchardServices;
this.askUsMailer = askUsMailer;
this.Logger = NullLogger.Instance;
}
public ILogger Logger { get; set; }
public void SendAskUs(AskUsViewModel model)
{
var messageAskUs = this.askUsMailer.EMailAskUs(model);
messageAskUs.To.Add("email#email.com");
//Don't need the following (setting up e-mails to send a copy anyway)
//messageAskUs.Bcc.Add(AdminEmail);
//messageAskUs.Subject = "blabla";
Send(messageAskUs);
}
....
}
The EMailMessagingService.cs also contains the Send method:
private void Send(MailMessage messageAskUs)
{
var smtpSettings = orchardServices.WorkContext.
CurrentSite.As<SmtpSettingsPart>();
// can't process emails if the Smtp settings have not yet been set
if (smtpSettings == null || !smtpSettings.IsValid())
{
Logger.Error("The SMTP Settings have not been set up.");
return;
}
using (var smtpClient = new SmtpClient(smtpSettings.Host,
smtpSettings.Port))
{
smtpClient.UseDefaultCredentials =
!smtpSettings.RequireCredentials;
if (!smtpClient.UseDefaultCredentials &&
!String.IsNullOrWhiteSpace(smtpSettings.UserName))
{
smtpClient.Credentials = new NetworkCredential
(smtpSettings.UserName, smtpSettings.Password);
}
if (messageAskUs.To.Count == 0)
{
Logger.Error("Recipient is missing an email address");
return;
}
smtpClient.EnableSsl = smtpSettings.EnableSsl;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
messageAskUs.From = new MailAddress(smtpSettings.Address);
messageAskUs.IsBodyHtml = messageAskUs.Body != null &&
messageAskUs.Body.Contains("<") &&
messageAskUs.Body.Contains(">");
try
{
smtpClient.Send(messageAskUs);
Logger.Debug("Message sent to {0} with subject: {1}",
messageAskUs.To[0].Address, messageAskUs.Subject);
}
catch (Exception e)
{
Logger.Error(e, "An unexpected error while sending
a message to {0} with subject: {1}",
messageAskUs.To[0].Address, messageAskUs.Subject);
}
}
}
Now, in EMailMessagingService.cs I was getting an error that things weren't being implemented, so I auto-generated the following (don't know if this is part of my error):
public void Send(Orchard.ContentManagement.Records.ContentItemRecord recipient, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public void Send(System.Collections.Generic.IEnumerable<Orchard.ContentManagement.Records.ContentItemRecord> recipients, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public void Send(System.Collections.Generic.IEnumerable<string> recipientAddresses, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public bool HasChannels()
{
throw new NotImplementedException();
}
public System.Collections.Generic.IEnumerable<string> GetAvailableChannelServices()
{
throw new NotImplementedException();
}
2) IEMailMessagingServices.cs
public interface IEMailMessagingService
{
MailMessage SendAskUs(AskUsViewModel model);
}
MvcMailer works fine without this addition (outside of Orchard), but I am trying to get everything working within Orchard.
I just cannot figure out what I am doing wrong. Any thoughts?
Sorry for excessive code.
IEmailMessaginService does not implement IDependency, so it can't be found by Orchard as a dependency. That's why it's null.

Resources