MailGun Api Example - mailgun

I'm doing a test with mailgun, and I copy the example and put my domain and password, but it's not going, and I do not get the mail either
I have put my : Domain Name and API Key.
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
public static JsonNode sendSimpleMessage() throws UnirestException {
HttpResponse<JsonNode> request = Unirest
.post("https://api.mailgun.net/v3/" + "sandbox21801cd223b94bbc92dbd011424xxxxx.mailgun.org"
+ "/messages")
.basicAuth("api", "xxx8013e6a2e75889370b0d2e670b2e")
.queryString("from", "Excited User <notifications-noreply#miempresa.com>")
.queryString("to", "joseluis.garcia#miempresa.com").queryString("subject", "hello")
.queryString("text", "testing").asJson();
return request.getBody();
}
Error:
Exception in thread "main" com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143)
at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
at com.abalia.crm482.sms_mail.mailSendInfobip.sendSimpleMessage(mailSendInfobip.java:22)
at com.abalia.crm482.sms_mail.mailSendInfobip.main(mailSendInfobip.java:11)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:106)
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:139)
... 3 more
Caused by: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:51)
at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:95)
... 4 more
Caused by: org.json.JSONException: A JSONArray text must start with '[' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
at org.json.JSONArray.<init>(JSONArray.java:113)
at org.json.JSONArray.<init>(JSONArray.java:157)
at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:48)
... 5 more

I had the same issue when I passed in a wrong key. By replacing public key with private key (which you can find from mailgun console), I fixed this problem.
Basically what happened when you pass in a wrong key is like this:
If you debug inside into com.mashape.unirest.http.HttpResponse<T>, inside the constructor, you will find how the JsonNode was build. And rawBody, which suppose to be a json string, become a simple String: Forbidden if you failed the key authentication. And trying to build a JsonArray from such a string throws such exception.
Hope it helps~

Related

How to check a cookie name is “not” present on page using Katalon Studio?

I need to check that a cookie is "NOT" present on-page.
Based on this post, I have tried the following on the scripted Katalon mode:
added these to the standard import from the test case:
import com.kms.katalon.core.webui.driver.DriverFactory as DriverFactory
import org.openqa.selenium.WebDriver as WebDriver
then I wrote:
WebUI.verifyMatch(driver.manage().getCookieNamed('foo'), is(null()))
and then I get the following error on null pointer
FAILED Reason:
java.lang.NullPointerException: Cannot invoke method call() on null object
Is there a way to write a check on "none" existing cookies using the script mode for Katalon Studio?
P.S:
I have tried this other approach
try {
_fbp = driver.manage().getCookieNamed('_fbp').getName()
}
catch (Exception e) {
String _fbp = new String('Something went wrong')
System.out.println('Something went wrong')
}
WebUI.verifyMatch('Something went wrong', _fbp, false)
It fails only on the verifyMatch part. It seems that 'something went wrong' does not really get stored in the variable _fbp.
FAILED.
Reason:
groovy.lang.MissingPropertyException: No such property: _fbp for class:
WebUI.verifyMatch() is used for checking matching between two strings.
You can do that using the plain Groovy assert. Instead of
WebUI.verifyMatch(driver.manage().getCookieNamed('foo'), is(null()))
do this:
assert driver.manage().getCookieNamed('foo').is(null)

Groovy Regex matcher OR - either unique groups or duplicate group ids

