Restlet Studio Error 422 when generating sample client and server - rest

Hi I'm using the restlet studio to generate a client and server from your sample pet store API . Here are my steps:
Generate Java Server (JAX-RS)
Edit pom.xml to make a war file
mvn package
Deploy to jetty server as webapp
Verify it works by going to hitting the URL with a browser:
http://54.149.215.125:8080/v2/pet/findByTags
Response:
{"code":4,"type":"ok","message":"magic!"}
At this point I think it works, until I generate the client in Java
I change the endpoint from the webnik one to my webserver
Make a simple main method
public static void main(String[] args) {
try {
FindPetByTagsClientResource a = new FindPetByTagsClientResource();
Pet represent = a.represent();
} catch (Exception ex) {
Logger.getLogger(APIPetStore.class.getName()).log(Level.SEVERE, null, ex);
}
}
When I run it I get this:
run:
Starting the internal HTTP client
null
Unprocessable Entity (422) - The server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the contained instructions
at org.restlet.resource.Resource.toObject(Resource.java:893)
at org.restlet.engine.resource.ClientInvocationHandler.invoke(ClientInvocationHandler.java:326)
at com.sun.proxy.$Proxy5.represent(Unknown Source)
at net.apispark.webapi.client.FindPetByTagsClientResource.represent(FindPetByTagsClientResource.java:22)
at apipetstore.APIPetStore.main(APIPetStore.java:28)
Caused by: java.io.IOException: Unable to create the Object representation
at org.restlet.engine.converter.DefaultConverter.toObject(DefaultConverter.java:282)
at org.restlet.service.ConverterService.toObject(ConverterService.java:229)
at org.restlet.resource.Resource.toObject(Resource.java:889)
... 4 more
Caused by: java.lang.IllegalArgumentException: The serialized representation must have this media type: application/x-java-serialized-object or this one: application/x-java-serialized-object+xml
at org.restlet.representation.ObjectRepresentation.(ObjectRepresentation.java:221)
at org.restlet.representation.ObjectRepresentation.(ObjectRepresentation.java:123)
at org.restlet.representation.ObjectRepresentation.(ObjectRepresentation.java:104)
at org.restlet.engine.converter.DefaultConverter.toObject(DefaultConverter.java:279)
... 6 more
BUILD SUCCESSFUL (total time: 0 seconds)
Change the main method to this and it works:
public static void main(String[] args) {
try {
FindPetByTagsClientResource a = new FindPetByTagsClientResource();
a.getClientResource().get().write(System.out);
} catch (Exception ex) {
Logger.getLogger(APIPetStore.class.getName()).log(Level.SEVERE, null, ex);
}
}
Output:
Starting the internal HTTP client
{"code":4,"type":"ok","message":"magic!"}
Any ideas on how I can fix this?

