Send html email with java using html external template? - java

I'm trying to send an HTML email with parameters and attachments.
What i have right now is this code:
<%#include file="/libs/fd/af/components/guidesglobal.jsp" %>
<%#page import="com.day.cq.wcm.foundation.forms.FormsHelper,
org.apache.sling.api.resource.ResourceUtil,
org.apache.sling.api.resource.ValueMap,
org.apache.sling.api.request.RequestParameter,
com.day.cq.mailer.MessageGatewayService,
com.day.cq.mailer.MessageGateway,
org.apache.commons.mail.Email,
org.apache.fulcrum.template.TemplateHtmlEmail,
org.apache.commons.mail.*" %>
<%#taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0" %>
<%#taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0"
%>
<cq:defineObjects/>
<sling:defineObjects/>
<%
String storeContent = "/libs/fd/af/components/guidesubmittype/store";
FormsHelper.runAction(storeContent, "post", resource, slingRequest, slingResponse);
ValueMap props = ResourceUtil.getValueMap(resource);
HtmlEmail email = new HtmlEmail();
String[] mailTo = props.get("mailto", new String[0]);
email.setFrom((String)props.get("from"));
for (String toAddr : mailTo) {
email.addTo(toAddr);
}
String htmlEmailTemplate = props.get("templatePath");
//========Email Attachments===============
for (Map.Entry<String, RequestParameter[]> param : slingRequest.getRequestParameterMap().entrySet()) {
RequestParameter rpm = param.getValue()[0];
if(!rpm.isFormField()) {
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(rpm.getFileName());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Any Description");
attachment.setName("Any name you can set");
email.embed(new ByteArrayDataSource(rpm.get(), rpm.getContentType()), rpm.getFileName());
}
}
//========Email Attachment END===========
String emailTextToSend = "<p>Company Name: " + slingRequest.getParameter("company-name") + "</p>";
emailTextToSend += "<p>Message: " + slingRequest.getParameter("address") + "</p>";
email.setHtmlMsg(emailTextToSend);
email.setSubject((String)props.get("subject"));
MessageGatewayService messageGatewayService = sling.getService(MessageGatewayService.class);
MessageGateway messageGateway = messageGatewayService.getGateway(HtmlEmail.class);
messageGateway.send(email);
%>
With this code i can send the email, but i want to modify the code to use a path to an html template file (the path is on the variable htmlEmailTemplate.
This is my first question, how to change that code.
My second question is that if in that template i can have something like this:
<span>${company-name}</span>
Where company-name is one of the fields that i want to use on the template.
Is this possible?

Take a look at the com.day.cq.commons.mail.MailTemplate api
if your template is in the JCR repository, you can instantiate it with something like:
String template = values.get(TEMPLATE_PROPERTY, String.class);
Resource templateRsrc = request.getResourceResolver().getResource(template);
final MailTemplate mailTemplate = MailTemplate.create(templateRsrc.getPath(),
templateRsrc.getResourceResolver().adaptTo(Session.class));
final HtmlEmail email = mailTemplate.getEmail(StrLookup.mapLookup(properties), HtmlEmail.class);
Where properties is simply a HashMap of Key:Values for the template's own properties.
Since the MailTemplate returns a HtmlEmail object, you can still set all the settings you set in your own code as well.

Related

Unable to include a JSP file

I am trying to check for a file exists and then include the JSP file if true. But I am getting errors from below code.
Syntax error on tokens, delete these tokens
file.handler cannot be resolved to a type
Syntax error on token "=", . expected
This is my code:
String uri = request.getRequestURI();
String pageName = uri.substring(uri.lastIndexOf("/")+1);
String filename = pageName.replace(".jsp", "");
String path = request.getServletPath();
path = path.replace( pageName , "");
String handler=path+"handler/"+filename+"_handler.jsp";
if(null != application.getResource(handler)){
<%#include file="${handler}"%>
}
I am a PHP programmer but I am new to JSP. Please advice
You might try a dispatcher to include a resource
if(null != application.getResource(handler)){
request.getRequestDispatcher(handler).include(request, response);
}
Try with JSP Expression something like:
<%#include file="<%=handler %>" %>
What about <jsp:include page="${handler}"/>?

How to get Uuid from User

I am trying to get the UUID from a user.
So far i tried
Accessing the user from a liferay portlet?
Get the current user Liferay using a simple Java code
putting String userId = renderRequest.getRemoteUser() into the view.jsp worked to get the intern ID.
However i wanted the UUID instead.
If i use the code from the links above (into the java-class doView) i only get a null-user object.
Using getUserUuid() and getUuid() returns null.
Here is my class:
ThemeDisplay td =(ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
User user = td.getUser();
String userId = user.getUuid();
renderRequest.setAttribute("myUser", userId);
and my view.jsp
<%
String userId = (String) renderRequest.getAttribute("myUser");
%>
<%= userId %>
Any help is appreciated.
On JSP, extract your parameter from implicit request object. Like:
<%
String userId = (String) request.getAttribute("myUser");
%>

Set Content-Type to application/json in jsp file

I am created some jsp file that returns as a response some json string. But I see that the Content-Type is set to txt automatically
My jsp code looks like
<%# page import="java.util.Random" %>
<%# page language="java" %>
<%# page session="false" %>
<%
String retVal = "// some json string";
int millis = new Random().nextInt(1000);
// System.out.println("sleeping for " + millis + " millis");
Thread.sleep(millis);
%>
<%=retVal%>
How can I perform something like
setHeader("Content-Type", "application/json");
in this example?
You can do via Page directive.
For example:
<%# page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8"%>
contentType="mimeType [ ;charset=characterSet ]" |
"text/html;charset=ISO-8859-1"
The MIME type and character encoding the JSP file uses for the
response it sends to the client. You can use any MIME type or
character set that are valid for the JSP container. The default MIME
type is text/html, and the default character set is ISO-8859-1.
Try this piece of code, it should work too
<%
//response.setContentType("Content-Type", "application/json"); // this will fail compilation
response.setContentType("application/json"); //fixed
%>
#Petr Mensik & kensen john
Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:
<%
String callback = request.getParameter("callback");
response.setCharacterEncoding("UTF-8");
if (callback != null) {
// Equivalent to: <#page contentType="text/javascript" pageEncoding="UTF-8">
response.setContentType("text/javascript");
} else {
// Equivalent to: <#page contentType="application/json" pageEncoding="UTF-8">
response.setContentType("application/json");
}
[...]
String output = "";
if (callback != null) {
output += callback + "(";
}
output += jsonObj.toString();
if (callback != null) {
output += ");";
}
%>
<%=output %>
When callback is supplied, returns:
callback({...JSON stuff...});
with content-type "text/javascript"
When callback is NOT supplied, returns:
{...JSON stuff...}
with content-type "application/json"

How to reload a JSP with request.getAttribute values

I have this application where i want to populate a text file on the basis of entries entered from user interface.
I chose Struts1 for this and i have been able to complete most of the functionalities.But the part of keeping on populating the
text file on the basis of user entries in my JSP is something i am struggling with. The following are the flow of pages on user interface
1.'Accept user entries' http://www.image-share.com/ijpg-1178-104.html
2.'Ask for scan data on the basis of entries in page1' http://www.image-share.com/ijpg-1178-105.html
3.'Submit after entering the scandata. ' http://www.image-share.com/ijpg-1178-106.html
(I have been able to straighten the null values in the images via session variables. Thanks to Dave)
message is seen with null entries like this Post validation.
My questions is:
What should be used so that there is a scenario that the users enter the Scan Data on page 2 and can continue to enter
more scan data values by falling back on the same JSP . I was thinking on the lines of reloading the page using JavaScript
on the button click. Is it the right approach?
The relevant code for this is
<html:form action="txtwriter">
<% String itemname = (String)session.getAttribute("itemname"); %>
<% String lotnumber = (String)session.getAttribute("lotnumber"); %>
<% String godownname = (String)session.getAttribute("godownname"); %>
<br/>
<% String message = (String)session.getAttribute("message");
session.setAttribute( "theFileName", message ); %>
Filename : <%= message %>
<br/> Item Name :<%= itemname %>
<br/> Lot Number :<%= lotnumber %>
<br/> Godown Name :<%= godownname %>
<br/> <bean:message key="label.scandata"/>
<html:text property="scanData" ></html:text>
<html:errors property="scanData"/>
<br/>
<html:submit/>
/* How should the submit button handle the onClick event so that when the users click
after entering the text.
1. The entered text must be populated in the text file using a different action class. (I have this part working)
2.They must be on the same jsp with the scanData text box cleared waiting for the next user entry into that text
box so that this subsequest entry can also be entered into the text file.
Is there a way i can empty the 'scanData' textbox by accessing it by name inside my action so that i can empty it from my action class?
(I am looking for this answer)
*/
I used this inside the LoginAction.java
HttpSession session = request.getSession();
session.setAttribute("message", textFile);
session.setAttribute("itemname",loginForm.getItemName().trim());
session.setAttribute("lotnumber",loginForm.getLotNumber().trim());
session.setAttribute("godownname",loginForm.getStockGodown().trim());
(Not an answer; refactored but untested code for others trying to help.)
This is a refactored action, making it easier to see what's actually going on; the original code is difficult to reason about. The trim() functionality is moved to action form setters to avoid redundancy.
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
if (invalidForm(loginForm)) {
return mapping.findForward("failure");
}
String fileName = createFile(loginForm);
request.setAttribute("message", fileName);
request.setAttribute("itemname", loginForm.getItemName());
request.setAttribute("lotnumber", loginForm.getLotNumber());
request.setAttribute("godownname", loginForm.getStockGodown());
return mapping.findForward("success");
}
private String createFile(LoginForm loginForm) throws IOException {
ServletContext context = getServlet().getServletContext();
String driveName = context.getInitParameter("drive").trim();
String folderName = context.getInitParameter("foldername").trim();
String pathName = driveName + ":/" + folderName;
new File(pathName).mkdirs();
String fileNamePath = pathName + createFileName(loginForm);
ensureFileExists(fileNamePath);
return fileNamePath;
}
private void ensureFileExists(String fileNamePath) throws IOException {
boolean fileExists = new File(fileNamePath).exists();
if (!fileExists) {
File file = new File(fileNamePath);
file.createNewFile();
}
}
private boolean invalidForm(LoginForm loginForm) {
return loginForm.getItemName().equals("")
|| loginForm.getLotNumber().equals("")
|| loginForm.getStockGodown().equals("");
}
private String createFileName(LoginForm loginForm) {
return loginForm.getItemName() + "_"
+ loginForm.getLotNumber() + "_"
+ loginForm.getStockGodown() + "_"
+ createFileNameTimeStamp() + ".txt";
}
private String createFileNameTimeStamp() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' hh.mm.ss z");
String dateTime = sdf.format(Calendar.getInstance().getTime());
String[] tempDateStore = dateTime.split("AD at");
return tempDateStore[0].trim() + "_" + tempDateStore[1].trim();
}
}

