How to use Twilio SendGrid Java Helper Library with azure functions? - java

I am using SendGrid as the output of one of my azure function. And I am sending the same email to multiple users with the help of personalization. The code is as follows
#FunctionName("ehprocessor")
public void eventHubProcessor(
#EventHubTrigger(name = "msg", eventHubName = "", connection = "eventhubConnString", cardinality = Cardinality.ONE) String eventHubMessage,
#SendGridOutput(name = "message", dataType = "String", apiKey = "sendGridAPIKey", to = "jithin#mailinator.com", from = "jithin#vinnovatelabz.com", subject = "Event From The Machine", text = "Sent from Azure Functions") OutputBinding<String> message,
final ExecutionContext context) {
final String toAddress = "jithin#mailinator.com";
final String toAddressMail = "jishnu#mailinator.com";
StringBuilder builder = new StringBuilder().append("{")
.append("\"personalizations\": [{ \"to\": [{ \"email\": \"%s\"},{ \"email\": \"%s\"}]}],")
.append("\"content\": [{\"type\": \"text/plain\", \"value\": \"%s\"}]").append("}");
final String body = String.format(builder.toString(), toAddress, toAddressMail, value);
message.setValue(body);
}
As you can see I am using the Json body to personalize the things. but now I want to use the helper library for sendgrid provided by java. How can I use it. Can somebody give me a code snippet of that?

You can use Twilio SendGrid library to send Email in java by following the below steps:
If you are using Maven then add this dependency in pom.xml:
<dependency>
<groupId>com.sendgrid</groupId>
<artifactId>sendgrid-java</artifactId>
<version>4.4.1</version>
</dependency>
Create a new class called SendGridEmailer in your project with the following content:
import com.sendgrid.*;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.*;
import java.io.IOException;
public class SendGridEmailer {
public static void main(String[] args) throws IOException {
Email from = new Email("test#example.com");
Email to = new Email("test#example.com");
String subject = "Sending with Twilio SendGrid ";
Content content = new Content("text/html", "and Sending with Twilio SendGrid <strong>Java</strong>");
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getHeaders());
System.out.println(response.getBody());
}
}
Here, API key is read from an environment variable.

Related

Post message creating message in Draft State Microsoft Graph API Java

When I try to send a message using Microsoft Graph Java API, It's state is Draft.
Authentication.initialize(appId);
final String accessToken = Authentication.getUserAccessToken(appScopes);
authProvider = new SimpleAuthProvider(accessToken);
// Create default logger to only log errors
DefaultLogger logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.DEBUG);
// Build a Graph client
graphClient = GraphServiceClient.builder()
.authenticationProvider(authProvider)
.logger(logger)
.buildClient();
IMailFolderDeltaCollectionPage mailFolderCollectionPage = graphClient.me().mailFolders().delta()
.buildRequest().get();
AtomicReference<String> inBoxFolderId = new AtomicReference<>("");
while (mailFolderCollectionPage.getNextPage() != null) {
List<MailFolder> mailFolders = mailFolderCollectionPage.getCurrentPage();
mailFolders.forEach(m -> {
if (m.displayName.equals("Inbox")) {
inBoxFolderId.set(m.id);
}
});
mailFolderCollectionPage = mailFolderCollectionPage.getNextPage().buildRequest().get();
}
IMessageDeltaCollectionPage messageCollectionPage = graphClient.me().mailFolders("Inbox")
.messages().delta().buildRequest().get();
Message backedMessaged = null;
while (messageCollectionPage.getNextPage() != null) {
System.out.println("messageCollectionPage = " + messageCollectionPage);
List<Message> messageList = messageCollectionPage.getCurrentPage();
backedMessaged = messageList.get(0);
break;
}
graphClient.me().mailFolders("Inbox").messages().buildRequest().post(backedMessaged);
When you create an Outlook message, its state will remain as draft until you send it. You should use the send request to send your message. It will then not be marked as draft anymore.
Look here for more informations : https://learn.microsoft.com/fr-fr/graph/api/message-send?view=graph-rest-1.0&tabs=http

