Spring Boot Java Request GET Request Mapping URL problems - spring-boot

How to turn this 【http://myurl.com/test/api/v1/data/?:getlicense=1234】
to this way 【http://myurl.com/test/api/v1/data/:getlicense/1234】
The code below using postman GET http://myurl.com/test/api/v1/data/?:getlicense=1234 will return result success.
Below is my code:
#RequestMapping(value="/api/v1/data/" ,produces=MediaType.APPLICATION_JSON_VALUE,headers="Accept=*/*",method = { RequestMethod.GET })
public Map ReturnData(#RequestParam(":getlicense") String getdata) {
Map returns = new HashMap();
try {
queryData qD= new queryData ();
qD.setData(getdata);
returns = result.getdataList(qD);
} catch (Exception e) {
e.printStackTrace();
}
return returns;
}
please help me, thank you.

You have to convert your RequestParam to a PathVariable
#GetMapping("/api/v1/data/licenses/{id}")
public Map returnData(#PathVariable(value = "id") String id) {
Map returns = new HashMap();
try {
queryData qD= new queryData ();
qD.setData(id);
returns = result.getdataList(qD);
} catch (Exception e) {
e.printStackTrace();
}
return returns;
}

Please find below solution
#RequestMapping(value="/api/v1/data/licenses/{id}" ,produces=MediaType.APPLICATION_JSON_VALUE,headers="Accept=*/*",method = { RequestMethod.GET })
public Map ReturnData(#PathVariable(value = "id") String id) {
Map returns = new HashMap();
try {
queryData qD= new queryData ();
qD.setData(id);
returns = result.getdataList(qD);
} catch (Exception e) {
e.printStackTrace();
}
return returns;
}

Related

How to mock the optional ResponseEntity code below for code coverage. Could someone please assist?

