Adding headers to Jetty in Wiremock - jetty

I'm running into CORS issues using the Wiremock standalone jar. I call my mock service using jQuery ajax. Is it possible to add the required "Access-Control-Allow-Origin" header when starting up the server?

I got it to work by adding an options.json file in my mappings folder for the CORS preflight request
{
"request" : {
"url" : "/myurl",
"method" : "OPTIONS"
},
"response" : {
"status" : 200,
"headers" : {
"Access-Control-Allow-Origin" : "http://myorigin",
"Access-Control-Allow-Headers": "accept, content-type",
"Access-Control-Allow-Methods": "GET, POST"
}
}
}
and all my other mappings look like this
{
"request" : {
"urlPattern" : "/myurl",
"method" : "POST",
"bodyPatterns" : [ {
"equalToJson" : "{\"foo\":0}",
"jsonCompareMode" : "LENIENT"
} ]
},
"response" : {
"status" : 200,
"bodyFileName" : "body-file.json",
"headers" : {
"Access-Control-Allow-Origin" : "*"
}
}
}
hope it helps

I managed to make it work, with wiremock in standalone just adding enable-stub-cors flag.
java -jar wiremock-standalone-2.27.2.jar --enable-stub-cors

Related

WSO2 DataService (DataSource) Return Custom Error Message

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

Reference Cloud Formation property within same instance

I have a Cloud Formation template where I am looking to set an environment variable TAKE_ACTION on my API Gateway Stage with one of the endpoints of the stage, which requires the stage name, but when I access it using {"Ref":"MyApiStage"} I get a circular reference error.
Is there a workaround for what I'm trying to accomplish?
{
"AWSTemplateFormatVersion":"2010-09-09",
"Transform":"AWS::Serverless-2016-10-31",
"Description":"my POC.",
"Resources":{
"MyApiStage":{
"Type":"AWS::ApiGateway::Stage",
"Properties":{
"DeploymentId":{ "Ref":"ApiDeployment"},
"MethodSettings":[
{
"DataTraceEnabled":true,
"HttpMethod":"*",
"LoggingLevel":"INFO",
"ResourcePath":"/"
}
],
"RestApiId":{ "Ref":"MyApi" },
"StageName":"Prod",
"Variables":{
"TAKE_ACTION" : {"Fn::Join" :
["",
["https://",
{"Ref" : "ApiDeployment"},
".execute-api.",
{"Ref":"AWS::Region"},
".amazonaws.com/",
{"Ref":"MyApiStage"}
] ] }
}
}
}
}
}

Ionic / angulfire2 - Query join reference multiple times

I'm building app with Ionic and angulfire2 and I'm trying to join multiple references from firebase by using the object key.
Database looks following:
{
"achievements" : {
"200" : {
"authorId" : "nGSlhjaDRKh8XdrgxcusU0wdiHN2",
"description" : "I did it"
}
},
"challengeAchievements" : {
"100" : {
"200" : true
}
},
"challenges" : {
"100" : {
"name" : "test challenge"
},
"101" : {
"name" : "test challenge 2"
}
},
"users" : {
"nGSlhjaDRKh8XdrgxcusU0wdiHN2" : {
"email" : "user1#test.com"
},
"wBMX8WOHIpM7dEkzj0hM19OPMbs1" : {
"email" : "user2#test.com"
}
}
}
I would like to join all this data together so that from challenges you get achievements, and from achievements you get the user data.
Currently I'm able to get the achievement details, but not the user data. My provider looks like this at the moment:
getChallengeAchievements(challengeKey) {
return this.rtdb.list(`/challengeAchievements/${challengeKey}`)
.map(achievements => achievements.map((achievement) => {
if (achievement.key)
achievement.details = this.getAchievementDetails(achievement.key);
achievement.user = this.getAchievementUserDetails(achievement.details.authorId);
return achievement;
}));
}
getAchievementDetails(achievementKey?: string): Observable<any> {
if (achievementKey)
return this.rtdb.object(`/achievements/${achievementKey}`);
}
getAchievementUserDetails(authorId?: string): Observable<any> {
if (authorId)
return this.rtdb.object(`/users/${authorId}`);
else console.log('Not found');
}
How should I structure the authorId query in this function? If I use static value in
achievement.details.authorId('nGSlhjaDRKh8XdrgxcusU0wdiHN2')
I'm able to receive the data.
Solved it by subscribing to the first join "achievement.details" and obtaining the user data from there.
getChallengeAchievements(challengeKey) {
return this.rtdb.list(`/challengeAchievements/${challengeKey}`)
.map(achievements => achievements.map((achievement) => {
if (achievement.key)
achievement.details = this.getAchievementDetails(achievement.key);
achievement.details.subscribe(
details => {
achievement.user = this.getAchievementUserDetails(details.authorId);
})
return achievement;
}));
}

