WSO2 DataService (DataSource) Return Custom Error Message - wso2

How to return Custom Error Response when using WSO2 EI(6.5.0) DataService
I am getting this error when validation input values :
{
"Fault": {
"faultcode": "axis2ns16:VALIDATION_ERROR",
"faultstring": "DS Code: VALIDATION_ERROR\nNested Exception:-\njavax.xml.stream.XMLStreamException: DS Code: VALIDATION_ERROR\nSource Data Service:-\nName: MWGetBranchCodes\nLocation: \\MWGetBranchCodes.dbs\nDescription: N/A\nDefault Namespace: http://ws.wso2.org/dataservice\nCurrent Request Name: _post_getbankcodes\nCurrent Params: {SOURCE=source, REQUESTER=bond, FUNCTION=function, SECURITYCODE=1FE550839D5DD7933032340DA85F614}\nNested Exception:-\nSecuritycode and Function are not matched : \nField Name: SECURITYCODE\nField Value: 1FE550839D5DD7933032340DA85F614\n\n",
"detail": ""
}
}
i want this :
{
"Error": {
"ErrorCode": "0", 0-failed/ 1-success
"ErrorMessage": "VALIDATION_ERROR : Securitycode is NULL",
"detail": " \nField Name: SECURITYCODE\nField Value: null\n\n"
}
}
Help me please Thanks.

I think that for that behaviour you need to create custom validators, check this post:
http://mycodeideas.blogspot.com/2016/07/custom-validators-with-wso2-dss.html

Related

Postman Get Azure Synapse Bearer Token

I am trying to get a Azure Synapse Bearer Token using Postman. I've followed this Postman link/video and have successfully called:
Azure Management Rest API: https://management.azure.com/subscriptions/{{subscriptionId}}/resourcegroups?api-version=2020-09-01
Per Microsoft documentation and PowerShell, I have successfully obtained a Synapse Bearer Token and called:
https://mysynapseworkspace.dev.azuresynapse.net/pipelines?api-version=2020-12-01
PowerShell: NOTE: The Endpoint is https://dev.azuresynapse.net/
Create Azure APP Service Principal
az login --service-principal --username "appid" --password "pasword" --tenant "tenantid"
az account get-access-token --resource https://dev.azuresynapse.net/
In the Postman link example, the Pre-request-Script
pm.test("Check for collectionVariables", function () {
let vars = ['clientId', 'clientSecret', 'tenantId', 'subscriptionId'];
vars.forEach(function (item, index, array) {
console.log(item, index);
pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.undefined;
pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.empty;
});
if (!pm.collectionVariables.get("bearerToken") || Date.now() > new Date(pm.collectionVariables.get("bearerTokenExpiresOn") * 1000)) {
pm.sendRequest({
url: 'https://login.microsoftonline.com/' + pm.collectionVariables.get("tenantId") + '/oauth2/token',
method: 'POST',
header: 'Content-Type: application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "grant_type", value: "client_credentials", disabled: false },
{ key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false },
{ key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false },
{ key: "resource", value: pm.collectionVariables.get("resource") || "https://management.azure.com/", disabled: false }
]
}
}, function (err, res) {
if (err) {
console.log(err);
} else {
let resJson = res.json();
pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_on);
pm.collectionVariables.set("bearerToken", resJson.access_token);
}
});
}
});
I modified the Pre-Request-Script statement:
The PostMan Variable: resource = dev.azuresynapse.net
{ key: "resource", value: pm.collectionVariables.get("resource") || "https://dev.azuresynapse.net/", disabled: false }
Post Failed:
{
"code": "AuthenticationFailed",
"message": "Token Authentication failed - IDX12741: JWT: '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' must have three segments (JWS) or five segments (JWE)."
}
What is the problem? Thx
I try to reproduce same thing in my environment and got below result:
PowerShell with Bearer Token:
Shell Script:
$applicationID = '4381xxxxxxxxxxxfa606b3edf'
$clientSecret = '4KI8Qxxxxxxxxxxxxxxxx6sQcKw'
$tenantId = 'fb134080xxxxxxxxxxxxx3a0c218f3b0'
$url = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$resource = "https://graph.microsoft.com/"
$restbody = #{
grant_type = 'client_credentials'
client_id = $applicationID
client_secret = $clientSecret
resource = $resource
}
# Get the return Auth Token
$token = Invoke-RestMethod -Method POST -Uri $url -Body $restbody Write-Host "Authenticated - token retrieved of type " $($token.token_type)
$token
Or
I generated Bearer token via postman with below parameters:
POST
https://login.microsoftonline.com/fb1380-e4d2-xxxxx-f3a0c218f3b0/oauth2/v2.0/token
client_id:4KIxxxxxx2CS2UasSu9zTXhrMNQy6sQcKw
scope:https://management.azure.com/.default
client_secret: 4KI8Q~7xxxxxxxxxzTXhrMNQy6sQcKw
grant_type:client_credentials
Response:

ValidationException on DynamoDB with AWS sdk for Java

