Autodesk java api response mapping - autodesk-forge

We are using the forge-api-java-client. There is an issue in Model Derivatives getManifest call.
The response fails mapping with a single Message String being returned instead of the expected String Array.
Have switched to using local build of the jar, change in file Message.java to include an alternative constructor for the class setMessage
public void setMessage(String message) {
List<String> messages = new ArrayList<>();
messages.add(message);
setMessage(messages);
}
Could this change be merged into the project.

We'll check it, but as of today, that package is just under maintenance. You are welcome to submit a PR.

Related

spring boot return escaped json

my code
#GetMapping(value = {"/metadata"}, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public String getMetadata() {
return dppService.getMetadata();
}
the method getMetadata will just return a json string. it just read data from the json file, and it is in another library can not be changed.
But when call this api, i got the follow reponse:
"{\"Namespace\":\"com.xxx\"...
the json string was escaped.
expected:
"{"Namespace":"com.xxx"...
How could i make it return the right json? BTW, our other services also return a json string in the controller, but their response will not be escaped which is so confused for me.
You could do this two ways:
From what I could understand you are having this issues because you might be returning the json as a string from from the service method dppService.getMetadata() by converting it manually to a string. If so , change that and instead return a POJO class from the service method as well as the controller, spring default jackson converter should automatically convert it to a json when the request is served. (I would suggest you go with this approach)
Another approach (the hacky less desirable one) if you still want to keep returning a string then you could configure the StringMessageConverter like below to accept json:
#Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
stringConverter.setSupportedMediaTypes(Arrays.asList( //
MediaType.TEXT_PLAIN, //
MediaType.TEXT_HTML, //
MediaType.APPLICATION_JSON));
converters.add(stringConverter);
}
root cause:
There is a configuration file in the project:
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter(jacksonBuilder().build()));
converters.stream()
.filter(converter -> converter instanceof MappingJackson2HttpMessageConverter)
.findFirst()
.ifPresent(converter -> ((MappingJackson2HttpMessageConverter) converter).setDefaultCharset(UTF_8));
}
This configuration overrite the defualt jackson behavior. There are two ways to solve this issue:
1.Remove this configuration, then it will be the default behavior
2.Add the StringHttpMessageConverter in this configuration, see Ananthapadmanabhan's option2

How to force DotNetCore 2.1 Web API to output Json format? What library do I need?

I be straight to the point. I am in the process of converting ASP.Net web services into DotNetCore 2.1 services. My question is very simple. How do I get json output from a string (with a GET verb)?
I'm new at this, but almost every piece of documentation and recommendations do not work with DotNetCore.
Obviously, the following will not work:
[HttpGet]
public string Get()
{
return "{\"country_code\":\"US\",\"country_name\":\"United States\",\"region_name\":\"California\",\"city_name\":\"Los Angeles\",\"latitude\":\"34.052230\",\"longitude\":\" - 118.243680\",\"zip_code\":\"90001\",\"time_zone\":\" - 08:00\"}";
}
I just need to convert this string (or tell the client) that I want the output in json. The following does not work either - got a squiggly line under the "Json(" method and, for the life of me, can't find a reference to make it go away (I pulled it from an example, so they must be using a 3rd party json parsing library or there's a reference that I'm missing)
[HttpGet]
public JsonResult Get()
{
return Json("{\"country_code\":\"US\",\"country_name\":\"United States\",\"region_name\":\"California\",\"city_name\":\"Los Angeles\",\"latitude\":\"34.052230\",\"longitude\":\" - 118.243680\",\"zip_code\":\"90001\",\"time_zone\":\" - 08:00\"}", "application/json");
}
Ideally, I'd like to serialize an object to json, but figured I'd start with something ridiculously simple.
Anywho, if anyone can help.
If you don't already have a strongly typed model, you can build an anonymous type and return that from the controller
Simple Example.
public class MyController: Controller {
[HttpGet]
public IActionResult Get() {
var model = new {
country_code = "US",
country_name = "United States",
region_name = "California",
city_name = "Los Angeles",
latitude = 34.052230,
longitude = -118.243680,
zip_code = 90001,
time_zone = "- 08:00"
};
return Ok(model); //200 OK with content
}
}
In more complex scenarios you would get your objects from a data source.
No library needed, the framework out of the box will serialize the object(s) into JSON for you by default unless otherwise configured.
If you insist on passing a manually formatted string then use the ContemntResult object. Pass it the string and the content type.
[HttpGet]
public IActionResult Get() {
string json = "{\"country_code\":\"US\",\"country_name\":\"United States\",\"region_name\":\"California\",\"city_name\":\"Los Angeles\",\"latitude\":\"34.052230\",\"longitude\":\" - 118.243680\",\"zip_code\":\"90001\",\"time_zone\":\" - 08:00\"}";
return Content(json, new MediaTypeHeaderValue("application/json"));
}
Reference Format response data in ASP.NET Core Web API
Forcing a Particular Format
If you would like to restrict the response formats for a specific action you can apply the
[Produces] filter. The [Produces] filter specifies the response
formats for a specific action (or controller). Like most Filters, this
can be applied at the action, controller, or global scope.
[Produces("application/json")]
public class AuthorsController
The [Produces] filter will force all actions within the
AuthorsController to return JSON-formatted responses, even if other
formatters were configured for the application and the client provided
an Accept header requesting a different, available format.
Don't return string but object. So result of your actions are json string this is why you will get string in JSON and not an object
Make sure that your client is sending header "Content-Type": "application/json".
[HttpGet]
public Address Get()
{
return new Address{ CountryCode = "US"} ;
}

