I have used the java mail API to send emails within our group. I am aware of the DataHandler objects that in turn uses FileDataSource to grab the files and attach as a multipart file. However, I am not able to use it in scala. Can anyone help me on this?
Heres my code:
def createMessage: Message = {
val properties = new Properties()
properties.put("mail.smtp.host", smtpHost)
properties.put("mail.smtp.port",smtpPort)
val session = Session.getDefaultInstance(properties, null)
return new MimeMessage(session)
}
var message: Message = null
message = createMessage
message.setFrom(new InternetAddress(from))
message.setSentDate(new Date())
message.setSubject(subject)
message.setText(content)
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to))
def sendMessage {
Transport.send(message)
}
I can use message.sefileName to set file name of the attachment, but how can I attach the actual files. For example in Java, we can achieve similar results like the following:
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
FileDataSource fdatasource = new FileDataSource(file);
messageBodyPart2.setDataHandler(new DataHandler(fdatasource));
messageBodyPart2.setFileName(fdatasource.getName)
Multipart mpart = new MimeMultipart();
mpart.addBodyPart(messageBodyPart1);
mpart.addBodyPart(messageBodyPart2);
message.setContent(mpart);
I don't know this mail API, but you should be able to use a Java API the same way in Scala that you would use it in Java. If you see something like this in Java:
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
You usually want to translate it to something like this in Scala:
val messageBodyPart1: MimeBodyPart = new MimeBodyPart()
messageBodyPart1.setText(messageText)
Just translate the Java code you have posted to Scala this way and it should work as well (or not well) as it worked in Java.
Related
I have a requirement where-in I have to read the JSON file which exists in AEM DAM. So, I have created a query to read the JSON file in inputStream. With the below line of code, i could get the JSON file in Input Stream. Now, I need to know If there is any standard library to read the input stream and create the JSON Object?
InputStream is = asset.getOriginal().getStream();
There are many libraries for serializing/deserializing JSON in java, the most notable is Google’s Gson: https://github.com/google/gson
I’ve used gson in all my AEM projects that require JSON manipulation. That does not mean you can’t use another library.
As mentioned above there are many libraries like Google’s Gson, Jackson an etc. I think the below code snippet can help you,
public JSONObject getJsonFromFile(ResourceResolver resolver,String filePath){
JSONObject jsonObj=new JSONObject();
Resource resource= resolver.getResource(filePath);
try {
Node jcnode = resource.adaptTo(Node.class).getNode("jcr:content");
InputStream content=jcnode.getProperty("jcr:data").getBinary().getStream();
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new
InputStreamReader(content,StandardCharsets.UTF_8));
while ((line = br.readLine()) != null) {
sb.append(line);
}
jsonObj = new JSONObject(sb.toString());
}catch (RepositoryException | JSONException | IOException e) {
LOGGER.error(e.getMessage(),e);
}
return jsonObj;
}
I am using HtmlEmail Class of ApacheCommons for sending HTML formatted email with embedded images
Apache Commons Email API (v1.4) is used in my Scala project
I am not Seeing the Alias (MY REPORTS) as sender name in my Received Email
Following is my Function
#throws(classOf[EmailException])
#throws(classOf[Exception])
def createHTMLEmailMessage(htmlContent: String): EmailMessage = {
val email = new HtmlEmail
// alternative message if the client does not support html
email.setHtmlMsg(htmlContent)
email.addTo("TO_address#gmail.com")
email.setFrom("MY_address#GMAIL.com", "MY REPORTS")
email.setHostName("MY_HOSTNAME")
email.setSmtpPort(587)
email.setAuthentication("USERNAME","PASSWORD")
email.setStartTLSEnabled(true)
email.setSSLOnConnect(false)
email.setSubject("Subject")
val emailMsg = EmailMessage(email)
emailMsg
}
I have an XML string that I would like to deserialize into a strongly typed class. The below code works great until I put it into a sandboxed plugin, at which point I get a FileIOPermissions error because I am using the StringReader class. I am having issues trying to deserialize without using StringReader. Does anyone have a good alternative?
byte[] binary = Convert.FromBase64String(configurationWebResource.Attributes["content"].ToString());
resourceContent = UnicodeEncoding.UTF8.GetString(binary);
DataContractSerializer serializer = new DataContractSerializer(typeof(ViewSecurityConfiguration));
using (StringReader reader = new StringReader(resourceContent))
{
using (XmlTextReader xmlReader = new XmlTextReader(reader))
{
if (serializer.IsStartObject(xmlReader)) //Throws FileIOPermissions error
{
currentViewSecurityConfiguration = (ViewSecurityConfiguration)(serializer.ReadObject(xmlReader));
}
}
}
Try the following which I've run successfully in a sandbox plugin:
byte[] binary = Convert.FromBase64String(configurationWebResource.Attributes["content"].ToString());
resourceContent = UnicodeEncoding.UTF8.GetString(binary);
XmlSerializer serializer = new XmlSerializer(typeof(ViewSecurityConfiguration));
using (StringReader reader = new StringReader(resourceContent))
{
currentViewSecurityConfiguration = (ViewSecurityConfiguration)serializer.Deserialize(reader);
}
I'm kind of newbie to this...Basicly I need to run a script to download .csv files from google trends. I wrote the following code according to this reference , the code is like:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
nameValuePairs.add(new BasicNameValuePair("Email", "myEmail"));
nameValuePairs
.add(new BasicNameValuePair("Passwd", "myPasswd"));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "xapi"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
if (line.startsWith("SID=")) {
String key = line.substring(4);
// Do something with the key
} catch (Exception e) {
}
I got the information about SID, LSID, Auth, but don't know how to use these information. I guess I should add these cookies in my following request, but don't know exactly how. I wrote another piece of code to connect to the certain URL, but I keep getting this message "You must be signed in to export data from Google Trends." The code is here if it helps:
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty("Authorization", "SID"+key);
conn.addRequestProperty("Email", "myEmail");
conn.addRequestProperty("Passwd", "myPasswd");
conn.setReadTimeout(5000);
conn.connect();
I searched around and found few useful information, anyone could help?
Does it have to be in Java? In python, it's as simple as this:
from pyGTrends import pyGTrends
connector = pyGTrends('google username','google password')
connector.download_report(('keyword1', 'keyword2'))
print connector.csv()
You'll need the google trends api library.
If it has to be Java, you may want to look at the HttpClient examples from Apache. "Form based logon" and "client authentication" may both be relevant.
I have just coded this:
https://github.com/elibus/j-google-trends-api
It is an unofficial Java implementation of Google Trends API. You could use it to easily access Google Trends or you might want to have a look at the code to see it works.
Anyway the authentication flow works as follows (all the steps are required):
Fetch https://accounts.google.com/ServiceLoginAuth and parse the GALX id
Post username/password + GALX
Get http://www.google.com
Then you can access Google Trend with relaxed QoS policies for authenticated users.
I have developed a Gwt application and need now to call its remote service implementation
from another java application. Is there a method that given a List of Java Objects can transform them in a format suitable for invoking the get service servlet?something like:
myObject = .......
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://localhost:8080/ppp//org.yournamehere.Main/gwtservice");
String serialized = <somelibrary.serialize>(myObject);
StringEntity input = new StringEntity(serialize);
input.setContentType("text/x-gwt-rpc; charset=UTF-8");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
Although, I haven't tried it the following link seems to be what you are looking for
http://googlewebtoolkit.blogspot.com/2010/07/gwtrpccommlayer-extending-gwt-rpc-to-do.html