package be.redtree.initialize;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import be.redtree.xstream.CustomProperties;
import be.redtree.xstream.DynamicContent;
import be.redtree.xstream.DynamicElement;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.CompanyThreadLocal;
import com.liferay.portal.service.CompanyLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portlet.documentlibrary.service.DLFolderLocalServiceUtil;
import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
import com.liferay.portlet.dynamicdatamapping.service.DDMStructureLocalServiceUtil;
import com.liferay.portlet.dynamicdatamapping.service.DDMTemplateLocalServiceUtil;
import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class DefaultValuesBuilder implements ServletContextListener {
private static Log sLog = LogFactory.getLog(DefaultValuesBuilder.class);
public static String FOLDER_DOWNLOAD = "Webform CSV Export";
private static String TYPE_MAIL_TEMPLATE = "forms-mail-template";
public static String MAIL_ADMIN_TITLE = "forms-mail-admin-template";
public static String MAIL_USER_TITLE = "forms-mail-user-template";
public String[] webcontents = new String[] { MAIL_ADMIN_TITLE, MAIL_USER_TITLE };
public void contextInitialized(ServletContextEvent sce) {
sLog.info("checking default values for the web-forms portlet");
List<Company> companies = new ArrayList<Company>();
try {
companies = CompanyLocalServiceUtil.getCompanies();
} catch (SystemException e) {
e.printStackTrace();
}
InputStream is = getClass().getClassLoader().getResourceAsStream("mail.xml");
String content = null;
try {
content = IOUtils.toString(is);
} catch (IOException e) {
e.printStackTrace();
}
for (Company company : companies) {
if (company.isActive()) {
try {
CompanyThreadLocal.setCompanyId(company.getCompanyId());
sLog.info("checking default values for the web-forms portlet : " + company.getWebId());
Long groupId = company.getGroup().getGroupId();
User user = company.getDefaultUser();
DDMStructure ddmStructure = getStructure(groupId, user);
DDMTemplate ddmTemplate = verifyTemplate(groupId, user, ddmStructure);
String ddmStructureKey = ddmStructure.getStructureKey();
String ddmTemplateKey = ddmTemplate.getTemplateKey();
try {
for (String title : webcontents) {
try {
JournalArticleLocalServiceUtil.getArticleByUrlTitle(groupId, title);
} catch (Exception e) {
createTemplate(company, title, content, ddmStructureKey, ddmTemplateKey);
}
}
ServiceContext serviceContext = new ServiceContext();
boolean mountPoint = false;
try {
DLFolderLocalServiceUtil.getFolder(groupId, new Long(0), FOLDER_DOWNLOAD);
} catch (Exception e) {
long parentFolderId = new Long(0);
String name = FOLDER_DOWNLOAD;
String description = "";
long repositoryId = groupId;
boolean hidden = false;
DLFolderLocalServiceUtil.addFolder(user.getUserId(), groupId, repositoryId, mountPoint, parentFolderId, name, description, hidden, serviceContext);
}
} catch (PortalException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
sLog.info("Successfully checked default values for the web-forms portlet");
}
public void createTemplate(Company company, String title, String content, String ddmStructureKey, String ddmTemplateKey) throws PortalException, SystemException, IOException {
Long globalId = company.getGroup().getGroupId();
User user = company.getDefaultUser();
XStream xstream = new XStream(new StaxDriver());
xstream.autodetectAnnotations(true);
xstream.alias("dynamic-content", DynamicContent.class);
xstream.alias("dynamic-element", DynamicElement.class);
xstream.alias("root", CustomProperties.class);
CustomProperties customProperties = new CustomProperties();
List<DynamicElement> dynamicElements = new ArrayList<DynamicElement>();
DynamicElement elementContent = new DynamicElement();
elementContent.setName("HTMLContent");
elementContent.setDynamicContent(new DynamicContent(content));
dynamicElements.add(elementContent);
customProperties.setDynamicElements(dynamicElements);
content = xstream.toXML(customProperties);
long userId = user.getUserId();
long groupId = globalId;
long classNameId = new Long(0);
long classPK = new Long(0);
String articleId = "";
boolean autoArticleId = true;
double version = 1.0;
Map<Locale, String> titleMap = new HashMap<Locale, String>();
titleMap.put(LocaleUtil.getDefault(), title);
Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
String type = "general";
String layoutUuid = "";
int displayDateMonth = (new DateTime().getMonthOfYear() - 1);
int displayDateDay = new DateTime().getDayOfMonth();
int displayDateYear = new DateTime().getYear();
int displayDateHour = 0;
int displayDateMinute = 0;
int expirationDateMonth = (new DateTime().getMonthOfYear() - 1);
int expirationDateDay = new DateTime().getDayOfMonth();
int expirationDateYear = new DateTime().plusYears(100).getYear();
int expirationDateHour = 0;
int expirationDateMinute = 0;
boolean neverExpire = true;
int reviewDateMonth = new DateTime().getMonthOfYear();
int reviewDateDay = new DateTime().getDayOfMonth();
int reviewDateYear = new DateTime().plusYears(100).getYear();
int reviewDateHour = 0;
int reviewDateMinute = 0;
boolean neverReview = true;
boolean indexable = true;
boolean smallImage = false;
String smallImageURL = "";
File smallImageFile = null;
Map<String, byte[]> images = new HashMap<String, byte[]>();
String articleURL = "";
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(globalId);
long folderId = new Long(0);
JournalArticleLocalServiceUtil.addArticle(userId, groupId, folderId, classNameId, classPK, articleId, autoArticleId, version, titleMap, descriptionMap, content, type, ddmStructureKey, ddmTemplateKey, layoutUuid, displayDateMonth, displayDateDay, displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay, expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour,
reviewDateMinute, neverReview, indexable, smallImage, smallImageURL, smallImageFile, images, articleURL, serviceContext);
}
private DDMTemplate verifyTemplate(Long groupId, User user, DDMStructure ddmStructure) throws SystemException, PortalException {
long classNameId = new Long(10102);
List<DDMTemplate> templates = DDMTemplateLocalServiceUtil.getTemplates(groupId, classNameId);
DDMTemplate ddmTemplate = null;
for (DDMTemplate template : templates) {
String templateKey = template.getTemplateKey().toLowerCase();
if (templateKey.equals(TYPE_MAIL_TEMPLATE.toLowerCase())) {
ddmTemplate = template;
}
}
long userId = user.getUserId();
Map<Locale, String> nameMap = new HashMap<Locale, String>();
nameMap.put(LocaleUtil.getDefault(), TYPE_MAIL_TEMPLATE);
Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
long classPK = ddmStructure.getPrimaryKey();
String type = "display";
String mode = "";
String language = "vm";
String script = "<div></div>";
String templateKey = TYPE_MAIL_TEMPLATE;
boolean cacheable = false;
boolean smallImage = false;
String smallImageURL = "";
File smallImageFile = null;
if (ddmTemplate == null) {
return DDMTemplateLocalServiceUtil.addTemplate(userId, groupId, classNameId, classPK, templateKey, nameMap, descriptionMap, type, mode, language, script, cacheable, smallImage, smallImageURL, smallImageFile, serviceContext);
} else {
return DDMTemplateLocalServiceUtil.updateTemplate(ddmTemplate.getTemplateId(), classPK, nameMap, descriptionMap, type, mode, language, script, cacheable, smallImage, smallImageURL, smallImageFile, serviceContext);
}
}
private DDMStructure getStructure(Long globalId, User user) throws SystemException, PortalException {
List<DDMStructure> structures = DDMStructureLocalServiceUtil.getStructures(globalId);
DDMStructure ddmStructure = null;
for (DDMStructure structure : structures) {
if (structure.getStructureKey().toLowerCase().equals(TYPE_MAIL_TEMPLATE.toLowerCase())) {
ddmStructure = structure;
}
}
long userId = user.getUserId();
long groupId = globalId;
Map<Locale, String> nameMap = new HashMap<Locale, String>();
nameMap.put(LocaleUtil.getDefault(), TYPE_MAIL_TEMPLATE);
Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
StringBuilder xsd = new StringBuilder();
xsd.append("<root available-locales=\"" + LocaleUtil.getDefault() + "\" default-locale=\"" + LocaleUtil.getDefault() + "\">");
// Subject
xsd.append("<dynamic-element dataType=\"string\" indexType=\"keyword\" name=\"TextContent\" readOnly=\"false\" repeatable=\"false\" required=\"false\" showLabel=\"true\" type=\"text\" width=\"small\">");
xsd.append("<meta-data locale=\"" + LocaleUtil.getDefault() + "\">");
xsd.append("<entry name=\"label\"><![CDATA[Subject]]></entry>");
xsd.append("<entry name=\"predefinedValue\"><![CDATA[]]></entry>");
xsd.append("<entry name=\"tip\"><![CDATA[]]></entry>");
xsd.append("</meta-data>");
xsd.append("</dynamic-element>");
// Content
xsd.append("<dynamic-element dataType=\"html\" fieldNamespace=\"ddm\" indexType=\"keyword\" name=\"HTMLContent\" readOnly=\"false\" repeatable=\"false\" required=\"false\" showLabel=\"true\" type=\"ddm-text-html\" width=\"small\">");
xsd.append("<meta-data locale=\"" + LocaleUtil.getDefault() + "\">");
xsd.append("<entry name=\"label\"><![CDATA[Content]]></entry>");
xsd.append("<entry name=\"predefinedValue\"><![CDATA[]]></entry>");
xsd.append("<entry name=\"tip\"><![CDATA[]]></entry>");
xsd.append("</meta-data>");
xsd.append("</dynamic-element>");
xsd.append("</root>");
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
long parentStructureId = new Long(0);
long classNameId = new Long(10109);
String structureKey = TYPE_MAIL_TEMPLATE;
String storageType = "xml";
int type = 0;
String content = xsd.toString();
if (ddmStructure == null) {
return DDMStructureLocalServiceUtil.addStructure(userId, groupId, parentStructureId, classNameId, structureKey, nameMap, descriptionMap, content, storageType, type, serviceContext);
} else {
return DDMStructureLocalServiceUtil.updateStructure(groupId, parentStructureId, classNameId, structureKey, nameMap, descriptionMap, content, serviceContext);
}
}
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}