SparkPost not returning error code or error on email generation failure - sparkpost

I am trying to implement email attachment functionality using Sparkpost. I get a generation failure in the logs on the sparkpost dashboard that indicates that my email's estimated size is more than 20 MB which is expected since I was testing that scenario.
However in the HTTP response I only receive
{{"total_rejected_recipients": 0,"total_accepted_recipients": 1,"id": "7099572646706409988"}}
I would like to know how I can get an error code or error in my response from sparkpost
My code looks something like this
HttpWebRequest Request = WebRequest.Create(requestURL) as HttpWebRequest;
Request.Proxy = null;
Request.Method = ServiceRequestType.POST.ToString();
AttachHeaders(headers, ref Request);
AttachTimeout(timeoutInSeconds, ref Request);
AttachContentType(contentType, ref Request);
AttachNetworkCredentials(credentials, ref Request);
AttachInputObject(content, ref Request);
Response = (HttpWebResponse)Request.GetResponse();
if ((Response.StatusCode == HttpStatusCode.OK || Response.StatusCode == HttpStatusCode.Accepted || Response.StatusCode == HttpStatusCode.Created || Response.StatusCode == HttpStatusCode.NoContent) == false)
{
throw new Exception(String.Format("Server error (HTTP {0}: {1}).", Response.StatusCode, Response.StatusDescription));
}
using (Response)
{
using (StreamReader ResponseReader = new StreamReader(Response.GetResponseStream()))
{
JsonResponse = JsonConvert.DeserializeObject(ResponseReader.ReadToEnd());
ResponseReader.Close();
}
Response.Close();
}
The logic for creating email is fine since I am able to send and recieve emails when the attachment size is within limits.

Related

Spring WebClient throw error based on response body

I am using Spring WebClient to call REST API. I want to throw an error based on the response. For example, if there is an error (400) with body
{"error": "error message1 "}
then I want to throw an error with "error message1". Same way if there is an error(400) with the body
{"error_code": "100020"}
then I want to throw an error with error_cde 100020. I want to do it in a non-blocking way.
public Mono<Response> webclient1(...) {
webClient.post().uri(createUserUri).header(CONTENT_TYPE, APPLICATION_JSON)
.body(Mono.just(request), Request.class).retrieve()
.onStatus(HttpStatus::isError, clientResponse -> {
//Error Handling
}).bodyToMono(Response.class);
}
A body from ClientResponse should be extracted in a reactive way (javadoc) and lambda in onStatus method should return another Mono (javadoc). To sum up, take a look at below example
onStatus(HttpStatus::isError, response -> response
.bodyToMono(Map.class)
.flatMap(body -> {
var message = body.toString(); // here you should probably use some JSON mapper
return Mono.error(new Exception(message));
})
);

How to update an asset (status and comment) using version one REST data API?

I'm trying to update an asset using data API like below. But I am unable to update it, it is showing an error as Bad request.
String updateIssueData = "{\"Attributes\":{\"Status.Name\":{\"value\":"+"Done"+",\"act\":set}}}";
invokePostMethod("rest-1.v1/Data/Defect/1538",updateIssueData);
private static String invokePostMethod(String url, String data) throws AuthenticationException, ClientHandlerException {
Client client = Client.create();
WebResource webResource = client.resource(versionOneBaseURL+url);
ClientResponse response = webResource.header("Authorization", "Bearer " + fToken).type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,data);
int statusCode = response.getStatus();
System.out.println("statuscode::"+statusCode);
return response.getEntity(String.class);
}

No headers available in xhr object when an UNAUTHORIZED error occurs - IE10

