Import xml namespace from custom Dataweave module - mule

I'm trying to create a custom Dataweave module for centralizing my custom XML namespaces.
I followed the official document of Mulesoft:https://docs.mulesoft.com/mule-runtime/4.3/dataweave-create-module
it states that: "When you import a custom module into another DataWeave script, any functions, variables, types, and namespaces defined in the module become available for use in the DataWeave body".
So I was expecting that I could create a module (in modules folder) containing my namespaces like this: Namespaces.dwl
ns myNs1 http://namespaces/my1
ns myNs2 http://namespaces/my2
import that module in another Dataweave like this:
%dw 2.0
import * from modules::Namespaces
output application/java
---
{
body: {
myNs1#Response: {
outcome: 'ACCEPTED'
}
} write "application/xml"
}
But I got this error:
The prefix myNs1 has not been previously declared using ns
I'm running on Mule 4.3.0

As aled have pointed out, it might have been a bug or incorrect information in the docs. From what I can see, the namespaces are properly imported but it seems that prefixes are expected to be declared locally.
You can use below:
%dw 2.0
import * from modules::Namespaces
output application/java
var myNs1Local = myNs1 as Namespace
---
{
body: {
myNs1Local#Response: {
outcome: 'ACCEPTED'
}
} write "application/xml"
}
which will result to the expected output.
{
body: "<?xml version='1.0' encoding='UTF-8'?>\n<myNs1:Response xmlns:myNs1=\"http://namespaces/my1\">\n <outcome>ACCEPTED</outcome>\n</myNs1:Response>" as String {class: "java.lang.String"}
} as Object {encoding: "UTF-8", mediaType: "*/*", mimeType: "*/*", class: "java.util.LinkedHashMap"}
Notice here that what I used as the prefix is the declared variable (myNs1Local) but it still write the prefix as referenced in Namespace.dwl

Related

Fastify response schema with $merge-keyword throws FST_ERR_SCH_BUILD

When adding a response schema to a fastify resource that leverages the $merge keyword, an error
FST_ERR_SCH_BUILD: Failed building the schema for GET: /, due error undefined unsupported
is thrown.
Schema looks like the following, but the same error is thrown using the examples from ajv or fastify.
response: {
200: {
$merge: {
source: {
type: 'object',
properties: {
foo: { type: 'string' }
}
},
with: {
type: 'object',
properties: {
bar: { type: 'string' }
}
}
}
}
}
workaround described in own answer
I have found a workaround for this:
it seems that unlike when using $merge in any other schema, either fastify or ajv require the type keyword to be present on $merge level.
This might be a bug, as it can be deduced from the merged objects and the methodology works when using $merge for other schemas.
The serializer doesn't implement the ajv's schema customization (as it is $merge). Under the hood fast-json-stringify is used by default.
You should use standard JSON schema and its combining keywords.
In fastify v2 the serializer that uses the schemas is not customizable, so you should write your own serializer and set up it using setReplySerializer.

Mule Dataweave: How to dynamically map HTTP response(JSON) to XML output

I am building an application, where I have to hit a restful interface, and pass a specific section of the response to the UI.
The response model is quite huge with a lot of fields(String, array of objects, object,number datatypes), so using manual transformation is a big pain.
Is there a way to map the section of the response to a variable and directly send it to the UI.
I tried,
%dw 2.0
%output application/xml
%var UserAcct= payload.UserResponse.UserDetailsResp.UserAccounts
---
{
User: {
"UserAccount": {
Account: UserAcct
}
}
}
This doesn't work because, the payload has List, Array of Objects etc in the response and mapping to a variable throws an error. Is it possible to send the section payload.UserResponse.UserDetailsResp.UserAccounts directly in dataweave?? Please help.
It will be more helpful if you add Input payload, error and XML output.
Following is the code just by assuming your scenario. You can give this a try:
%dw 2.0
output application/xml
---
{
User: {
"UserAccount": {
(payload.UserResponse.UserDetailsResp.UserAccounts map {
Address:{
<XMLFieldName>: $.<respectiveJSONFieldToMap>
....
}
})
}
}
}

Swagger definition errors