Swift 3.0 Alamofire 4.0 - Domain=NSURLErrorDomain Code=-999 "cancelled"

I am trying to use Alamofire (latest version) with Swift 3.0, iOS 10 and xCode 8. Currently trying to do a post call. The code is written below and I keep getting the same issue. Please help, would appreciate anything on this.
private class func getDefaultHeaders() -> HTTPHeaders {
let headers: HTTPHeaders = [
"Connection" : "keep-alive",
"token" : "0781d3957fd8da6ee35c4e3124d974a2999925274771234",
"nonce" : "9b2436331ed908bb2f399568d2adbc4e",
"uuid" : "uuid",
"latitude" : "43.656781",
"longitude" : "-79.380823",
"Content-Type" : "application/json",
"userTypeId" : "1",
"userAgent" : "UserAgent",
"Content-Length" : "0",
"Host" : "localhost:8080",
"User-Agent" : "iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0"
]
return headers
}
func generateCustomSession() -> SessionManager {
let headers = ServicesController.getDefaultHeaders()
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = headers
let manager: SessionManager = SessionManager(configuration: configuration)
return manager
}
func post(url: String, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void) {
generateCustomSession().request(
url,
method: .post,
encoding: JSONEncoding.default)
.validate(statusCode: 200..<300)
.downloadProgress { (progress) -> Void in
print("download progress: \(progress.fractionCompleted)")
}
.responseJSON { (response) -> Void in
if #available(iOS 10.0, *) {
print(response.metrics)
}
debugPrint(response)
if response.result.isSuccess {
let resJson = JSON(response.result.value!)
success(resJson)
}
if response.result.isFailure {
let error : Error = response.result.error!
failure(error)
}
}
}
"cancelled" may happen if there is a problem with a suspicious https certificate that could be fixed by the user allowing access, and that doesn't happen.
Quite possible the root cause is the server using a less than perfect certificate.
I found a way to resolve the issue. Below is code that will help you cancel authentication challenge. I don't recommend this, this useful for temporary solution. The best thing to do is still validate the authentication challenge fully.
let manager: SessionManager = SessionManager(configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .cancelAuthenticationChallenge
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
return manager
}

Error with jsonpCallback. Internal Server Errror

I'm trying to access ajax (jquery-mobile and PhoneGap) to a web service (asmx), but something is wrong and what is not.
This is the js code:
$.ajax({
type : "POST",
url : webMethod,
data : param,
dataType : 'jsonp',
jsonp : 'callback',
jsonpCallback : 'jsonpCallback',
success : function(data) {
alert(data.nombre);
},
error : function(x,y,z) {
alert("-- " + x+'\n'+y+'\n'+z + " --");
}
});
function jsonpCallback(){
alert("OK");
}
and the web service (asmx)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void WebServiceTest()
{
HttpContext.Current.Response.ContentType = "application/json";
string qs = HttpContext.Current.Request.QueryString["jsonpCallback"];
HttpContext.Current.Response.Write(qs + "( [{ \"name\": \"John\", \"message\": \"Ok\"}] )");
}
When I run the debug gives me an error -->
callback=jsonpCallback&_=1343139529496 500 (Internal Server Error)
I have already tried a thousand things (or at least that's the feeling I have ...)
I would greatly appreciate your suggestions.
P. S. Forgive my poor English