In fact, the JAXRS server skeleton is really a server skeleton ;-) This means that it doesn't actually send back the right content according to the client. If you look at the server code, you always see this:
public Response findPetsByTags(#ApiParam(value = "Tags to filter by") #QueryParam("tags") List<String> tags)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
}
It doesn't correspond to a list of pet objects...
On the client side, you got the error since you try to use annotated interfaces. They automatically try to use the internal converter of Restlet. It fails since it expects an object of type Pet and you received something with this structure: {"code":4,"type":"ok","message":"magic!"}.
In conclusion, you need to do some work to adapt the server skeleton to return the correct objects. Here is an hardcoded solution to make work your client SDK:
#GET
#Path("/findByTags")
#ApiOperation(value = "Finds Pets by tags", notes = "Finds Pets by tags", response = Pet.class, responseContainer = "List")
#ApiResponses(value = {
#ApiResponse(code = 400, message = "") })
public Response findPetsByTags(#ApiParam(value = "Tags to filter by") #QueryParam("tags") List<String> tags)
throws NotFoundException {
// do some magic!
Pet pet = new Pet();
pet.setId(10);
pet.setName("My pet");
pet.setStatus("status");
List<Tag> actualTags = new ArrayList<Tag>();
Tag tag1 = new Tag();
tag1.setId(1);
tag1.setName("tag1");
actualTags.add(tag1);
Tag tag2 = new Tag();
tag2.setId(2);
tag2.setName("tag2");
actualTags.add(tag2);
pet.setTags(actualTags);
return Response.ok().entity(pet).build();
}
I'll have a look if we can improve this for the server side. In fact, the Restlet Studio internally uses the swagger2 codegen tool chain to generate this server skeleton.
Hope it helps,
Thierry

Related

handle Exceptions from API server in client server

I am trying to learn how to handle exception in APIs servers so I followed this where he has built API for birds, he finally reached to APIs like this:
#GetMapping(value = "/params")
public Bird getBirdRequestParam(#RequestParam("birdId") Long birdId) throws EntityNotFoundException {
Bird bird = birdRepository.findOne(birdId);
if(bird == null){
throw new EntityNotFoundException(Bird.class, "id", birdId.toString());
}
return bird;
}
and the ControllerAdvice has a method:
#ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<Object> handleEntityNotFound(
EntityNotFoundException ex) {
ApiError apiError = new ApiError(NOT_FOUND);
apiError.setMessage(ex.getMessage());
return buildResponseEntity(apiError);
}
the response will be a bird like this
{
"id": 1,
"scientificName": "Atlantic canary",
"specie": "serinus canaria",
"mass": 10,
"length": 11
}
or an exception details like this:
{
"apierror": {
"status": "NOT_FOUND",
"timestamp": "09-04-2018 10:11:44",
"message": "Bird was not found for parameters {id=2}"
}
but the problem is with my server that contacts with API
I am using :
public void gett(#RequestParam Long id) {
ResponseEntity<Bird> responseEntity = restTemplate.getForEntity("http://localhost:8181/params" + id, Bird.class);
bird = responseEntity.getBody();
model.addAttribute("birdform", bird);
return "bird";
}
the getForEntity is waiting for a response with bird body but an exception may be thrown in server and the response may be json of the error.
how to handle this problem in my client server?
in other words :
how to know in my client server that the api server has thrown an exception in json form.???
I have tried to get the response in "Object" variable and then try to know if it was excption or bird with "instance of" expression like this code
#GetMapping("/getbird")
public String getAll(#RequestParam Long id, Model model) {
ResponseEntity<Object> responseEntity = restTemplate.getForEntity("http://localhost:8181/api/bird/getone?id=" + id, Object.class);
if (responseEntity.getBody() instanceof Bird.class) {
Bird bird= (Bird) responseEntity.getBody();
model.addAttribute("Bird", bird);
return "bird-form";
}
else{
// something else
return "someview";
}
}
but first thing it didnot work (the instance of always return false)
the second thing is that this is a hard work to do with all my controllers' actions.
I hope that i could explain my problem clearly .
thanks....
You don't need to check the body of the response to see if you got an error. restTemplate.getForEntity() (and other methods) would throw an HttpClientErrorException if you get a 4XX response, or HttpServerErrorException if you get a 5XX response from the call.
To catch these exceptions, you can define a #ControllerAdvice with proper methods for exception handling:
#ControllerAdvice
class GlobalControllerExceptionHandler {
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 500
#ExceptionHandler(HttpClientErrorException.class)
public ApiError handle4xxFromClient(HttpClientErrorException ex) {
// construct and return a custom ApiError object
}
}
See https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc for details.
Two solutions :
Use a custom implementation error handler in your reste template.
restTemplate.setErrorHandler(customerErrorHandler)
Use the http status, rest template will throw an exception if it gets a bad http status from the server it is querying. Catch the exception and get the ApiError Object from the exception, and then throw and exception of your own that will be handled by your exception handler in your client server.
For these solutions to work, the server your are querying needs to send the right http status code when something wrong happens.

Apache FOP: upgrading from 1.1 to 2.1

I am following the migration guide, but I don't seem to get it right.
In FOP 1.1 I have this working code:
public class XsltFactory {
private static final String FO_CONFIG_FILE = "/path/to/fop-config.xml";
private static FopFactory fopFactory;
private static synchronized void initFopFactory(final ServletContext context) throws Exception {
Configuration cfg = new DefaultConfigurationBuilder().build(XsltFactory.class.getResourceAsStream(FO_CONFIG_FILE));
fopFactory = FopFactory.newInstance();
fopFactory.setURIResolver(new ServletContextURIResolver(context));
fopFactory.setUserConfig(cfg);
}
}
I adapted the above code to stick with FOP 2.1:
public class XsltFactory {
private static final String FO_CONFIG_FILE = "/path/to/fop-config.xml";
private static FopFactory fopFactory;
private static synchronized void initFopFactory(final ServletContext context) throws Exception {
Configuration cfg = new DefaultConfigurationBuilder().build(XsltFactory.class.getResourceAsStream(FO_CONFIG_FILE));
FopFactoryBuilder fopFactoryBuilder = new FopFactoryBuilder(
new URI(ServletContextURIResolver.SERVLET_CONTEXT_PROTOCOL),
new URIResolverAdapter(new ServletContextURIResolver(context))
);
fopFactoryBuilder.setConfiguration(cfg);
fopFactory = fopFactoryBuilder.build();
}
}
But I get the following error:
java.lang.Exception: Fail to create PDF
at ....web.controller.PrintPdfController.renderPdf(PrintPdfController.java:181)
[...]
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
Caused by: java.net.URISyntaxException: Expected scheme-specific part at index 16: servlet-context:
at java.net.URI$Parser.fail(URI.java:2829)
at java.net.URI$Parser.failExpecting(URI.java:2835)
at java.net.URI$Parser.parse(URI.java:3038)
at java.net.URI.<init>(URI.java:595)
[...]
... 42 common frames omitted
The PDF fails to load, since it failed at being created.
EDIT:
After adding + "///" after SERVLET_CONTEXT_PROTOCOL the context, I now get:
Caused by: java.net.MalformedURLException: unknown protocol: servlet-context
at java.net.URL.<init>(URL.java:592)
at java.net.URL.<init>(URL.java:482)
at java.net.URL.<init>(URL.java:431)
at java.net.URI.toURL(URI.java:1096)
at org.apache.fop.fonts.FontDetectorFactory$DefaultFontDetector.detect(FontDetectorFactory.java:94)
... 59 common frames omitted
After a few days of investigation, the migration has finally been done successfully. The problem was coming from the URI resolver, and fixing this problem created new problems, which I solved subsequently.
The guide at https://xmlgraphics.apache.org/fop/2.1/upgrading.html is of relatively limited help.
The core of the problem is the URI resolver. You now have to define a custom resolver, but NOT as in the example provided at:
https://xmlgraphics.apache.org/fop/2.0/servlets.html
ResourceResolver resolver = new ResourceResolver() {
public OutputStream getOutputStream(URI uri) throws IOException {
URL url = getServletContext().getResource(uri.toASCIIString());
return url.openConnection().getOutputStream();
}
public Resource getResource(URI uri) throws IOException {
return new Resource(getServletContext().getResourceAsStream(uri.toASCIIString()));
}
};
The right way of doing it is:
ResourceResolver resolver = new ResourceResolver() {
public OutputStream getOutputStream(URI uri) throws IOException {
URL url = context.getResource(uri.getPath());
return url.openConnection().getOutputStream();
}
public Resource getResource(URI uri) throws IOException {
return new Resource(context.getResourceAsStream(uri.getPath()));
}
};
Instead of uri.toASCIIString(), the correct syntax is uri.getPath().
In addition, we had to remove all "servlet-context:" markup in fonts URIs (in fop-config.xml) and images URIs (in any XSL transformation file or template).
Finally, I got an issue with hyphenation: FOP could not find .hyp files anymore, because for some reason, the baseUri was being used instead of the custom context resolver (I had to dig into FOP's source files to find out). So, I had to modify the getResource method of my custom resolver. I know this is a hack, but it works and it is sufficient for me as I already spent three days on this problem):
public OutputStream getOutputStream(URI uri) throws IOException {
URL url = context.getResource(uri.getPath());
return url.openConnection().getOutputStream();
}
public Resource getResource(URI uri) throws IOException {
InputStream stream = null;
/*
* For some reason, in FOP 2.x, the hyphenator does not use the
* classpath fop-hyph.jar.
*
* This causes trouble as FOP tries to find "none.hyp" in the
* war directory. Setting
* <hyphenation-base>/WEB-INF/hyph</hyphenation-base> in the
* fop-config.xml file does not solve the issue. The only
* solution I could find is to programmatically detect when a
* .hyp file is trying to be loaded. When this occurs, I modify
* the path so that the resolver gets the right resource.
*
* This is a hack, but after spending three days on it, I just
* went straight to the point and got a workaround.
*/
if (uri.getPath().endsWith('.hyp')) {
String relUri = uri.getPath().substring(uri.getPath().indexOf(baseUri.getPath()) + baseUri.getPath().length());
stream = context.getResourceAsStream(FopManager.HYPH_DIR + relUri);
} else {
stream = context.getResourceAsStream(uri.getPath());
}
Resource res = new Resource(stream);
return res;
}
};
Note that I also had to create the none.hyp file manually, since it does not exist in the .hyp files provided by OFFO. I just copied en.hyp and renamed it none.hyp. This solved my last problem.
I hope this saves someone a few days of work ;)