Trying to use Swagger on my JAX-RS application with enunciate Maven plugin.
The generated JSON definition works well.
But when I try to validate it online with Swagger Editor, the converted YAML file has some weird errors.
For example:
Definition:
parameters:
- name: body
in: body
type: file
description: 'Bla bla'
responses:
'201':
ERROR:
Parameters with "type: file" must have "in: formData"
JAX-RS Code:
#POST
#Path(value = "/validatedata")
public Response validate(ValidateDataFromInput validateDataFromInput) throws CustomException {
return Response.status(Status.ACCEPTED).entity(validationActionService.getDataFromInput(validateDataFromInput.getConsumerInput(),
validateDataFromInput.getValidateInput(), null)).build();
}
I am using: swagger-core-1.5.21 and enunciate-maven-plugin-2.11.1.
Not sure which is wrong here.

Symfony - No Extension Is Able To Load The Configuration (Subscriber/Event Listening) (REST API Exception Handling with JSON output)

Purpose
Hello, I am fairly new to Symfony and am trying to create an exception/error handling functionality for our Web API.
Requirements
When a user makes an invalid request to our API, we want to return a simple JSON object that looks something like the following:
{"errorCode": 1234567, "errorMessage": "Parameter 1 is invalid. String expected"}
In addition to API-specific errors, we also want to hook into the built-in exception-handling in Symfony and re-use that, but instead of returning an HTML error page (which is what happens by default), we want to return a JSON object like:
{"errorCode": 404, "errorMessage": "Not found"}
Current Approach
Obviously, we want this to be implemented in the most efficient way, so after doing some research, I found what I think is a great approach which I can then adapt to our specific needs. Here is the tutorial I followed:
https://knpuniversity.com/screencast/symfony-rest2
I ended up buying this course in order to get access to the full code. The issue is that it was written for Symfony 2, but we are running Symfony 3.3, so some things are outdated and I have not been able to get the example running yet.
Code
So, I have posted some of the relevant code below. (I obviously cannot post the whole code, but have posted what are hopefully the relevant portions of the publicly-available code).
services.yml (Their version, Symfony 2 Style)
api_exception_subscriber:
class: AppBundle\EventListener\ApiExceptionSubscriber
arguments: []
tags:
- { name: kernel.event_subscriber }
services.yml (my full file with all comments removed)
This includes a modified version of what they have above (hopefully this is the correct Symfony 3.3 way of doing things).
NOTE: Anything that was part of the private code which I cannot show, I have replaced with the word "something".
parameters:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundle\:
resource: '../../src/AppBundle/*'
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
AppBundle\EventListener\ApiExceptionSubscriber:
arguments:
- ['%something.something%']
tags:
- {name: 'kernel.event_subscriber'}
routing.yml (relevant section of their file)
app_api:
resource: "#AppBundle/Controller/Api"
type: annotation
defaults:
_format: json
routing.yml (my full file) - NOTE: I had to add the "_format: json" directly to the "app" section here rather than "app_api" because in our REST API, all of our URLs are at the root level, and do NOT have to be prefixed with "api" like http://localhost/api/someMethod/someMethodParameter as in the tutorial's code
app:
resource: '#AppBundle/Controller/'
type: annotation
defaults: {_format:json}
yml_route:
path: /yml-route
defaults:
_controller: AppBundle:Default:yml
awesome_route:
path: /awesome-route/{ic}
defaults:
_controller: AppBundle:Rest:awesomeRoute
src/AppBundle/RestController.php (edited to show just the basic structure)
<?php
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\HttpFoundation\Request;
class RestController extends Controller {
public function doSomething($id)
{
// Code to populate $result with data from database is here
return new JsonResponse($result);
}
// This file contains many different functions similar to doSomething() which retrieve the request for the API caller.
// For example, doSomething() can be accessed via http://localhost/app_dev.php/doSomething/123
}
src/AppBundle/Api/ApiProblem.php (edited to show just the basic structure)
namespace AppBundle\Api;
use Symfony\Component\HttpFoundation\Response;
class ApiProblem
{
// Code relevant to this class is in here
}
src/AppBundle/Api/ApiProblemException.php (edited to show just the basic structure)
<?php
namespace AppBundle\Api;
use Symfony\Component\HttpKernel\Exception\HttpException;
class ApiProblemException extends HttpException
{
private $apiProblem;
public function __construct($severalParametersWhichICannotListHereBecauseCodeIsPrivate) {
// Does some stuff and then calls the parent:__construct
// Includes a getter for $apiProblem
}
}
src/AppBundle/EventListener/ApiExceptionSubscriber.php (edited to show just the basic structure)
<?php
namespace AppBundle\EventListener;
use AppBundle\Api\ApiProblem;
use AppBundle\Api\ApiProblemException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
// Code relevant to this subscriber is here
}
The Issue
I'm getting the following error when I try to run any type of command from the command-line bin/console:
C:\htdocs\projects\myproject>php bin/console debug:container
PHP Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: T
here is no extension able to load the configuration for "AppBundle\EventListener\ApiExceptionSubscribe
r" (in C:\htdocs\projects\myproject\app/config\services.yml). Looked for namespace "AppBundle\EventListe
ner\ApiExceptionSubscriber", found "framework", "security", "twig", "monolog", "swiftmailer", "doctrin
e", "sensio_framework_extra", "demontpx_parsedown", "doctrine_cache", "doctrine_migrations", "debug",
"web_profiler", "sensio_distribution", "web_server" in C:\htdocs\projects\myproject\vendor\symfony\symfo
ny\src\Symfony\Component\DependencyInjection\Loader\YamlFileLoader.php:644
Stack trace:
#0 C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Loader\
YamlFileLoader.php(614): Symfony\Component\DependencyInjection\Loader\YamlFileLoader->validate(Array,
'C:\\htdocs\\proje...')
#1 C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Loader\
YamlFileLoad in C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\Config\Loader\
FileLoader.php on line 179
Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: There
is no extension able to load the configuration for "AppBundle\EventListener\ApiExceptionSubscriber" (i
n C:\htdocs\projects\myproject\app/config\services.yml). Looked for namespace "AppBundle\EventListener\A
piExceptionSubscriber", found "framework", "security", "twig", "monolog", "swiftmailer", "doctrine", "
sensio_framework_extra", "demontpx_parsedown", "doctrine_cache", "doctrine_migrations", "debug", "web_
profiler", "sensio_distribution", "web_server" in C:\htdocs\projects\myproject\vendor\symfony\symfony\sr
c\Symfony\Component\Config\Loader\FileLoader.php on line 179
Symfony\Component\Config\Exception\FileLoaderLoadException: There is no extension able to load the con
figuration for "AppBundle\EventListener\ApiExceptionSubscriber" (in C:\htdoc
fig\services.yml). Looked for namespace "AppBundle\EventListener\ApiExceptio
work", "security", "twig", "monolog", "swiftmailer", "doctrine", "sensio_fra
arsedown", "doctrine_cache", "doctrine_migrations", "debug", "web_profiler",
eb_server" in C:\htdocs\projects\myproject\app/config\services.yml (which is b
ocs\projects\myproject\app/config\config.yml"). in C:\htdocs\projects\myproject\
\Symfony\Component\Config\Loader\FileLoader.php on line 179
Call Stack:
1.4353 6149416 1. Symfony\Component\Debug\ErrorHandler->handleExcep
myproject\vendor\symfony\symfony\src\Symfony\Component\Debug\ErrorHandler.php:
What I've Tried
I've been debugging this for the last several days and have read many related discussions on Stack Overflow. I'm fairly new to services, subscribers, and dependency injection and I've tried editing both the routes.yml and services.yml numerous times. I was also getting some circular reference exceptions before but think I've fixed those now. I was hoping someone could please provide me with some direction and hopefully help me turn this into a working example on Symfony 3.3 that I can learn from. If you need any additional detail, please let me know.
From what I've learned, autowiring/autoconfiguring of services in Symfony 3.3 seems to be new and I think that may be impacting things but I'm not sure. I did try turning both of those settings off in services.yml though but with no luck.

DataWeave - Transformer Mule error "There is no variable named 'message'"

How to display Outbound properties in mule via the DataWeave transformer?
I tried this:
%dw 1.0
%output application/json skipNullOn="everywhere"
---
{
test_property: message.outboundProperties.testProperty
}
but I get this error: There is no variable named 'message'.
Thanks.
invoke directly without using 'message' as shown below
test_property: outboundProperties.testProperty
or else define a flow variable and use it as below
flowvar1: flowVars.flowvar1