I am currently in the process of integrating MailGun into one of my applications. For my use cases I need to be able to send out attachments. So far, I have been able to send out attachments just fine but my problem is that I am unable to specify the attachment's name. Their documentation found here specifies that the attachment part should be added when including attachment, but does not state how to specify the file's name.
For reference I am using Spring's RestTemplate as my client and I am reading the file as a base64 encoded string which is then trasnformed into a ByteArrayResource. For reference my code is this:
#Override
public EmailDocument sendEmail(EmailDocument email) {
var properties = propProvider.findFor(email.getCompany());
var parts = new LinkedMultiValueMap<String, Object>();
parts.add("from", email.getFrom());
parts.add("to", toCommaString(email.getTo()));
if (!email.getCc().isEmpty()) {
parts.add("cc", toCommaString(email.getCc()));
}
if (!email.getBcc().isEmpty()) {
parts.add("bcc", toCommaString(email.getBcc()));
}
parts.add("subject", email.getSubject());
if (email.getIsHtml()) {
parts.add("html", email.getBody());
} else {
parts.add("text", email.getBody());
}
email.getAttachments().forEach(attachment -> {
var decoded = Base64.getDecoder().decode(attachment.getBytes(StandardCharsets.UTF_8));
parts.add("attachment", new ByteArrayResource(decoded));
});
var header = headerProvider.createHeader("api", properties.getApiKey(), inferMediaType(email));
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(parts, header);
try {
var response = restTemplate.exchange(createDomain(properties.getDomain()), HttpMethod.POST, request, MailGunApiResponse.class);
log.info("Got the following MailGun response {}", response);
if (!response.getStatusCode().is2xxSuccessful()) {
email.setFailureReason(Optional.ofNullable(response.getBody()).map(MailGunApiResponse::getMessage).orElse(null));
email.setRetries(email.getRetries() + 1);
email.setFailed(isFailed(email));
} else {
email.setSent(true);
}
} catch (Exception e) {
log.error("An error has occurred while attempting to send out email {}", email, e);
email.setFailureReason(e.getMessage());
email.setRetries(email.getRetries() + 1);
email.setFailed(isFailed(email));
}
return email;
}
Does anyone know how to specify a filename for the attachment?
I'm trying to get the "symbol" of a JSON HttpRequest in Java. I want to use GSON of google but, I can't reach any value ... I'm always with a null value in my object... I know that the error are "stock.symbol" I certainly need to put some "node" before ... I'm lost ... so ...
here the code :
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://yahoo-finance-low-latency.p.rapidapi.com/v6/finance/quote?symbols=AAPL&lang=en®ion=CA"))
.header("x-rapidapi-key", "---")
.header("x-rapidapi-host", "***")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
try {
HttpResponse<String> reponse = null;
reponse = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.print(reponse.body());
Gson gson = new Gson();
Stock stock = gson.fromJson(reponse.body(), Stock.class);
System.out.println("******************************************************");
System.out.println(stock.symbol + stock.displayName + stock.quoteType);
System.out.println("******************************************************");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
here my output, you will be eable to see the answer from the api in JSON format :
{"quoteResponse":{"result":[{"language":"en-US","region":"CA","quoteType":"EQUITY","quoteSourceName":"Nasdaq Real Time Price","triggerable":true,"currency":"USD","firstTradeDateMilliseconds":345479400000,"priceHint":2,"postMarketChangePercent":-0.0956731,"postMarketTime":1621641596,"postMarketPrice":125.31,"postMarketChange":-0.120003,"regularMarketChange":-1.8799973,"regularMarketChangePercent":-1.4767083,"regularMarketTime":1621627203,"averageAnalystRating":"2.0 - Buy","tradeable":false,"esgPopulated":false,"marketState":"POSTPOST","regularMarketPrice":125.43,"regularMarketDayHigh":128.0,"regularMarketDayRange":"125.21 - 128.0","regularMarketDayLow":125.21,"regularMarketVolume":79152773,"regularMarketPreviousClose":127.31,"bid":125.37,"ask":125.37,"bidSize":12,"askSize":10,"fullExchangeName":"NasdaqGS","financialCurrency":"USD","regularMarketOpen":127.82,"averageDailyVolume3Month":103188411,"averageDailyVolume10Day":86685085,"fiftyTwoWeekLowChange":47.1575,"fiftyTwoWeekLowChangePercent":0.60247856,"fiftyTwoWeekRange":"78.2725 - 145.09","fiftyTwoWeekHighChange":-19.659996,"fiftyTwoWeekHighChangePercent":-0.13550209,"fiftyTwoWeekLow":78.2725,"fiftyTwoWeekHigh":145.09,"dividendDate":1620864000,"earningsTimestamp":1619627400,"earningsTimestampStart":1627469940,"earningsTimestampEnd":1627905600,"trailingAnnualDividendRate":0.82,"trailingPE":28.192854,"trailingAnnualDividendYield":0.006440971,"epsTrailingTwelveMonths":4.449,"epsForward":5.36,"epsCurrentYear":5.2,"priceEpsCurrentYear":24.121155,"sharesOutstanding":16687599616,"bookValue":4.146,"fiftyDayAverage":130.1347,"fiftyDayAverageChange":-4.7047043,"fiftyDayAverageChangePercent":-0.03615257,"twoHundredDayAverage":127.04788,"twoHundredDayAverageChange":-1.6178818,"twoHundredDayAverageChangePercent":-0.012734425,"marketCap":2093125599232,"forwardPE":23.40112,"priceToBook":30.253258,"sourceInterval":15,"exchangeDataDelayedBy":0,"exchange":"NMS","shortName":"Apple Inc.","longName":"Apple Inc.","messageBoardId":"finmb_24937","exchangeTimezoneName":"America/New_York","exchangeTimezoneShortName":"EDT","gmtOffSetMilliseconds":-14400000,"market":"us_market","displayName":"Apple","symbol":"AAPL"}],"error":null}}******************************************************
nullnullnull`
Process finished with exit code 0
public class Stock {
public String symbol, displayName, quoteType;}
We need to get to the JSON inside the result array:
Gson gson = new Gson();
JsonObject json = gson.fromJson(jsonStr, JsonObject.class)
.get("quoteResponse")
.getAsJsonObject()
.get("result")
.getAsJsonArray()
.get(0) // only one object in the array
.getAsJsonObject();
String symbol = json.get("symbol").getAsString();
String displayName = json.get("displayName").getAsString();
String quoteType = json.get("quoteType").getAsString();
Stock stock = new Stock(symbol, displayName, quoteType);
I want to trigger or call a azure webjob using my java application which is simple a spring boot application.
I have some questions like can we invoke or trigger the azure webjob using Spring Rest API call?
And if yes then how. webjob also require a username and password.
I tried something like:
#GetMapping
public String methodCall(#RequestHeader String username, #RequestHeader String password) {
String ApiUrl = "https://myapp.scm.azurewebsites.net/api/triggeredwebjobs/webjob";
RestTemplate resetTemplate = new RestTemplate();
StringBuilder sb = new StringBuilder().append(ApiUrl).append(username).append(password);
String response = resetTemplate.getForObject(sb.toString(), String.class);
System.out.println("response:----------" + response);
return response;
}
If you want to run a triggered azure web job, you can use the Azure REST API
POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/triggeredwebjobs/{webJobName}/run?api-version=2019-08-01
Authorization: Bearer <access token>
For example
Create a service principal and assign Contributor Role to the sp
Code
private static String authority = "https://login.microsoftonline.com/<tenantid>/";
private static String clientId="sp clientId";
private static String secret="sp client secret";
private static String scope="https://management.azure.com/.default";
try {
// use msal4j to get token
ConfidentialClientApplication app = ConfidentialClientApplication.builder(
clientId,
ClientCredentialFactory.createFromSecret(secret))
.authority(authority)
.build();
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
Collections.singleton(scope))
.build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + future.get().accessToken());
HttpEntity<String> entity = new HttpEntity<String>("",headers);
String url ="https://management.azure.com/subscriptions/e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68/resourceGroups/0730BowmanWindow/providers/Microsoft.Web/sites/bowman0210webapp/triggeredwebjobs/test/run?api-version=2019-08-01";
String res= restTemplate.postForObject(url,entity,String.class);
return res;
} catch (MalformedURLException e) {
throw e;
} catch (InterruptedException e) {
throw e;
} catch (ExecutionException e) {
throw e;
}finally {
return "cannot start";
}
Currently building an Android App that has a Web Service. Trying to get data from the SQL Database using the okhttp3 but I'm getting a weird response and I can't figure it out. My API in Laravel is:
public function getAccount(Request $request, User $user)
{
$email = $request->input('email');
//$response = Users::find($email);
$response = DB::table('users')->where('email', $email)->first();
$count = count($response);
if($count == 0) {
return Response::json([
'message' => 'An error occured',
], 401);
} else {
return Response::json([
'user' => $response->name,
'lastName' => $response->lastName,
'weight' => $response->weight,
'height' => $response->height,
'dob' => $response->DOB,
'email' => $response->email,
], 200);
}
And my Android code is:
private void getDetails() {
Thread thread = new Thread(new Runnable(){
public void run() {
OkHttpClient client = new OkHttpClient();
// Json string with email and password
String bodyString = "{\n\t\"email\" : \"" + email +"\"\n}";
// Make HTTP POST request
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, bodyString);
Request request = new Request.Builder()
.url("http://192.168.1.100/CAB398/public/api/auth/getAccount")
.post(body)
.addHeader("accept", "application/json")
.addHeader("content-type", "application/json")
//.addHeader("cache-control", "no-cache")
//.addHeader("postman-token", "c3d60511-7e0f-5155-b5ad-66031ad76578")
.build();
// execute request
try {
Response response = client.newCall(request).execute();
String responseData = response.body().toString();
// Response code 200 means login details found in DB
if(response.code() == 200){
etfirstName.setText(responseData);
} else if(response.code() == 401){
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
//wait for thread to finish
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The issue is that I am getting the response of: okhttp3.internal.http.RealResponseBody#b8a47c8 as the response.body().toString(). I have tested the API call using postman and do get the correct response of:
{"user":"Joe","lastName":"smith","weight":108,"height":179,"dob":"1980-09-06","email":"JoeSmith#gmail.com"}
I think I am messing up the Request. Builder but I can't figure this out.
Cheers
Peter
You have mistaken the string() method from the ResponseBody object with the usual toString() method.. Here are some docs for it.
Just have:
String responseData = response.body().string();
instead of:
String responseData = response.body().toString();
You can find some info in here also
I have got a simple Jersey REST Webservice which will read the rss mix url and display the latest news to the website .
But the issue i am facing is that the response is being very slow sometimes and i am getting timeout many times (Ajax call)
will the cache help ??
#Path("/latestnews")
public class RssReader {
#GET
#Produces("text/plain")
public String hello() {
JSONArray latestnews = new JSONArray();
try {
String url = "http://www.rssmix.com/u/8159030/rss.xml";
URL feedUrl = new URL(url);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
for (SyndEntry entry : (List<SyndEntry>) feed.getEntries()) {
JSONObject jsonobj_latestnews = new JSONObject();
String title = entry.getTitle();
String link = entry.getLink();
String pub_date = entry.getPublishedDate().toString();
jsonobj_latestnews.put("title", title).put("link", link).put("pub_date", pub_date);
latestnews.put(jsonobj_latestnews);
}
} catch (Exception e) {
e.printStackTrace();
}
return "jsonCallback(" + latestnews.toString() + ")";
}
}
Could you please let me know how can i improve the response time of the above ajax call ??
Thanks in advance