How to create angularjs springboot application that stores data to a mysql database. using json

I'm kinda stuck on this topic.
This is what i already found out.
A good tutorial was :
Using MySQL in Spring Boot via Spring Data JPA and Hibernate
http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/
I also found some information how to make single page application with hsqldb.
But i really want to create something that permanent saves the users data to the database using mysql.
But in order to use angular http i need json. Can i convert the urls like
/create?email=[email]&name=[name]
To json how should i proceed. Does anyone knows good tutorials on this. Or are there better way's to proceed.
The simplest/handy way to consuming JSON with Spring Boot is using a Java class that resembles your JSON (https://stackoverflow.com/a/6019761).
So, you can follow the tutorial you linked, then use a controller like this one to handle JSONs:
#RestController
public class UserController {
#RequestMapping(
value = "/user/create",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> createUser(#RequestBody User user) {
try {
// Handle the User object here
userDao.save(user);
}
catch (Exception ex) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
}
// ...
}
Receiving a JSON like this (at the url /user/create):
{email: "john#doe.com", name: "John Doe"}
An user will be saved in your database.
Responding with JSON
Moreover, if you want to send a response as JSON from your controller you should create a java object then send it back as response, within the ResponseEntity object.
For example, suppose to have this class:
public class SuccessDto {
private String success;
public SuccessDto(String success) {
this.success = success;
}
}
You can change your controller in this way:
public ResponseEntity<SuccessDto> createUser(#RequestBody User user) {
// ...
return new ResponseEntity<>(
new SuccessDto("true"),
HttpStatus.OK
);
}
and you will have this JSON as response
{success: "true"}
if you have already managed to use it with HSQLDB, it's juste a matter of database properties (like the JDBC URL) and schema initialization.
Can you provide the code sample of the controller, how you save the data (via a Repository or a simple DAO ?) and the application.properties

How to Get a Json from api/metrics of sonarqube?

I tried to use the GET method of api/metrics to retrieve a JSON to use for my program, but the documentation lack to describe all the parameter to use in the requestUrl.
for example in for my program I find, using the Google Chrome console, that the requestUrl is this one:
http://localhost:9000/api/resources?resource=my%3AjavaSample%3AMandria%2Fsrc%2Fmandria%2FIllnessException.java&metrics=new_technical_debt%2Cblocker_violations%2Cburned_budget%2Cbusiness_value%2Cclasses%2Ccomment_lines%2Ccomment_lines_density%2Ccomplexity%2Cclass_complexity%2Cfile_complexity%2Cfunction_complexity%2Cbranch_coverage%2Cnew_it_branch_coverage%2Cnew_branch_coverage%2Cconfirmed_issues%2Ccoverage%2Cnew_it_coverage%2Cnew_coverage%2Ccritical_violations%2Cdirectories%2Cduplicated_blocks%2Cduplicated_files%2Cduplicated_lines%2Cduplicated_lines_density%2Cfalse_positive_issues%2Cpackage_tangles%2Cfiles%2Cfile_complexity_distribution%2Cfunctions%2Cfunction_complexity_distribution%2Cgenerated_lines%2Cgenerated_ncloc%2Cit_branch_coverage%2Cit_coverage%2Cit_line_coverage%2Cit_uncovered_conditions%2Cit_uncovered_lines%2Cinfo_violations%2Cviolations%2Cline_coverage%2Cnew_it_line_coverage%2Cnew_line_coverage%2Clines%2Cncloc%2Clines_to_cover%2Cnew_it_lines_to_cover%2Cnew_lines_to_cover%2Cmajor_violations%2Cminor_violations%2Cnew_blocker_violations%2Cnew_critical_violations%2Cnew_info_violations%2Cnew_major_violations%2Cnew_minor_violations%2Cnew_violations%2Copen_issues%2Coverall_branch_coverage%2Cnew_overall_branch_coverage%2Coverall_coverage%2Cnew_overall_coverage%2Coverall_line_coverage%2Cnew_overall_line_coverage%2Cnew_overall_lines_to_cover%2Coverall_uncovered_conditions%2Cnew_overall_uncovered_conditions%2Coverall_uncovered_lines%2Cnew_overall_uncovered_lines%2Cpackage_cycles%2Cpackage_feedback_edges%2Cpackage_tangle_index%2Cprojects%2Cpublic_api%2Cpublic_documented_api_density%2Cpublic_undocumented_api%2Calert_status%2Creopened_issues%2Csqale_rating%2Cskipped_tests%2Cstatements%2Cteam_size%2Csqale_index%2Csqale_debt_ratio%2Cuncovered_conditions%2Cnew_it_uncovered_conditions%2Cnew_uncovered_conditions%2Cuncovered_lines%2Cnew_it_uncovered_lines%2Cnew_uncovered_lines%2Ctests%2Ctest_execution_time%2Ctest_errors%2Ctest_failures%2Ctest_success_density
is it possible to find a more detailed documentation or the way I try to solve my problem is not the correct one?
Just add &format=json to the parameters.
See http://docs.sonarqube.org/display/SONARQUBE43/Web+Service+API#WebServiceAPI-ResponseFormats
In response to your question how to call from a outside comment:
If you want to call the SonarQube Web Service API from a Java program you can use the Apache HTTP Client:
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpGet httpGet = new HttpGet("http://localhost:9000/api/resources?metrics=lines");
try(CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);) {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
}
}
In this case it prints all projects on SonarQube and additionaly the metric "lines". You can add multiple metrics to the list, separated by a comma:
"http://localhost:9000/api/resources?metrics=lines,blocker_violations"