httpunit PutMethodWebRequest throws IOException; bad file descriptor

Could someone explain why this httpunit test case keeps failing in wc.getResponse with "bad file descriptor". I added the is.close() as a guess and moved it before and after the failure but that had no effect. This tests put requests to a Dropwizard app.
public class TestCircuitRequests
{
static WebConversation wc = new WebConversation();
static String url = "http://localhost:8888/funl/circuit/test.circuit1";
#Test
public void testPut() throws Exception
{
InputStream is = new FileInputStream("src/test/resources/TestCircuit.json");
WebRequest rq = new PutMethodWebRequest(url, is, "application/json");
wc.setAuthentication("FUNL", "foo", "bar");
WebResponse response = wc.getResponse(rq);
is.close();
}
No responses? So I'll try myself based on what I learned fighting this.
Httpunit is an old familiar tool that I'd use if I could. But it hasn't been updated in more than two years, so I gather its support for #PUT requests isn't right.
So I converted to Jersey-client instead. After a bunch of struggling I wound up with this code which does seem to work:
#Test
public void testPut() throws Exception
{
InputStream is = new FileInputStream("src/test/resources/TestCircuit.json");
String circuit = StreamUtil.readFully(is);
is.close();
Authenticator.setDefault(new MyAuthenticator());
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
com.sun.jersey.api.client.WebResource service = client.resource(url);
Builder builder = service.accept(MediaType.APPLICATION_JSON);
builder.entity(circuit, MediaType.APPLICATION_JSON);
builder.put(String.class, circuit);
return;
}
This intentionally avoids JAX-RS automatic construction of beans from JSON strings.

FOP/ikvm: error "Provider com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl not found"

I have produced a fop.dll from fop-1.0 with ikvm:
ikvmc -target:library -reference:IKVM.OpenJDK.Core.dll -recurse:{myPathToJars}\*.jar -version:1.0 -out:{myPathToJars}\fop.dll
If I use my fop.dll in a Windows Application, everything works perfect.
If I use it in a Class Library, I get the following error:
"Provider com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl not found" at javax.xml.transform.TransformerFactory.newInstance()
The code line is: TransformerFactory factory = TransformerFactory.newInstance();
Here is the code of method:
public static void xmlToPDF(String xmlPath, String xslPath, SortedList arguments, String destPdfPath)
{
java.io.File xmlfile = new java.io.File(xmlPath);
java.io.File pdffile = new java.io.File(destPdfPath);
try
{
// configure fopFactory as desired
FopFactory fopFactory = FopFactory.newInstance();
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
// configure foUserAgent as desired
// Setup output
OutputStream outputStream = new java.io.FileOutputStream(pdffile);
outputStream = new java.io.BufferedOutputStream(outputStream);
try
{
// Construct fop with desired output format
Fop fop = fopFactory.newFop("application/pdf" /*MimeConstants.MIME_PDF*/, foUserAgent, outputStream);
// Setup XSLT
TransformerFactory factory = TransformerFactory.newInstance();
java.io.File xsltfile = new java.io.File(xslPath);
Transformer transformer = factory.newTransformer(new StreamSource(xsltfile.getAbsoluteFile()));
// Set the value of a in the stylesheet
if (arguments != null)
{
IList keys = arguments.GetKeyList();
foreach (var key in keys)
{
Object value = arguments[key];
transformer.setParameter(key.ToString(), value);
}
}
// Setup input for XSLT transformation
Source src = new StreamSource(xmlfile);
// Resulting SAX events (the generated FO) must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
transformer.transform(src, res);
}
catch (Exception e1)
{
System.Console.WriteLine(e1.Message);
}
finally
{
outputStream.close();
}
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
I used ikvm-0.46.0.1 to make my fop.dll (based on fop 1.0). I included the following jars:
avalon-framework-4.2.0.jar
batik-all-1.7.jar
commons-io-1.3.1.jar
commons-logging-1.0.4.jar
fop.jar
serializer-2.7.0.jar
xalan-2.7.0.jar
xercesImpl-2.7.1.jar
xml-apis-1.3.04.jar
xml-apis-ext-1.3.04.jar
xmlgraphics-commons-1.4.jar
Any idea why this error occurs? Why is the behaviour different between Windows Application and Class Library?
Addition 10/19/11:
I managed to get working the following:
MyMainPrg (a Windows Forms Application)
MyFopWrapper (a Class Library that calls fop.dll)
But for my case this is not the solution, because in my target project, I have the following structure:
MainCmdLinePrg (a Console Application; calls DLL_1)
DLL_1 (calls DLLsharedFop) {there are several DLLs that can call DLLsharedFop}
DLLsharedFop (calls directly fop.dll; or - I don't care - might call MyFopWrapper)
Unfortunately this construct results in the error.
You can shorten to a pair (ACmdLinePrg,MyFopWrapper): already this does not work! But (MyMainPrg,MyFopWrapper) does...
Here is how I got that error and how I resolved:
My solultion looks like this:
ClientApp (references)--> ClassLibrary1
My ClassLibrary1 public functions are using, but not exposing any IKVM related objects, therefore the caller (ClientApp) did not have to add IKVM references. All is good in compile time.
However in runtime, the situation is different. I got the same exception and realized that ClientApp also needed to reference the correct IKVM dll (IKVM.OpenJDK.XML.Transform.dll) that contains "com.sun.org.apache.xalan.#internal.xsltc.trax" namespace.
I resolved a similar problem by adding the following before the problematic line:
var s = new com.sun.org.apache.xerces.#internal.jaxp.SAXParserFactoryImpl();
var t = new com.sun.org.apache.xalan.#internal.xsltc.trax.TransformerFactoryImpl();
As described here
Do you have the dll with the missing class in your working directory?
If you have the dll then it is a classloader problem. Look in the IKVM wiki. Often the BootClassPathAssemby help.
I was using NuGet Packages of FOP.dll v1.1.0 and IKVM pacakges of v7.1.45 in C#.NET app. I got this issue on Windows 2016 x64 server with error messages like:
------------------------------ Fop.cs (111): Provider com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
not found - at javax.xml.transform.TransformerFactory.newInstance()
Fop.cs (125): Provider
com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl not found
- at javax.xml.parsers.SAXParserFactory.newInstance()\r\n at org.apache.avalon.framework.configuration.DefaultConfigurationBuilder..ctor(Boolean
enableNamespaces)\r\n at
org.apache.avalon.framework.configuration.DefaultConfigurationBuilder..ctor()\r\n
I resolved the problem by adding those two lines at begins of procedure
com.sun.org.apache.xerces.#internal.jaxp.SAXParserFactoryImpl s = new com.sun.org.apache.xerces.#internal.jaxp.SAXParserFactoryImpl();
com.sun.org.apache.xalan.#internal.xsltc.trax.TransformerFactoryImpl t = new com.sun.org.apache.xalan.#internal.xsltc.trax.TransformerFactoryImpl();
helpful link:
https://github.com/KevM/tikaondotnet/issues/21

Form Instantiation time in Restlet

I am new to Restlet framework and I have the following time issue in the post method of my server resource.
My post method code
#Post
public Representation represent(Representation entity){
try{
//Thread.sleep(1000);
long start = System.currentTimeMillis();
Form aForm = new Form(getRequestEntity());
System.err.println("FORM Instantiation TIME: " + (System.currentTimeMillis()-start));
}catch(Exception ex){
ex.printStackTrace();
}
return new StringRepresentation("hello");
}
On different trails, the output that I am getting is 1900-1999 ms. But if I uncomment the line Thread.sleep(1000), then the time output is 900-999 ms. Can any one please confirm what is happening when instantiation the Form object and why the time is always 1900+ ms. Sorting out this time issue is important for me as I have to implement token based authentication to reduce the post method processing time.
Sorry for late reply. The restlet version I am using is 2.0.7
Here is the details
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
VirtualHost aHost = component.getDefaultHost();
aHost.attach("/sample", new MyApplication());
component.getLogger().setLevel(Level.OFF);
component.start();
System.err.println("REST SERVICE STARTED ON PORT NUMBER 8182...");
}
I am running this application in local and not in any Web/App Server.