Is it possible to have a list of string as query param in JSONDoc ?
My code works, but i can't test it on JSONDoc.
My url is for example:
/url?statut=A&statut=B
Here is how the JSONDoc shows the test parameters :
So i can't test with multiples status .
Here is my code :
#GET
#Path("/url")
#Produces(MediaType.APPLICATION_JSON)
#ApiMethod(path = "url?statut={statut}", verb = ApiVerb.GET, description = "", produces = {
MediaType.APPLICATION_JSON })
#ApiResponseObject(clazz = MyClass.class)
public Response get(
#ApiQueryParam(name = "statut", description = "status list") #QueryParam("statut") final List<String> statuts ){
log.info("get status :" + statuts);
return ...;
}
Related
I am currently trying to return an input stream via my API. The input stream contains an html file that I previously fetch from Jenkins via the Cdancy Jenkinsclient via the input stream. I want to pass this html through my endpoint. If I enter Json as #Produce, then the HTML content comes with the note that the JSON can not be parsed. If I specify another MediyType, then a 406 comes back. Is it even bestpractise to return an inputstream or should I transform it into an outputstream first?
This is my Code:
Endpoint
#GET
#Path(API_RESOURCE_IMAGE_REPORT)
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#Operation(summary = "", description = "")
#APIResponses(
value = {
#APIResponse(
responseCode = "200",
description =
"",
content = #Content(mediaType = MediaType.APPLICATION_JSON)),
#APIResponse(
responseCode = "400",
description = "",
content =
#Content(
mediaType = MediaType.APPLICATION_JSON,
schema = #Schema(implementation = ErrorResponseDO.class))),
})
public Response getReport(#Parameter(
description = "",
required = true)
#PathParam("imageName") final String imageName,
#Parameter(description = "", required = true)
#PathParam("tag") final String tag,
#Parameter(description = "")
#PathParam("type") String type
) throws ApplicationException, IOException {
InputStream report = jenkinsClient.getReport(imageName, tag, type);
return Response.status(HttpURLConnection.HTTP_ACCEPTED).entity(report).build();
}
Jenkinsclient:
public InputStream getReport(final String imageName, final String tag, final String type) throws ApplicationException {
try {
final int lastSuccessfulBuildnumber = jenkinsClient.api().jobsApi().jobInfo(imageName, tag).lastSuccessfulBuild().number();
LOG.info("Last successful buildnumber: " + lastSuccessfulBuildnumber);
final InputStream report = jenkinsClient.api().jobsApi().artifact(imageName, tag, lastSuccessfulBuildnumber, Objects.equals(type, "image") ? "trivy_image_report.html" : "trivy_Dockerfile_report.html");
if (report == null) {
throw new NotFoundException();
}
return report;
} catch (Exception e) {
throw new NotFoundException();
}
}
Output:
Output is 406 everytime (TEXT_HTML, OCTET_STREAM, TEXT_PLAINE).
Only with #Produces(MediaType.APPLICATION_JSON) it is successfull with the html code bud with the message: json cant be parsed.
Thanks for your help
Like VGR stated. Problem was the caller which was not using text/html. Ive tested in swaggerui and set it to "text/html". Works as expected. Was application/json beforen and the reason for working only with application json as produce annoation.
Please help the beginner.
When sending a request to the requestBody json I get:
key: "{
"grant_type" : "client_credentials",
"client_id" : "OC_CLIENT_ID",
"client_secret" : "OC_CLIENT_SECRET"
}"
value: ""
and it is required that the requestBody looks like this
{
key:"grant_type"
value: "client_credentials"
}
{
key:"client_id"
value: "OC_CLIENT_ID"
}
{
key:"client_secret"
value: "OC_CLIENT_SECRET"
}
The server sent for some reason not a set of parameters, but simply stuck json into the name of the first parameter.
The code is:
#Path("/")
public interface OAuth2RequestService {
#POST
AccessTokenRecord create(#HeaderParam(value = "Content-type") String type,
#FormParam(value = "grant_type") String grantType,
#FormParam(value = "client_id") String clientId,
#FormParam(value = "client_secret") String clientSecret);
}
#Override
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public OAuth2Interceptor getAccessTokenInterceptor(Account account,
Boolean isGeneralEpaService) {
if (openAmIsEnabled(account)) {
final FeignOptions<OAuth2RequestService> options =
new FeignOptions<>(getAccessTokenUrl(account, isGeneralEpaService));
final AccessTokenRecord accessTokenRecord = workerRestService(options)
.create(HEADER_TYPE, CLIENT_CREDENTIALS, getClientId(isGeneralEpaService),
getClientSecret(isGeneralEpaService));
logger.infof("OAuth2 access token retrieval succeeded.");
return new OAuth2Interceptor(accessTokenRecord);
}
final AccessTokenRecord accessTokenRecord = new AccessTokenRecord();
accessTokenRecord.setAccessToken(getOsDefaultAccessToken(account));
accessTokenRecord.setTokenType(TOKEN_TYPE);
return new OAuth2Interceptor(accessTokenRecord);
}
private OAuth2RequestService workerRestService(
final FeignOptions<OAuth2RequestService> options) {
final Request.Options requestOptions =
new Request.Options(options.getConnectionTimeOut(), options.getReadTimeOut());
return Feign.builder().options(requestOptions).client(new OkHttpClient())
.contract(new JAXRSContract()).encoder(new JacksonEncoder())
.decoder(new JacksonDecoder()).decode404()
.target(OAuth2RequestService.class, options.getHostUrl());
}
I have tried several options with #QueueParam #FormParam
I'm trying to send "search" parameters to Spring Controller but keep getting the 400 bad request . I tried #RequestParam("personalNumber")String personalNumber but it still doesn't work, so now I'm trying to get the wrapper , can you suggest how to send wrapper info to Java controller ? (Wrapper has instances of other classes)
AngularJs
angular.extend($scope, {
obj:{
personalNumber:"",
firstName:"",
lastName:"",
dateFrom:"",
dateTo:""
},
loadCarLoan: urls.BASE_API + "user/getOnlineApplicationList",
carLoanList:[
],
});
$scope.getCarLoan = function () {
$(".loader").show();
console.log("In the angular");
$http.post($scope.loadCarLoan + $.param($scope.obj))
.success(function (response) {
console.log(response);
if(response.success){
$scope.carLoanList = response;
}
$(".loader").hide();
}).error(function () {
$(".loader").hide();
$scope.carLoanList = [];
})
};
$scope.filter = function () {
$scope.getCarLoan();
};
Java Controller :
#RequestMapping(value = "user/getOnlineApplicationList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
public #ResponseBody String getOnlineApplicationList(HttpSession session,
#RequestBody OnlineApplicationListWrapper wrapper) {
System.out.println("In the Controller Java");
HashMap<String, Object> jsonMap = new HashMap<>();
Car car = wrapper.getCar();
Loan loan = wrapper.getLoan();
CustPaymentPlan cpp = wrapper.getCpp();
NaturalPerson np = wrapper.getPerson();
jsonMap.put("success", "true");
jsonMap.put("car", car);
jsonMap.put("loan", loan);
jsonMap.put("cpp", cpp);
jsonMap.put("np", np);
System.out.println(wrapper.getCar().toString());
System.out.println(wrapper.getLoan().toString());
System.out.println(wrapper.getCpp().toString());
System.out.println(wrapper.getPerson().toString());
System.out.println("========");
System.out.println(gson.toJson(jsonMap));
return gson.toJson(jsonMap);
}
You need to change:
#RequestParam("personalNumber") String personalNumber
To:
#RequestParam(value = "personalNumber", required = false) String personalNumber
The required = false indicates to spring that the parameter can be optional.
No need to create a wrapper
As shown in the image, it says "Response Class (Status 200)" for the add operation. However, the add operation has been implemented in such a way that it will never return 200. It returns 201 on success.
My question is how can I change the (Status 200) to (Status 201)?
The code for this part is as follows:
#RequestMapping(method = RequestMethod.PUT, value = "/add")
#ApiOperation(value = "Creates a new person", code = 201)
#ApiResponses(value = {
#ApiResponse(code = 201, message = "Record created successfully"),
#ApiResponse(code = 409, message = "ID already taken")
})
public ResponseEntity<String> add(#RequestParam(value = "name", required = true) String name,
#RequestParam(value = "id", required = true) String id) {
if (PD.searchByID(id).size() == 0) {
Person p = new Person(name, id);
PD.addPerson(p);
System.out.println("Person added.");
return new ResponseEntity<String>(HttpStatus.CREATED);
} else {
System.out.println("ID already taken.");
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
Thanks!
You can add the #ResponseStatus annotation to any a controller method to define the http status it should return. Ex
Adding the following annotation on acontroller method:
#ResponseStatus(code = HttpStatus.CREATED)
Will return a HTTP status 201 (Created)
Adding the following annotation in controller method (method = requestMethod.PUT) or (method = requestMethod.POST)
#ResponseStatus (code = HttpStatus.ACCEPTED)
I know it is a simple one . But couldn't find a solution.
My jQuery-ajax will be ,
var json = {"message":"Message123","time":"time123","name":"test123"}
data : JSON.stringify(json),
My Spring controller will be ,
#RequestMapping(value = "chat.html", method=RequestMethod.GET )
public #ResponseBody String getChat() {
System.out.println("Entered in to the controller ");
String name == ???
String msg == ???
String time == ???
//Process the functionality using the msg,name,time
return "Json String";
}
How can I get the values of the name, message , time.
Hope our stack members will help me.
var json = {"message":"Message123","time":"time123","name":"test123"}
data : JSON.stringify(json) should have a key ,
data : {json:{"message":"Message123","time":"time123","name":"test123"}},
url:/json/test
Controller
#RequestMapping(value = {"json/test"},method = RequestMethod.GET)
#ResponseBody
public String jsonTest(String json){
JSONObject jsonObject = JSONObject.fromObject(json);
String m = jsonObject.get("message").toString();
String t = jsonObject.get("time").toString();
String n = jsonObject.get("name").toString();
}
I use the net.sf.json.JSONObject
You can use org.Json jar from this link ...
Then try this code, I have done is in my current project and is working fine and efficiently
var json = {"message":"Message123","time":"time123","name":"test123"}
$.ajax({
type: "POST",
url: "/chat.html",
data: "jsonObject="+json,
success: function(response) {
// your success code
},
error: function(e) {
// your error code
}
});
In controller change your code like this
#RequestMapping(value = "/chat.html", method=RequestMethod.POST )
public #ResponseBody String getChat(HttpServletRequest req,HttpServletResponse res) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(req.getParameter("jsonObject"));
} catch(JSONException _instance) {
// Exception Handle Message
}
System.out.println("Entered in to the controller ");
String name ="" , msg = "", time = "";
if(jsonObject.has("name")) {
name = jsonObject.getString("name");
}
... // Do it for other variables also
//Process the functionality using the msg,name,time
return "Json String";
}