How to initialize Email without hardcoding using sendgrid with java - java

How can I initialize email in my service class without hardcoding(eg : Email to = new Email("1234#gmail.com"). I use the following code to initialize my email but it returns some error. Help me to fix this. I'm using SendGrid API. Here is my service code:
Email to = new Email();
to.setEmail(emailIDTO.getTO()); //emailIDTO is an object of IDTO class
// IDTO class takes the value from the JSON request body and initializes it to the email object
And the relevant IDTO snippet:
public Email getTo(){
return to;
} // method getTo return the mail id of the recipient.
public Email createTo(EmailIDTO emailIDTO){
to.setName(emailIDTO.getName();
to.setEmail(emailIDTO.getEmail());
return null;
}
Error :
setEmail (java.lang.String) in Email cannot be applied to (com.sendgrid.Email)
 

Your code is failing because your emailIDTO.getTO() method is returning Email object, which you are trying to assign using method that accepts String parameter. The error is pretty self-explanatory in this case.
You can try one of the following:
Option 1 - set object directly from IDTO:
Email to = emailIDTO.getTO();
Option 2 - extract the string value:
Email to = new Email();
to.setEmail(emailIDTO.getTO().getEmail());
Caution - your IDTO.createTo() method returns null, which may have unexpected consequences. Perhaps you wanted to return to?

Related

Rest Assured code not allowing to use println

I am trying to automate twitter API. when tried to print "js.get("text") using
System.out.println(js.get("text")); I am getting error as
"The method println(boolean) is ambiguous for the type PrintStream"
I downloaded jars and passed in Build path as well "scribejava-apis-2.5.3" and "scribejava-core-4.2.0"
Below code is not allowing me use println for ------>js.get("text")
public class Basicfunc {
String Consumerkeys= "**************";
String Consumersecretkeys="*******************";
String Token="*******************";
String Tokensecret="***************************";
#Test
public void getLatestTweet(){
RestAssured.baseURI = "https://api.twitter.com/1.1/statuses";
Response res = given().auth().oauth(Consumerkeys, Consumersecretkeys, Token, Tokensecret).
queryParam("count","1").
when().get("/home_timeline.json").then().extract().response();
String response = res.asString();
System.out.println(response);
JsonPath js = new JsonPath(response);
System.out.println(js.get("text"));
}
}
Use System.out.println(js.getString("text")); instead of System.out.println(js.get("text"));, because get returns any primitive value.
I think your problem is that your twitter response is actually a list.
Try to use System.out.println(js.getList()[0].get("text")); and be aware that you are only using the first [0] entry and ignoring the rest.

reading two variable values after decrypting

I am working on "Forgot Password". I am trying to create a reset token with email + current_time. email is user login whilst code will check if time >= 5 minutes then this link will not work. Here is my code:
// preparing token email + time
Date now = new Date();
String prepareToken = "?email="+email+"&tokenTime="+now.getTime();
// encrypt prepareToken value
Encryptor enc = new Encryptor();
resetToken = enc.encrypt(resetToken);
The token will be sent as for example as http://domainname.com/ForgotPassword?resetToken=adj23498ljj238809802340823
Problem:
When user click it then I got as request parameter and obviously decrypt this parameter but how can I get email in one String + time as another String
Please advise
If your issue is simply parsing the decoded String to get some sort of Map of your parameters, I'd suggest you to read Parse a URI String into Name-Value Collection .
Hope it helps.
EDIT :
Assuming you have the splitQuery(URL url) method from the previous link and that you successfully decoded the token :
public String getEmailFromToken(String decodedToken) {
// if you decoded your token it will looks like the prepareToken String
String stubUrl = "http://localhost"+decodedToken;
Map<String,String> map = splitQuery(new URL(stubUrl));
return map.get("timeToken");
}
I created a properly formed URL to respect the URL syntax.
With little tweak, you should be able to implement splitQuery for a String. I hope you can manage that.

XSnippet EmailBean error

I na project I want to use the EmailBean written by Tony McGuckin, IBM
https://openntf.org/XSnippets.nsf/snippet.xsp?id=emailbean-send-dominodocument-html-emails-cw-embedded-images-attachments-custom-headerfooter
However I get an error message when I want to loop through a list of people I want to address:
for (String person : persons) {
EmailBean emailBean = new EmailBean();
emailBean.setSendTo(person);
emailBean.setSubject("You have been mentioned");
emailBean.setSenderEmail("pk#mail.com");
emailBean.setSenderName("PK's app");
Document mail = null;
mail = db.createDocument();
> emailBean.setDocument( mail);
emailBean.setFieldName("Body");
emailBean.setBannerHTML("<p>You have been mentioned in a discussion on PK's App:</p>");
emailBean.setFooterHTML("<p>Kind regards,<br/>PK App<br/></p>");
emailBean.send();
}
The error message I get resides at the > line:
The method setDocument(DominoDocument) in the type EmailBean is not applicable for the arguments (Document) Comment.java comments.nsf/Code/Java/org/quintessens/comments line 98 Java Problem
I have tried to cast the Document as a DominoDocument but then I get an error at line
emailBean.send();
What should I change?
Your mail variable is a Document object. You need to wrap it into a DominoDocument object (the object used as Domino Document datasource)
after your line :
mail = db.createDocument();
add :
DominoDocument wrappedMail = DominoDocument.wrap(db.getFilePath(), mail, null, null, false, null, null);
then use it in your email bean :
emailBean.setDocument( wrappedMail );
But you will have to set something in the "body" field of your document created with this line :
mail = db.createDocument();
and before wrapping it, because the content of the mail you'll send is taken from this field.
But if you want to send "simple" content, use the class from Ulrich Krause in his comment of the XSnippet page which still give you the possibility to add the content of a field to the email but also let you add "simple" content.
Then remove the following lines in your original code :
Document mail = null;
mail = db.createDocument();
emailBean.setDocument( mail);
emailBean.setFieldName("Body");
And use this instead :
emailBean.addHtml("this is my mail content");
You can call this as many times as needed
To get the DominoDocument from a Document, a typical (DominoDocument) will not work.
You need to call the wrap method of the DominoDocument.
See the API, http://public.dhe.ibm.com/software/dw/lotus/Domino-Designer/JavaDocs/DesignerAPIs/com/ibm/xsp/model/domino/wrapped/DominoDocument.html#wrap(java.lang.String, lotus.domino.Document, java.lang.String, java.lang.String, boolean, java.lang.String, java.lang.String)

"Cast" a String Attribute to String Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a little problem with Attributes. I am currently working on a project that parses emails from an LDAP server into the Java application that will be doing some interesting stuff with emails in the future.
I am currently having this code that takes emails from users on LDAP and it needs to put emails in the User class as seen in my code:
[some code here, TRY CATCH is also included]
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum2 = ctx.search("[path to the server]", "(objectClass=user)", getSimpleSearchControls());
System.out.println("Test: print emails from whole DIRECOTRY: \n");
while (namingEnum2.hasMore()) {
SearchResult result = (SearchResult) namingEnum2.next();
Attributes attrs = result.getAttributes();
System.out.println(attrs.get("mail"));
/** This line above works fine, but every time there is no email
in User info, it prints "null" in some cases when there is
no email, which is not perfect. But this is just here to see
if everything works and indeed it does.**/
/**User Class accepts a String parameter, checks if it's empty
and all that, does some checking and etc... BUT! attrs.get("mail")
is an Attribute, NOT a String. And I need to somehow "cast" this
attribute to a String, so I can work with it.**/
User user = new User(attrs.get("mail")); //error yet,because the parameter is not a String.
User user = new User(attrs.get("mail").toString());//gives an expeption.
/** And I know that there is a toString() method in Attribute Class,
but it doesn't work, it gives an "java.lang.NullPointerException"
exception when I use it as attrs.get("mail").toString() **/
}
Here is User class's constructor:
public User(String mail){
eMail = "NO EMAIL!";
if (mail != null && !mail.isEmpty()){
eMail = mail;
}
else
{
eMail = "NO EMAIL!";
}
}
try this
User user = new User(attrs.get("mail")!=null?attrs.get("mail").toString():null);
First you need to check that given attribute exists by using != null (e.g. using Objects.toString which does that inside, or manual if) check, and then use either toString on the Attribute, just like println does inside:
User user = new User(Objects.toString(attrs.get("mail")));
Or you can also use (to retrieve a single value in the attribute, if you have many you need to use getAll):
Object mail = null;
if (attrs.get("mail") != null) {
mail = attrs.get("mail").get();
}
User user = new User(mail.toString());

Lotus Notes - Mail Document - Principal/From,INetFrom, SentTime, ReceivedTime fields

I have a requirement to fetch the SenderName,SenderEmail,ToNames,ToEmails,CCNames,CcEmails from a lotus notes document instance.
Issue1
Looking into lotus.domino.Document API I found out the method getItems. When I write the elements to the system.out values for SenderEmail, ToEmails and CcEmails can be found.
However values for SenderName(a.k.a From), ToNames cannot be derived that easily.
The values seems to be using an common name format. For example check check my system.output below.
Principal = "CN=Amaw Scritz/O=fictive"
$MessageID = "<OF0FF3779B.36590F8A-ON80257D15.001DBC47-65257D15.001DC804#LocalDomain>"
INetFrom = "AmawScritz#fictive.com"
Recipients = "CN=Girl1/O=fictive#fictive"
MailOptions = "0"
SaveOptions = "1"
From = "CN=Amaw Scritz/O=fictive"
AltFrom = "CN=Amaw Scritz/O=fictive"
SendTo = "CN=Girl1/O=fictive#fictive"
CopyTo = "CN=Girl2/O=fictive#fictive"
BlindCopyTo = ""
InetSendTo = "Girl1#fictive.com"
InetCopyTo = "Girl2#fictive.com"
$Abstract = "sasdasda"
$UpdatedBy = "CN=Amaw Scritz/O=fictive"
Body = "Hello World"
The question is how can I get 'Amaw Scritz' from the common name 'CN=Amaw Scritz/O=fictive'. Is there any look up mechanism that can be used. (I would prefer to have a option other than doing a substring of the common name)
Issue2
is it possible to retrieve SentTime and ReceivedTime from mail document instance?
I know that there are two methods called getCreated and getLastModified. getCreated can be loosely associated with the SentTime and getLastModified can be loosely associated with ReceivedTime. Are there are other ways to get times for SentTime and ReceivedTime.
Issue3
How can one distinguish whether a mail document is a Sent mail or a Received Mail?
Issue1
You can use Name class.
Here example from this link:
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
// (Your code goes here)
// Create a hierarchical name
Name nam = session.createName(
"CN=John B Goode/OU=Sales/OU=East/O=Acme/C=US");
// Returns:
// John B Goode
// John B Goode/Sales/East/Acme/US
// CN=John B Goode/OU=Sales/OU=East/O=Acme/C=US
System.out.println(nam.getCommon());
System.out.println(nam.getAbbreviated());
System.out.println(nam.getCanonical());
} catch(Exception e) {
e.printStackTrace();
}
}
}
Issue2
Use values of PostedDate field and DeliveredDate field of mail document.
Issue3
Check that $Inbox folder contains your mail document. Or take a look at Dave Delay answer.
I agree with #nempoBu4 on Issues 1 and 2. I disagree with the answer to Issue 3. A received message can be removed from the inbox, so checking $Inbox doesn't help you distinguish between sent and received messages.
Assuming you have the document open, the best approach is to check two items. Sent and received messages both have a PostedDate item, but only a received message has a DeliveredDate item. Incidentally, a draft message has neither PostedDate or DeliveredDate.

Categories