How do I send data from Struts action to javascript?

I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.
This is the list I'm trying to send/access:
List<MarkerClass> markers;
MarkerClass is defined acoprding to belove:
final class MarkerClass
{
public Integer objectId;
public String street;
public String streetNumber;
public String zip;
public String city;
public Integer statusId;
public Float lattitude;
public Float longitude;
}
The action also includes a getter for markers:
public List<MarkerClass> getMarkers()
{
return markers;
}
In my jsp-file I have tried doing this:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function initialize()
{
var titel = "";
for(var i, "${markers}")
{
titel = titel+ "${markers[i].street}";
}
}
The browser substitutes "${markers}" with "[se.fubar.test.MarkerClass#37a4, se.fubar.test.MarkerClass#9ad97c]"
I'm guessing there is a better and smarter way to do this but since I'm a bit new to Struts and is trying to code while under the influence of a migrane the answer elludes me.
You cannot just use a struts variable in a javascript function and expect it to work. Remember that the ${...} stuff gets processed before the HTML for the page is sent to the browser. By the time the javascript is rendered at the browser, you are only left with the textual representations. What you will need to do is something like (check the syntax, I haven't used this stuff i a while):
function initialize() {
var title = "";
<c:foreach var="marker" list="${markers}">
title = title + "${marker.street}";
</c:foreach>
}
Something along those lines anyway... Basically the Javascript seen by your browser will look like
function initialize() {
var title = "";
title = title + "Street1";
title = title + "Street2";
title = title + "Street3";
title = title + "Street4";
}
I hope that makes sense and is related to what you were asking.
By the way, there are usually better ways of accomplishing this functionality that building dynamic js etc. Probably there are built in Struts 2 components that you can use?
you would have to set that variable in request or in session and then access it using a <c:out jsp tag like so
var myVar= '<c:out value="${requestScope.myVar}"/>';
then use the var inside your js.
In case you set an object in request or session you have to use the get method to access the value of an attribute then use it like so:
var myVar= '<c:out value="${requestScope.myObj.attribute}"/>';
(assuming you getter method is getAttribute)
it is not possible to access data in session or request directly from js
hope this helps
You could convert the object to json on the server (see http://www.json.org/java/index.html ) and then call eval() on the string to get a javascript representation of your object.
you can try accessing it something like this.
but you have to use a loop to fetch each object from the list place it on the value stack and than fetch each object of it.else you can ask ognl to do it for you.something like
<script type="text/javascript">
function initialize()
{
var titel = "";
for(var i, "${markers}")
{
titel = titel+ <s:property value="%{markers.get(i).street}">;
}
}
just try it since OGNL has capacity to access the object on the value stack

Categories

Resources