I have a CORS Ajax call to a web api. I have a message handler which throws an:
var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" };
throw new HttpResponseException(msg);
On the client I can't get no response headers, tried:
error: function (xhr, error) {
var result = xhr.getResponseHeader("Response");
but result is null and no other heades are available.
The Debugger shows correctly a 401!
Should I return the Unauthorized Exception differently from the server?
Update:
I forgot the add the Origin header to my HttpResponseException, in order to get the headers.
But in IE10 I don't get any headers, only error message
"error"
How can I know what happend, when using IE10?
Here is related question.
As I cannot get the Headers when returning a 401 response.
No instead I return NoContent StatusCode, which triggers the AJAX success eventhandler.
Now I have to check the response header "response" (which I manually add on the server side) in the success eventhandler, in order to make it work in IE 10:
Server:
var msg = new HttpResponseMessage(HttpStatusCode.NoContent) { ReasonPhrase = "UNAUTHORIZED" };
msg.Headers.Add("RESPONSE", "401");
AddCORSHeaders(msg.Headers, request);
return await Task.FromResult(msg);
Client:
error: function (jqXhr, error) {
var isAuth= jqXhr.getResponseHeader("Response");
Now I get a "response" header with value 401.
IF SOMEONE HAS A BETTER APPROACH, I'LL EXCEPT THE ANSWER !
In IE10 the ajax error eventhandler you get readyState=0 and status="".
In Chrome you get a 401 and readyState=4.

Oracle MAF-MCS API call

I have created a custom POST api for getting login information in MCS. when i check in SOAPUI it works perfectly fine. the parameters passed are
1. header
Oracle-Mobile-Backend-Id: ********************
2. Authentocation
Username:****************
password: **************
and basic login info username and password as "User1" and "user1" respectively.
Step2:
when i call the API from MAF i am getting an error 400
the post method used is
public static Response callPost(String restURI, String jsonRequest) {
String responseJson = "";
Response response = new Response();
RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter();
restServiceAdapter.clearRequestProperties();
//restServiceAdapter.setConnectionName("MiddlewareAPI");
// restServiceAdapter.setConnectionName("");
restServiceAdapter.setRequestType(RestServiceAdapter.REQUEST_TYPE_POST);
restServiceAdapter.addRequestProperty("Content-Type", "application/json");
restServiceAdapter.addRequestProperty("Accept", "application/json; charset=UTF-8");
restServiceAdapter.addRequestProperty("Oracle-Mobile-Backend-Id", "**********");
restServiceAdapter.addRequestProperty("Domain", "mcsdem0001");
restServiceAdapter.addRequestProperty("Username", "******");
restServiceAdapter.addRequestProperty("Password", "*****");
//restServiceAdapter.addRequestProperty("Authorization", "Basic "+new String(encodedBytes));
System.out.println("**** Authorization String ****=>"+new String(encodedBytes));
System.out.println("**** RestURI ******=>"+restURI);
System.out.println("**** jsonRequest ******=>"+jsonRequest);
restServiceAdapter.setRequestURI(restURI);
restServiceAdapter.setRetryLimit(0);
try {
responseJson = restServiceAdapter.send(jsonRequest);
int responseCode = restServiceAdapter.getResponseStatus();
response.setResponseCode(responseCode);
response.setResponseMessage(responseJson);
response.setHeader(restServiceAdapter.getResponseHeaders());
} catch (Exception e) {
int responseCode = restServiceAdapter.getResponseStatus();
response.setResponseCode(responseCode);
response.setResponseMessage(responseJson);
}
System.out.println("Response:" + responseJson);
return response;
}
Could anyone please tell me is there any error in the post method??
This can be due to the version conflict. Try to use HttpUrlConnection instead of RestServiceAdapter and let me know if it works.
actually this bit
restServiceAdapter.addRequestProperty("Username", "******");
restServiceAdapter.addRequestProperty("Password", "*****");
doesn't work because you attempt to pass username and password as a HTTP header. Instead it should be passed as you were trying here
restServiceAdapter.addRequestProperty("Authorization", "Basic "+new String(encodedBytes));
However, these should not be encoded bytes but a base64 encoded string in the form
Basis (without the < abd >)
Note that user identity domains only need to be provided in multi-tenant environments. In MCS, the user domain is defined through the mobile backend you connect to.
Frank
Use the MAF MCS Utility library to make it allot easier.
The developer guide can be found here: http://download.oracle.com/otn_hosted_doc/maf/mafmcsutility-api-doc-082015.pdf
Example code:
MBEConfiguration mbeConfiguration =
new MBEConfiguration(
<mbe rest connection>,<mobileBackendId>,
<anonymous key string>,<application key string>,
MBEConfiguration.AuthenticationType.BASIC_AUTH);
mbeConfiguration.setEnableAnalytics(true);
mbeConfiguration.setLoggingEnabled(false)
mbeConfiguration.setMobileDeviceId(
DeviceManagerFactory.getDeviceManager().getName());
MBE mobileBackend = MBEManager.getManager().
createOrRenewMobileBackend(<mobile backend Id>, mbeConfiguration);
CustomAPI customApiProxy = mbe.getServiceProxyCustomApi();
MCSRequest request = new MCSRequest(mobileBackend.getMbeConfiguration());
request.setConnectionName(<Rest connection name>);
request.setRequestURI("/moile/custom/mockup/employees");
request.setHttpMethod(MCSRequest.HttpMethod.POST);
request.setPayload("{\"id\":\"1\"\"name\":\"nimphius\",\"firstName\":\"frank\"}");
request.setRetryLimit(0);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type","application/json");
request.setHttpHeaders(headers);
MCSResponse response = customApiProxy .sendForStringResponse(request);
String jsonResponse = (String) response.getMessage();

How to get Response Body when Server responds with 302 in Grails?

I want to request server side an image from a different server with a GET request. If the requesting server response with status code 200 everything works fine.
But often I get FOUND 302 redirect as status code. In this case there is no response.body which I need.
This is the code I use to retrieve a user image from facebook. Since facebook makes a redirect I get 302 as status code and not response.body.
def uri = new URI("http://graph.facebook.com/1000345345345/picture?width=200&height=200")
def requestFactory = new SimpleClientHttpRequestFactory()
def request = requestFactory.createRequest(uri, HttpMethod.GET)
try {
def response = request.execute()
def statusCode = response.statusCode
if (statusCode == HttpStatus.FOUND) {
log.debug "302"
// how do I get the response body?
}
if (statusCode == HttpStatus.OK) {
return response.body.bytes
}
else if(statusCode == HttpStatus.FORBIDDEN) {
throw new IllegalAccessError(response.statusCode.toString())
}
} catch(ex) {
log.error "Exception while querying $url", ex
}
return null
How do I get the correct response body in case on 302?
You can use this. You method is:
def queryUrl(url, ...) {}
You can use:
if (statusCode == HttpStatus.FOUND) {
def newUrl = response.connection.responses.getHeaders().Location[0]
log.debug "302 redirect to ${newUrl}"
return queryUrl(newUrl, "")
}
This will request the redirected url.

Resources