How to add SAS for file services of azure in java?

I got code in c# or code for blob storage. I need some reference code in java to have SAS token for file storage in azure. The SAS may be applicable for account or services.
Code 1 :
static string GetAccountSASToken()
{
// To create the account SAS, you need to use your shared key credentials. Modify for your account.
const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);
// Create a new access policy for the account.
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
{
Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.List,
Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
ResourceTypes = SharedAccessAccountResourceTypes.Service,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
Protocols = SharedAccessProtocol.HttpsOnly
};
// Return the SAS token.
return storageAccount.GetSharedAccessSignature(policy);
}
This code is about creating SAS token for account verification and expiry time.I need the same in java. I am not getting few things like, in first code how I can write the 'Permission' in java? I mean multiple in one line. Please provide equivalent java code for this.
Code 2 :
#Test
public String testFileSAS(CloudFileShare share, CloudFile file) throws InvalidKeyException,
IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
SharedAccessFilePolicy policy = createSharedAccessPolicy(EnumSet.of(SharedAccessFilePermissions.READ,
SharedAccessFilePermissions.LIST, SharedAccessFilePermissions.WRITE), 24);
FileSharePermissions perms = new FileSharePermissions();
// SharedAccessProtocols protocol = SharedAccessProtocols.HTTPS_ONLY;
perms.getSharedAccessPolicies().put("readperm", policy);
share.uploadPermissions(perms);
// Thread.sleep(30000);
CloudFile sasFile = new CloudFile(
new URI(file.getUri().toString() + "?" + file.generateSharedAccessSignature(null, "readperm")));
sasFile.download(new ByteArrayOutputStream());
// do not give the client and check that the new file's client has the
// correct permissions
CloudFile fileFromUri = new CloudFile(
PathUtility.addToQuery(file.getStorageUri(), file.generateSharedAccessSignature(null, "readperm")));
assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
fileFromUri.getServiceClient().getCredentials().getClass().toString());
// create credentials from sas
StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
file.generateSharedAccessSignature(policy, null, null));
System.out.println("Generated SAS token is : " + file.generateSharedAccessSignature(policy, null, null));
String token = file.generateSharedAccessSignature(policy, null, null);
CloudFileClient client = new CloudFileClient(sasFile.getServiceClient().getStorageUri(), creds);
CloudFile fileFromClient = client.getShareReference(file.getShare().getName()).getRootDirectoryReference()
.getFileReference(file.getName());
assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
fileFromClient.getServiceClient().getCredentials().getClass().toString());
assertEquals(client, fileFromClient.getServiceClient());
// self written
// String sharedUri =
// file.generateSharedAccessSignature(policy,null,null);
// System.out.println("token created is : "+sharedUri);
return token;
}
private final static SharedAccessFilePolicy createSharedAccessPolicy(EnumSet<SharedAccessFilePermissions> sap,
int expireTimeInSeconds) {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(new Date());
calendar.add(Calendar.HOUR, expireTimeInSeconds);
SharedAccessFilePolicy policy = new SharedAccessFilePolicy();
policy.setPermissions(sap);
policy.setSharedAccessExpiryTime(calendar.getTime());
return policy;
}
This code is a jUnit test. I don' want to import jUnit library. Want to do it in pure java.How I can convert the code? What I can use instead of assertEqauls?
Please consider the following code snippet in Java.
public static final String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
public String getAccountSASToken() throws InvalidKeyException, URISyntaxException, StorageException {
CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy();
policy.setPermissions(EnumSet.of(SharedAccessAccountPermissions.READ, SharedAccessAccountPermissions.WRITE, SharedAccessAccountPermissions.LIST));
policy.setServices(EnumSet.of(SharedAccessAccountService.BLOB, SharedAccessAccountService.FILE) );
policy.setResourceTypes(EnumSet.of(SharedAccessAccountResourceType.SERVICE));
policy.setSharedAccessExpiryTime(Date.from(ZonedDateTime.now(ZoneOffset.UTC).plusHours(24L).toInstant()));
policy.setProtocols(SharedAccessProtocols.HTTPS_ONLY);
return account.generateSharedAccessSignature(policy);
}