public ResponseEntity<Optional> getData(#RequestBody RequestModel requestModel) {
try {
List mango = new ArrayList();
mangoRepository.findByMangoTag(
requestModel.getMangoTag(),
requestModel.getMangoProduct(),
requestModel.getSellerType()).forEach(mango::add);
Optional<Mango> res = mango.stream().findFirst();
if (!res.isPresent()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(res, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}

Handling multipart response from spring rest controller

I am having controller method like this
#PostMapping(path = "/downloadAttachment",
produces = "application/octet-stream")
public ResponseEntity<?> downloadAttachment(#Valid #RequestBody Attachment attachmentModel) {
refreshProp(false);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try {
String byteRes = null;
JSONArray responseFromDownloadAttachment =
databaseOperations.downloadAttachment(attachmentModel);
if (responseFromDownloadAttachment.length() == 0) {
return new ResponseEntity<>("", HttpStatus.NO_CONTENT);
}
else {
for (int blobRes = 0; blobRes < responseFromDownloadAttachment.length(); blobRes++) {
JSONObject blobObj = responseFromDownloadAttachment.getJSONObject(blobRes);
if (blobObj != null) {
byteRes = (String) blobObj.getString("file");
}
}
}
byte[] byteArrray = byteRes.getBytes();
return new ResponseEntity<>(byteArrray, HttpStatus.OK);
} catch (Exception e) {
log.error("Exception occurred!" + e);
e.printStackTrace();
JSONObject errObj = new JSONObject();
errObj.put("status", "E");
errObj.put("message", e);
return new ResponseEntity<>(errObj.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
I am sending byte array as response.But i am not sure which type of file i will be getting from service layer.It can be in any form like xlsx,txt,png,jpg or any multimedia.I am setting headers to octet-stream and also produces to octet-stream.Can i use octet-stream to handle these type of responses?

ASP.Net web api2 - not working when the api returns a boolean

I am using Postman to test an ASP.Net web api 2 application that I created using I created using VS 2017.
It uses ADO.Net to call stored procedures. I tested the stored procedures and they work fine. I created a console app to test the methods and they work fine.
The URL that returns a model object works fine.
http://localhost:56224/api/profileandblog/getactiveuser/2020-03-03/DancinDan/32.211.50.62/1
The URL that returns a boolean does not. I get Error - 404.0 - Not Found
http://localhost:56224/api/profileandblog/validatelogin/2020-03-03/DancinDan/Morewealth1/32.211.50.62
Here is the dataaccesslayer.cs in my Models folder:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using GbngWebApi2.ADO_Utilities;
namespace GbngWebApi2.Models
{
public class DataAccessLayer
{
DatabaseFunctions dbFunc = new DatabaseFunctions();
public bool ValidateLogin(DateTime currentDateTime, string userName, string userPassword, string ipAddress)
{
bool returnedStatus = false;
try
{
dbFunc.OpenDB();
SqlCommand cmd = new SqlCommand("dbo.ValidateLogin", dbFunc.objConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#a_CurrentDateTime", currentDateTime);
cmd.Parameters.AddWithValue("#a_UserName", userName);
cmd.Parameters.AddWithValue("#a_UserPassword", userPassword);
cmd.Parameters.AddWithValue("#a_IpAddress", ipAddress);
// Set the OUT parameter.
cmd.Parameters.Add("#a_PasswordStatusSwitchOut", SqlDbType.Bit);
cmd.Parameters["#a_PasswordStatusSwitchOut"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
// Get the value from the OUT parameter.
// Cast to Boolean.
returnedStatus = (bool)cmd.Parameters["#a_PasswordStatusSwitchOut"].Value;
return returnedStatus;
}
catch (SqlException sqlex)
{
throw sqlex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbFunc.CloseDB();
}
}
public User GetActiveUser(DateTime currentDateTime, string userName, string ipAddress, int userId)
{
User user = new User();
SqlDataReader userDataReader = null;
try
{
dbFunc.OpenDB();
SqlCommand cmd = new SqlCommand("dbo.GetActiveUser", dbFunc.objConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#a_CurrentDateTime", currentDateTime);
cmd.Parameters.AddWithValue("#a_UserName", userName);
cmd.Parameters.AddWithValue("#a_IpAddress", ipAddress);
cmd.Parameters.AddWithValue("#a_UserId", userId);
userDataReader = cmd.ExecuteReader();
while (userDataReader.Read())
{
user.UserId = Convert.ToInt32(userDataReader["UserId"]);
user.UserName = userDataReader["UserName"].ToString();
user.ActiveSwitch = Convert.ToInt32(userDataReader["ActiveSwitch"]);
user.ApiAccessSwitch = Convert.ToInt32(userDataReader["ApiAccessSwitch"]);
user.AdminSwitch = Convert.ToInt32(userDataReader["AdminSwitch"]);
user.BlogAuthorSwitch = Convert.ToInt32(userDataReader["BlogAuthorSwitch"]);
user.BlogUserName = userDataReader["BlogUserName"].ToString();
user.IpAddress = userDataReader["IpAddress"].ToString();
user.IpAddressUsedForRegisteringCount = Convert.ToInt32(userDataReader["IpAddressUsedForRegisteringCount"]);
user.LoginCount = Convert.ToInt32(userDataReader["LoginCount"]);
user.ModifiedCount = Convert.ToInt32(userDataReader["ModifiedCount"]);
user.SuggestionCount = Convert.ToInt32(userDataReader["SuggestionCount"]);
user.SelectedForPublicViewSwitch = Convert.ToInt32(userDataReader["SelectedForPublicViewSwitch"]);
user.ModifiedDateTime = Convert.ToDateTime(userDataReader["ModifiedDateTime"]);
user.CreatedDateTime = Convert.ToDateTime(userDataReader["CreatedDateTime"]);
}
return user;
}
catch (SqlException sqlex)
{
throw sqlex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (userDataReader != null)
{
userDataReader.Close();
}
dbFunc.CloseDB();
}
}
}
}
Here is the WebApi2Controller:
using System;
using System.Web.Http;
using GbngWebApi2.Models;
namespace GbngWebApi2.Controllers
{
[RoutePrefix("api/profileandblog")]
public class WebApi2Controller : ApiController
{
DataAccessLayer dataaccesslayer = new DataAccessLayer();
[HttpGet]
[Route("validatelogin/{currentDateTime}/{userName}/{userPassword}/{ipAddress}")]
public bool ValidateLogin(DateTime currentDateTime, string userName, string userPassword, string ipAddress)
{
try
{
// Returns a boolean indicator of success or failure.
return dataaccesslayer.ValidateLogin(currentDateTime, userName, userPassword, ipAddress);
}
catch (Exception)
{
throw;
}
}
[HttpGet]
[Route("getactiveuser/{currentDateTime}/{userName}/{ipAddress}/{userId}")]
public User GetActiveUser(DateTime currentDateTime, string userName, string ipAddress, int userId)
{
try
{
// Returns the active "user" from the database.
return dataaccesslayer.GetActiveUser(currentDateTime, userName, ipAddress, userId);
}
catch (Exception)
{
throw;
}
}
}
}
From Nkosi: Add a slash at the end and it will work /32.211.50.62/

I want to upload file without using multipart in spring boot, would be great if I could get you valuable suggestions on this

Shall I remove this from application.properties
spring.http.multipart.enabled=true
What should be my approach towards this file upload without using multipart?
This way, I'm able to uploading file using where I'm using multipart.
#RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
public JsonNode dogCreation(HttpServletRequest httpRequest, #RequestParam(value = "picture", required = false) MultipartFile multipartFile,
#PathVariable("name") String name) throws IOException, InterruptedException {
JSONObject response = new JSONObject();
Dog dog = new Dog();
String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";
try {
File file = new File(DOG_IMAGES_BASE_LOCATION);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
dog = dogService.getDogByName(name);
if (dog == null) {
if (!multipartFile.isEmpty()) {
String multipartFileName = multipartFile.getOriginalFilename();
String format = multipartFileName.substring(multipartFileName.lastIndexOf("."));
try {
Path path = Paths.get(DOG_IMAGES_BASE_LOCATION + "/" + name + format);
byte[] bytes = multipartFile.getBytes();
File file = new File(path.toString());
file.createNewFile();
Files.write(path, bytes);
if (file.length() == 0) {
response = utility.createResponse(500, Keyword.ERROR, "Image upload failed");
} else {
String dbPath = path.toString().replace('\\', '/');
dog = new Dog();
dog.setName(name);
dog.setPicture(dbPath);
dog = dogService.dogCreation(dog);
response = utility.createResponse(200, Keyword.SUCCESS, "Image upload successful");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return objectMapper.readTree(response.toString());
}
I want to do it without using multipart, what would you suggest?
This is what I've done till now to solve this
#RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
public JsonNode dogCreation(HttpServletRequest httpRequest, #RequestParam("picture") String picture,
#PathVariable("name") String name) throws IOException, InterruptedException {
JSONObject response = new JSONObject();
Dog dog = new Dog();
String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";
try {
File file = new File(DOG_IMAGES_BASE_LOCATION);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
dog = dogService.getDogByName(name);
if (dog == null) {
if (!picture.isEmpty()) {
String dogPicture = picture;
byte[] encodedDogPicture = Base64.encodeBase64(dogPicture.getBytes());
String format = dogPicture.substring(picture.lastIndexOf("."));
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
return objectMapper.readTree(response.toString());
}
I just have to say that this should probably only be used as a workaround.
On your frontend, convert the file to base64 in js:
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt) {
console.log(evt.target.result);
//do POST here - something like this:
$.ajax("/upload64", {
method: "POST",
contentType: "application/text"
data: evt.target.result
}
};
On the server with an example of a decoder - more decoding options here Decode Base64 data in Java
import sun.misc.BASE64Decoder;
#PostMapping("/upload64")
public String uploadBase64(#RequestBody String payload){
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
//use your bytes
}

download csv using spring boot and apache commons

I have this below code for downloading CSV as an ajax button click, But the file is not downloading. Only showing the black new tab on the browser.
#RequestMapping(value = "/batch/download", method = RequestMethod.POST, produces = "text/csv")
#ResponseBody
public void downloadNGIBatchSelected(HttpServletResponse response) throws IOException {
List<String> ids = Arrays.asList("1312321","312313");
generateNewCustomerCSV(response.getWriter(),ids);
}
private void generateNewCustomerCSV(PrintWriter writer, List<String> ids){
String NEW_LINE_SEPARATOR = "\n";
//CSV file header
Object[] FILE_HEADER = {"Token Number",
"Token Expiry Date",
};
CSVPrinter csvPrinter = null;
try {
csvPrinter = new CSVPrinter(new BufferedWriter(writer), CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));
//Create CSV file header
csvPrinter.printRecord(FILE_HEADER);
for (PolicyMap PolicyMap : policyMaps) {
List customerCSV = new ArrayList();
customerCSV.add(PolicyMap.getInsurancePolicy().getTokenNo());
try {
csvPrinter.printRecord(customerCSV);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.flush();
writer.close();
csvPrinter.close();
} catch (IOException e) {
System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
e.printStackTrace();
}
}
}
You have set the content type in #RequestMapping annotation. But it is not going to work in the case when response is being written using HttpServletResponse. In this case, instead of spring, HttpServletResponse is writing the response that's why you have to set the response type in the response before getting the writer.
response.setContentType ("application/csv");
response.setHeader ("Content-Disposition", "attachment; filename=\"nishith.csv\"");

Resources