Unable to update collaboration, using update collaboration API in box-java-sdk-v2

I am trying to integrate Box with Kerika using box-java-sdk-v2. Library is added as maven dependency (net.box:boxjavalibv2) in the project.
Everything is working fine, except the update collaboration API. API call from the project looks like follow:
BoxCollabRequestObject requestObject = BoxCollabRequestObject.updateCollaborationObject(permission);
return client().getCollaborationsManager().
updateCollaboration(collaborationId, requestObject);
I searched google a lot to find the solution of this. But, I didn't get any. So, I have logged the issue at box-java-sdk-v2 issues on GitLab.
After spending some more time after a day a found that issue is with the Java library itself. There isn't any problem with Box API. I concluded this by accessing REST API directly from Advanced REST Client instead of Java library, and it worked.
So, as work around (Until the bug from the Java SDK is not officially fixed and release), I have updated my code as follows:
// As client library update function is not working properly so I have written custom code to deal with it.
BoxCollabRequestObject requestObject = BoxCollabRequestObject.updateCollabObjects(permission);
BoxCollaborationsManagerImpl boxCollaborationsManager = (BoxCollaborationsManagerImpl)client().getCollaborationsManager();
BoxUpdateCollaborationRequest request = new BoxUpdateCollaborationRequest(boxCollaborationsManager.getConfig(), boxCollaborationsManager.getJSONParser(), collaborationId, requestObject);
return (BoxCollaboration) boxCollaborationsManager.getResponseAndParseAndTryCast(request, BoxResourceType.COLLABORATION, boxCollaborationsManager.getJSONParser());
and the BoxUpdateCollaborationRequest class in the above code is self made. It looks like as follow:
public class BoxUpdateCollaborationRequest extends DefaultBoxRequest
{
private static final String URI = "/collaborations/%s";
public BoxUpdateCollaborationRequest(IBoxConfig config, IBoxJSONParser parser, String id, BoxCollabRequestObject requestObject) throws BoxRestException
{
super(config, parser, getUri(id), RestMethod.PUT, requestObject);
}
public static String getUri(final String id) {
return String.format(URI, id);
}
}
I noticed that the real problem in their original implementation is just the constant. It should be
private static final String URI = "/collaborations/%s";
Instead of
private static final String URI = "/collaboration/%s";
I am filing this issue here to help others who is having the same issue and searching Stack Overflow for the solution.