Standardization of a REST API using swagger core and swagger UI

I am trying to standardize a very basic REST Service made using jax-rs that converts temperature from Celsius to Fahrenheit and vice-a-versa. The class I am trying to standardize contains a simple code for converting temperature. I am trying to incorporate Swagger-Core to create a JSON file but the JSON file created is not in the Swagger syntax. The reason is that the swagger annotations I am using are not creating the JSON file , instead the JSON is created by the the return statement of the method. I have tried several approaches but in vain.Is there an issue with the annotations being used or is the create JSONObject ovveriding the Swagger part?
import org.json.JSONException;
import org.json.JSONObject;
import io.swagger.annotations.*;
#Api
#SwaggerDefinition(
info = #Info(
description = "My API",
version = "V1.2.3",
title = "The only API you'll ever need to learn about me",
termsOfService = "share and care",
contact = #Contact(name = "Sponge-Bob", email = "sponge-bob#swagger.io", url = "http://swagger.io"),
license = #License(name = "Apache 2.0", url = "http://www.apache.org")
),
consumes = {"application/json" },
produces = {"application/json" },
schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS},
externalDocs = #ExternalDocs(value = "About me", url = "http://about.me/me"))
#Path("/ftocservice")
#Produces({"application/json"})
public class FtoCService {
#GET
public Response convertFtoC() throws JSONException {
JSONObject jsonObject = new JSONObject();
Double fahrenheit = 98.24;
Double celsius;
celsius = (fahrenheit - 32)*5/9;
jsonObject.put("FtoC", celsius);
String result = ""+jsonObject;
return Response.status(200).entity(result).build();
}

Google App Engine. Stackdriver. Logging with Java

I want to POST Logs to "Custom Logs" of Stackdriver. These feature is beta, and maybe therefore it has no description, how to use Logging with Java API on App Engine. Anyway I want to describe my problem: I use this API version:
"com.google.apis:google-api-services-logging:v2beta1-rev10-1.21.0"
So, first I build the Logging Object like this (I hope this is right):
public static Logging createAuthorizedClient() throws IOException {
// Create the credential
HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
if (credential.createScopedRequired()) {
credential = credential.createScoped(LoggingScopes.all());
}
return new Logging.Builder(transport, jsonFactory, credential).setApplicationName(SharedConstants.APPLICATION_ID).build();
}
After I get the Logging client, I try to push an Entry to the Log:
LogEntry lEntry = new LogEntry();
lEntry.setTextPayload("I want to see this log!");
WriteLogEntriesRequest writeLogEntriesRequest = new WriteLogEntriesRequest();
writeLogEntriesRequest.setLogName("My Super log");
List<LogEntry> listEntries = new ArrayList<>();
listEntries.add(lEntry);
writeLogEntriesRequest.setEntries(listEntries);
Logging logging = LoggingManager.createAuthorizedClient();
Write write = logging.entries().write(writeLogEntriesRequest);
WriteLogEntriesResponse writeLogResponse = write.execute();
But what I get is:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 OK
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid resource id",
"reason" : "badRequest"
} ],
"message" : "Invalid resource id",
"status" : "INVALID_ARGUMENT"
}
=== UPDATE: WORKING SOLUTION ===
Thanks to mshamma. Here is complete code, how to send the data to the logging:
public boolean send() {
WriteLogEntriesResponse response = null;
try {
final String now = getNowUtc();
final String insertId = "entry-at-" + now;
final Map<String, String> labels = ImmutableMap.of("project_id", SharedConstants.APPLICATION_ID, "name",
"projects/" + SharedConstants.APPLICATION_ID + "/logs/" + this.logName);
Logging service = createAuthorizedClient();
MonitoredResource ressource = new MonitoredResource();
ressource.setType("logging_log");
ressource.setLabels(labels);
LogEntry entry = new LogEntry().setInsertId(insertId).setResource(ressource).setTimestamp(now)
.setJsonPayload(this.entriesMap)
.setLogName("projects/" + SharedConstants.APPLICATION_ID + "/logs/" + this.logName)
.setSeverity(this.severity);
WriteLogEntriesRequest content = (new WriteLogEntriesRequest())
.setEntries(Collections.singletonList(entry));
response = service.entries().write(content).execute();
} catch (Exception e) {
}
return response != null;
}
private static String getNowUtc() {
SimpleDateFormat dateFormatUtc = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
dateFormatUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormatUtc.format(new Date());
}
This code works fine with the last version of logging api
Thereby the EntriesMap is:
private Map<String, Object> entriesMap;
I ran into the same issue in the unmanaged Python environment. I got things working and I can see at least two issues in your code.
The log name needs to follow the pattern: "projects/<project-id>/logs/<log-id>". See the documentation of the field here: https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/LogEntry#SCHEMA_REPRESENTATION
You should add a resource descriptor both to the log entry (lEntry) and the write log entry request (writeLogEntriesRequest). In the case of GAE, the resource type field should be set to "gae_app" and you must add three labels to the resource that identify your GAE deployment: "project_id", "module_id" and "version_id".
I hope that will help resolve your issue!