I want to regex search a string representing a log file, locate multiple potential error message, and print the result.
Example Input (single string)
...
Unable to parse YAML file: [mapping values are not allowed in this context] at line 1234\r\n
worthless line\r\n
KitchenInventory.cs(285,118): error CS2345: 'ButteryBread' does not contain a definition for 'DropOnFloor'\r\n
another worthless line\r\n
...
Each error type has certain grouping categories that I'm attempting to capture, which may or may not be present in other error types.
My goal is to output error details after doing the regex search, filling in as many values as are present in each error regex:
Error: Unable to parse YAML file
Details: mapping values are not allowed in this context
Line: 1234
Error: CS2345
Details: 'ButteryBread' does not contain a definition for 'DropOnFloor'
Filename: KitchenInventory.cs
Line: 285,118
(Notice that filename is ommited for the YAML error, due to YAML errors not containing that piece of information.
I've found that I cannot do a logical OR to create a massive Regex string, because there are duplicate grouping names. I attempted to do each regex search individually, but I receive an exception when checking for the presence of a field:
def pattern = ~patternString
def matcher = pattern.matcher(lines)
while (matcher.find()) {
if (matcher.group('filename')) {
println "Filename: "+matcher.group('filename')
}
if (matcher.group('error')) {
println "Error: "+matcher.group('error')
}
if (matcher.group('message')) {
println "Message: "+matcher.group('message')
}
}
Caught: java.lang.IllegalArgumentException: No group with name <errorCode>
java.lang.IllegalArgumentException: No group with name <errorCode>
Is there a way for me to iterate through Groovy regex group names that COULD be present, without throwing exceptions? Alternatively, am I going about this the wrong way, and is there an easier way for me to achieve my goal?
I was looking for the same thing and was not able to find a "groovier" way to do it.
Only solution that I found was to verify if the pattern string contains the group name:
if (stringPattern.contains('message')) {
println "Message: "+matcher.group('message')
}

No value at JSON path

How to write mockMVC test for the below JSON which has combination of String and Array.
{
"id":1,
"firstName":"NPA",
"lastName":"TAS",
"mobile":"123454321",
"email":"ABCD#GMAIL.COM",
"accounts":[
{
"id":1,
"balance":"$1000",
"custid":"1",
"accNbr":"12345"
}
]
}
My code:
#Test
public void testJson() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(get("/acc/1")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accounts.id", Matchers.is(1)))
.andExpect(jsonPath("$.accounts.balance", Matchers.is("$1000")))
.andExpect(jsonPath("$.accounts.accNbr", Matchers.is("12345")))
.andExpect(jsonPath("$.accounts.custid", Matchers.is("1")))
.andExpect(jsonPath("$.*", Matchers.hasSize(4)));
}
i get the exception
No value at JSON path "$.accounts.id", exception:
Expected to find an object with property ['accounts'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
However, if i try using $.accounts[0].id i get exception
No value at JSON path "$.accounts[0].id", exception:
Expected to find an object with property ['accounts'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
The accounts attribute is an array so this: $.accounts.id would have to use an indexer such as: $.accounts[0].id.
From the docs:
[<number> (, <number>)] Array index or indexes
If you are uncertain about which index to use then you can filter the JSON and assert on the filtered account sub document. For example:
$.accounts[?(#.id == 1)].balance: returns $1000
$.accounts[?(#.accNbr == 12345)].id: returns 1
... etc
Plenty more details in the docs and you can use the use the JsonPath evaluator to play around with this.
As #glytching and I have mentioned, there is an array and it should work with $.accounts[0].id.
If you still encounter a problem, I would try to print the result your console:
MvcResult result = mockMvc.perform(MockMvcRequestBuilders
.get("/acc/1").accept(MediaType.APPLICATION_JSON)).andReturn();
String content = result.getResponse().getContentAsString();

Spring-Boot #RequestMapping and #PathVariable with regular expression matching

I'm attempting to use WebJars-Locator with a Spring-Boot application to map JAR resources. As per their website, I created a RequestMapping like this:
#ResponseBody
#RequestMapping(method = RequestMethod.GET, value = "/webjars-locator/{webjar}/{partialPath:.+}")
public ResponseEntity<ClassPathResource> locateWebjarAsset(#PathVariable String webjar, #PathVariable String partialPath)
{
The problem with this is that the partialPath variable is supposed to include anything after the third slash. What it ends up doing, however, is limiting the mapping itself. This URI is mapped correctly:
http://localhost/webjars-locator/angular-bootstrap-datetimepicker/datetimepicker.js
But this one is not mapped to the handler at all and simply returns a 404:
http://localhost/webjars-locator/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css
The fundamental difference is simply the number of components in the path which should be handled by the regular expression (".+") but does not appear to be working when that portion has slashes.
If it helps, this is provided in the logs:
2015-03-03 23:03:53.588 INFO 15324 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/webjars-locator/{webjar}/{partialPath:.+}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity app.controllers.WebJarsLocatorController.locateWebjarAsset(java.lang.String,java.lang.String)
2
Is there some type of hidden setting in Spring-Boot to enable regular expression pattern matching on RequestMappings?
The original code in the docs wasn't prepared for the extra slashes, sorry for that!
Please try this code instead:
#ResponseBody
#RequestMapping(value="/webjarslocator/{webjar}/**", method=RequestMethod.GET)
public ResponseEntity<Resource> locateWebjarAsset(#PathVariable String webjar,
WebRequest request) {
try {
String mvcPrefix = "/webjarslocator/" + webjar + "/";
String mvcPath = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
String fullPath = assetLocator.getFullPath(webjar,
mvcPath.substring(mvcPrefix.length()));
ClassPathResource res = new ClassPathResource(fullPath);
long lastModified = res.lastModified();
if ((lastModified > 0) && request.checkNotModified(lastModified)) {
return null;
}
return new ResponseEntity<Resource>(res, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
I will also provide an update for webjar docs shortly.
Updated 2015/08/05: Added If-Modified-Since handling
It appears that you cannot have a PathVariable to match "the remaining part of the url". You have to use ant-style path patterns, i.e. "**" as described here:
Spring 3 RequestMapping: Get path value
You can then get the entire URL of the request object and extract the "remaining part".

SharePoint SoapServerException calling GetListItems web service

I have the following statement in my code:
System.Xml.XmlNode items = lstWebs.GetListItems(
"Tasks", string.Empty, listQuery, listViewFields,
string.Empty, listQueryOptions, WorkspaceId);
When executing this, the following exception occurs:
Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.
Exception Source is:
System.Web.Services
Stack Trace:
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ImpersonationConsoleApp.MossLists.Lists.GetListItems(String listName, String viewName, XmlNode query, XmlNode viewFields, String rowLimit, XmlNode queryOptions, String webID) in C:\Documents and Settings\david\My Documents\_Dew02SiteCreator\DeWProjectStarter\ImpersonationConsoleApp\Web References\MossLists\Reference.cs:line 435
at ImpersonationConsoleApp.Program.DeleteTasksIfNotExist(DataRow[] drTasksdel, String siteURL) in C:\Documents and Settings\david\My Documents\_Dew02SiteCreator\DeWProjectStarter\ImpersonationConsoleApp\Program.cs:line 1384
I have confirmed the site URL and it is fine.
Could you please help on why the exception is occurring? Do I need to reset IIS?
please find the detail.
SoapException.InnerException is Null.
However the soapExcetion.Detail.InnerText is showing: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
Is the name tasks also the actual listname in the url? i.e. http://siteurl/lists/tasks? is the list in a subsite and are you using the service under the site-collection?
IF the list is in a subsite the use http://sitecollectionurl/subsite/_vti_bin/lists.asmx as the Service url, otherwise the lists.asmx will try to find the tasks list in the rootweb instead of the subsite.
The signature for GetListItems is
GetListItems(ListID, "", queryNode, viewFieldsNode, Nothing, queryOptionsNode, Nothing)
Try simplifying queryNode, viewFieldsNode and queryOptionsNode to the minimal.
In VB.NET
Dim caml = New XmlDocument
Dim queryNode = caml.CreateElement("Query")
Dim viewFieldsNode = caml.CreateElement("ViewFields")
Dim queryOptionsNode = caml.CreateElement("QueryOptions")
queryOptionsNode.InnerXml = "<ViewAttributes Scope=""Recursive"" /><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>"
In C#
var caml = new XmlDocument();
var queryNode = caml.CreateElement("Query");
var viewFieldsNode = caml.CreateElement("ViewFields");
var queryOptionsNode = caml.CreateElement("QueryOptions");
queryOptionsNode.InnerXml = "<ViewAttributes Scope=\"Recursive\" /><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>";
If it works, then the web service setup is correct.
When I had the mentioned problem, it was my invalid XML that caused it. There is a missing 'type' attribute on the 'Value' element of the 'Where' element in queryNode. I found it here from Microsoft.
Type | Required Text. Specifies the data type for the value contained by this element.
It works after adding the Type attribute. Check if any missing requirements for the xml in one of the nodes mentioned above?
Have you tried running with elevated permissions, it looks like the running user does not hav sufficient privileges to query the data...
SPSecurity.RunWithElevatedPrivileges