I'm trying to put an item and get it back a few statements later, but I'm getting a cryptic error from AWS.
class DataStore<Payload extends EventPayload> {
private final Clock clock;
private final Table table;
private final ObjectMapper objectMapper = new ObjectMapper();
private final Class<Payload> payloadType;
public DynamoDBEventStore(final Clock clock, final Class<Payload> eventClass, final String dataStoreName) {
final AmazonDynamoDB client =
AmazonDynamoDBClientBuilder.standard().build();
final DynamoDB dynamoDB = new DynamoDB(client);
this.table = dynamoDB.getTable(dataStoreName);
this.clock = clock;
this.payloadType = eventClass;
}
public void persist(final UUID eventId, final String aggregateId, final Long version, final Payload eventPayload) {
final Map<String, Object> rawDomainEvent = Map.of(
"EventId", eventId.toString(),
"Timestamp", LocalDateTime.now(clock).toString(),
"AggregateId", eventPayload.getAggregateKey(),
"Version", version,
"Payload", objectMapper.convertValue(eventPayload, Map.class)
);
final Item domainEvent = Item.fromMap(rawDomainEvent);
table.putItem(domainEvent);
}
public void testEvent(final UUID eventId) {
table.getItem("EventId", eventId.toString();
}
}
If I save an item calling to persist, then the Item is saved as expected (see the JSON below from DynamoDB console).
{
"EventId": {
"S": "8a2c1733-887d-42e1-b720-2e87dcf46269"
},
"Timestamp": {
"S": "2021-10-10T04:18:56.465223700"
},
"Payload": {
"M": {
"transactions": {
"L": []
},
"aggregateKey": {
"S": "bc406432-37f1-440f-9157-b0ce8da814c1"
}
}
},
"Version": {
"N": "1"
},
"AggregateId": {
"S": "bc406432-37f1-440f-9157-b0ce8da814c1"
}
}
But when I call to testEvent it fails returning the following error:
"message": "Unable to unmarshall exception response with the unmarshallers provided (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: E6M3NI8CTF05ONUC5G25H53PT7VV4KQNSO5AEMVJF66Q9ASUAAJG; Proxy: null)",
Any thoughts about what could be wrong with my code? FYI, I'm using Java 11, Spring Boot 2.5.4 and AWS SDK 1.12.81:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>1.12.81</version>
</dependency>
The error message isn't that cryptic! Ignore the unmarshalling part, and you are left with
Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException;
I would guess, your eventId can't be found in the database - but you need to debug from here

without Error in my code i am getting error in postaman #PostMapping

I write code for Restful services.in postman when i tried to send a request by using #Postmapping its getting error in postaman
this is my controller class
public class BookController {
private BookRepository bookrepository;
#PostMapping("/addBook")
public String save(#RequestBody Book book)
{
bookrepository.save(book);
return "added book with id"+book.getId();
}
#GetMapping("/findAllBooks")
public List<Book> getBooks()
{
return bookrepository.findAll();
}
#DeleteMapping("/delete")
public String deleteBook(#PathVariable int id){
bookrepository.deleteById(id);
return "book deleted"+id;
}
}
when i send a request to postman by post method at the time i m getting a error like the below
{
"timestamp": "2019-03-27T12:22:20.319+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/addBook"
}

Error response in ember-data api

My code for saving document to API looks like that
save(category) {
category.save().then(() => {
this.transitionTo('categories');
}).catch((adapterError) => {
console.log(category.get('errors').toArray());
console.log(category.get('isValid'));
});
},
When API answers is:
{"errors":[{"attribute":"name","message":"This value should not be blank."}]}
then
category.get('isValid')
still returns true.
My question is, how validation errors should looks like?
By default, ember-data's adapter determines that a response is invalid when the status code is 422. You can override the isInvalid function of the adapter to change this.
Also, ember-data now expects errors to be formatted into a json-api error object. If your backend doesn't return it in this format, you can transform it in ember by overriding the handleResponse function of the adapter.
This is a sample json-api error:
{"errors": [
{
"detail": "Must be unique",
"source": { pointer: "/data/attributes/title"}
},
{
"detail": "Must not be blank",
"source": { pointer: "/data/attributes/content"}
}
]}
If you're returning error responses you described above, you would have to do something like this in your adapter:
handleResponse(status, headers, payload) {
if (status === 422 && payload.errors) {
let jsonApiErrors = [];
for (let key in payload.errors) {
for (let i = 0; i < payload.errors[key].length; i++) {
jsonApiErrors.push({
detail: payload.errors[key][i],
source: {
pointer: `data/attributes/${key}`
}
});
}
}
return new DS.InvalidError(jsonApiErrors);
} else {
return this._super(...arguments);
}
}

Timeline item update error

I have a bundle of timelineitems using Mirror API, Now I am trying to change content of a timeline from bundle. But the below error occurs
An error occurred from update timeline : com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
{
"code" : 404,
"errors" : [ {
"domain" : "global",
"message" : "Not Found",
"reason" : "notFound"
} ],
"message" : "Not Found"
}
And update method is something like below
public static TimelineItem updateTimelineItem(Credential credential,
String itemId, String newText) {
try {
Mirror.Timeline timeline = getMirror(credential).timeline();
TimelineItem timelineItem = timeline.get(itemId).execute();
timelineItem.setText(newText);
return timeline.update(itemId, timelineItem).execute();
} catch (IOException e) {
System.err.println("\nAn error occurred from update timeline : " + e);
return null;
}
}
First I try to retrieve the timeline item, when I write execute, then the error occurred
Mirror.Timeline timeline = getMirror(credential).timeline();
TimelineItem timelineItem = timeline.get(itemId).execute();
How can I solve it?
It isn't completely clear from the exception you've posted, but it looks like the itemId isn't valid. How are you getting this itemId and can you verify if it is the timeline.get or the timeline.update that is causing the problem?