Chat bot using google app engine is not replying

heres the code
it basically takes a message and echos it back.
the problem is it is not replying at all :(
in google app engine, my applications page, i get error-"The requested URL /guestbook was not found on this server."
package guestbook;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.*;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
#SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {
private static final Logger LOG =
Logger.getLogger(GuestbookServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// Parse incoming message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
Message msg = xmpp.parseMessage(req);
JID jid = msg.getFromJid();
String body = msg.getBody();
LOG.info(jid.getId() + " --> JEliza: " + body);
// Get a response from Eliza
String response = "echo: " + body;
LOG.info(jid.getId() + " <-- JEliza: " + response);
// Send out response
msg = new MessageBuilder()
.withRecipientJids(jid)
.withBody(response)
.build();
xmpp.sendMessage(msg);
/*Message message = xmpp.parseMessage(req);
JID fromJid = message.getFromJid();
String body = message.getBody();
String respMsg = null;
if (body.equals("/list")) {
respMsg = "Hi";
} else if (body.equals("/help")) {
respMsg = "Welcome to the Guestbook Chatbot!\nThe following commands are supported: \n /list \n /help";
} else {
respMsg = "Command '" + body + "' not supported! \nEnter '/help' for list of commands.";
}
JID tojid = new JID(fromJid.getId());
Message msg = new MessageBuilder().withRecipientJids(tojid).withBody(respMsg).build();
boolean messageSent = false;
xmpp = XMPPServiceFactory.getXMPPService();
if (xmpp.getPresence(tojid).isAvailable()) {
SendResponse status = xmpp.sendMessage(msg);
messageSent = (status.getStatusMap().get(tojid) == SendResponse.Status.SUCCESS);
}*/
}
}
As per the details you have given i think the problem should be with the web.xml file
<servlet><servlet-name>GuestbookServlet</servlet-name><servlet-class>your.package.structure.GuestbookServlet</servlet-class></servlet><servlet-mapping><servlet-name>GuestbookServlet</servlet-name><url-pattern>/_ah/xmpp/message/chat/</url-pattern></servlet-mapping>
try adding this into the web.xml change your.package.structure.GuestbookServlet accordingly for example mine would be com.appengine.capp
JDK settings had to be changed from 1.7 to 1.6.
under window-> preferences -> java -> compiler

Categories