Created
July 22, 2014 14:32
-
-
Save cfalzone/bf0eb65651335d758513 to your computer and use it in GitHub Desktop.
Saving Content and Pushing to an environment in dotCMS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author cfalzone | |
* | |
* This class handles the forms for the agent tool | |
*/ | |
package com.aquent.agenttool; | |
import java.io.File; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Set; | |
import javax.servlet.ServletConfig; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import javax.servlet.http.HttpSession; | |
import org.apache.commons.fileupload.FileItem; | |
import org.apache.commons.fileupload.disk.DiskFileItemFactory; | |
import org.apache.commons.fileupload.servlet.ServletFileUpload; | |
import org.apache.commons.lang.StringUtils; | |
import com.aquent.AquentUtil; | |
import com.dotcms.publisher.bundle.bean.Bundle; | |
import com.dotcms.publisher.bundle.business.BundleAPI; | |
import com.dotcms.publisher.business.PublisherAPI; | |
import com.dotcms.publisher.environment.bean.Environment; | |
import com.dotcms.publisher.environment.business.EnvironmentAPI; | |
import com.dotmarketing.beans.Permission; | |
import com.dotmarketing.business.APILocator; | |
import com.dotmarketing.business.UserAPI; | |
import com.dotmarketing.business.VersionableAPI; | |
import com.dotmarketing.cache.FieldsCache; | |
import com.dotmarketing.portlets.categories.business.CategoryAPI; | |
import com.dotmarketing.portlets.categories.model.Category; | |
import com.dotmarketing.portlets.contentlet.business.ContentletAPI; | |
import com.dotmarketing.portlets.contentlet.model.Contentlet; | |
import com.dotmarketing.portlets.structure.model.Field; | |
import com.dotmarketing.util.Logger; | |
import com.dotmarketing.util.UtilMethods; | |
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; | |
import com.google.gson.Gson; | |
import com.liferay.portal.model.User; | |
public class AgentToolServlet extends javax.servlet.http.HttpServlet { | |
private static final long serialVersionUID = 6268799112023285849L; | |
private static final String STATUS_SUCCESS = "s=success"; | |
private static final String STATUS_FAIL = "s=fail"; | |
private static final String MSG_NO_INIT = "&m=no_init"; | |
private static final String MSG_NO_ACTION = "&m=no_action"; | |
private static final String MSG_INV_ACTION = "&m=inv_action"; | |
private static final String MSG_NO_USER = "&m=no_user"; | |
private static final String MSG_NO_AGENT = "&m=no_agent"; | |
private static final String MSG_NO_BRAND = "&m=no_brand"; | |
private static final String MSG_INV_PT = "&m=inv_pt"; | |
private static final String MSG_PIC_FAIL = "&m=pic_fail"; | |
private static final String MSG_PIC_SIZE = "&m=pic_size"; | |
private static final String MSG_PIC_TYPE = "&m=pic_type"; | |
private static final String MSG_VALIDATION = "&m=validation"; | |
private static final String MSG_CONTENT_CHECKIN = "&m=content_checkin"; | |
private static final String MSG_NO_ENV = "&m=no_env"; | |
private static final String MSG_PUSH_FAIL = "&m=push_fail"; | |
private String success_page = "/home/success.htm?"; | |
private static ArrayList<String> imageTypes = new ArrayList<String>(); | |
static { | |
imageTypes.add("image/gif"); | |
imageTypes.add("image/jpeg"); | |
imageTypes.add("image/tiff"); | |
imageTypes.add("image/png"); | |
} | |
private ContentletAPI conAPI = APILocator.getContentletAPI(); | |
private CategoryAPI catAPI = APILocator.getCategoryAPI(); | |
private UserAPI userAPI = APILocator.getUserAPI(); | |
private VersionableAPI verAPI = APILocator.getVersionableAPI(); | |
private EnvironmentAPI envAPI = APILocator.getEnvironmentAPI(); | |
private BundleAPI bundleAPI = APILocator.getBundleAPI(); | |
private PublisherAPI pubAPI = PublisherAPI.getInstance(); | |
private boolean inited = false; | |
private User sysUser = null; | |
private Field brandField = null; | |
public void init(ServletConfig config) throws ServletException { | |
super.init(config); | |
// Get the system user | |
sysUser = null; | |
try { | |
sysUser = userAPI.getSystemUser(); | |
} catch (Exception e) { | |
Logger.error(this, "Unable to get the System User", e); | |
return; | |
} | |
inited = true; | |
} | |
protected void doGet(HttpServletRequest req, HttpServletResponse resp) | |
throws ServletException, IOException { | |
doPost(req, resp); | |
} | |
protected void doPost(HttpServletRequest req, HttpServletResponse resp) | |
throws ServletException, IOException { | |
Logger.debug(this, "AgentTool doPost"); | |
// Get the referer | |
String referer = getReferer(req); | |
Logger.debug(this, "referrer="+referer); | |
// Get the action | |
String action = UtilMethods.isSet(req.getParameter("a")) ? req.getParameter("a") : ""; | |
if(action == "") { | |
Logger.error(this, "Agent Tool Called but no action was specified"); | |
resp.sendRedirect(referer+STATUS_FAIL+MSG_NO_ACTION); | |
return; | |
} | |
// Check to make sure we are inited | |
if(!inited) { | |
Logger.error(this, "Agent Tool Called but is not inited"); | |
resp.sendRedirect(referer+STATUS_FAIL+MSG_NO_INIT+"&a="+action); | |
return; | |
} | |
// Get the user | |
HttpSession session = req.getSession(); | |
GoogleTokenResponse tokenData = (GoogleTokenResponse) session.getAttribute("gPlusToken"); | |
if(!UtilMethods.isSet(tokenData)) { | |
Logger.error(this, "Agent Tool Called but no user in session"); | |
resp.sendRedirect(referer+STATUS_FAIL+MSG_NO_USER+"&a="+action); | |
return; | |
} | |
String agentEmail = (String) session.getAttribute("gPlusEmail"); | |
Logger.debug(this, "Current User Email="+agentEmail); | |
// Do the Action | |
String status = STATUS_FAIL+MSG_INV_ACTION+"&a="+action; | |
if(action.equalsIgnoreCase("UpdateAgent")) { | |
status = updateAgent(agentEmail, req); | |
} else if(action.equalsIgnoreCase("PushAgent")) { | |
status = pushAgent(agentEmail, req); | |
} else { | |
Logger.error(this, "Agent Tool Called with invalid action="+action); | |
resp.sendRedirect(referer+STATUS_FAIL+MSG_INV_ACTION+"&a="+action); | |
return; | |
} | |
if(status.contains(STATUS_SUCCESS)) resp.sendRedirect(success_page+status+"&a="+action); | |
else resp.sendRedirect(referer+status+"&a="+action); | |
return; | |
} | |
private String pushAgent(String agentEmail, HttpServletRequest req) { | |
// Get the agent | |
Contentlet agent = null; | |
String agentQuery = "+structureName:Agents +Agents.email:"+agentEmail; | |
Logger.debug(this, "Query = "+agentQuery); | |
try { | |
List<Contentlet> conts = conAPI.search(agentQuery, 1, 0, "modDate desc", sysUser, false); | |
if(conts.size() > 0) { | |
agent = conts.get(0); | |
} else { | |
Logger.error(this, "Agent Tool Called but no agent content found for emailAddress="+agentEmail); | |
return STATUS_FAIL+MSG_NO_AGENT; | |
} | |
} catch(Exception e) { | |
Logger.error(this,"Exception searching for agent profile for emailAddress="+agentEmail,e); | |
return STATUS_FAIL+MSG_NO_AGENT; | |
} | |
// Get the Environment | |
Environment env = null; | |
String role = AquentUtil.getInstance().getServerRole(); | |
try { | |
if(role.equals("dev")) { | |
env = envAPI.findEnvironmentByName("Staging"); | |
} else if(role.equals("stag")) { | |
env = envAPI.findEnvironmentByName("Dev + Prod"); | |
} | |
} catch(Exception e) { | |
Logger.error(this,"Exception trying to get push environment for server role: "+role,e); | |
return STATUS_FAIL+MSG_NO_ENV; | |
} | |
if(env == null) { | |
Logger.error(this,"No push environment for server role: "+role); | |
return STATUS_FAIL+MSG_NO_ENV; | |
} | |
List<Environment> envs = new ArrayList<Environment>(); | |
envs.add(env); | |
// Make a list of items to push | |
List<String> ids = new ArrayList<String>(); | |
ids.add(agent.getIdentifier()); | |
// Publish the Content | |
Map<String, Object> responseMap = null; | |
try { | |
Date publishDate = new Date(); | |
Bundle bundle = new Bundle(null, publishDate, null, sysUser.getUserId(), false); | |
bundleAPI.saveBundle(bundle, envs); | |
responseMap = pubAPI.addContentsToPublish( ids, bundle.getId(), publishDate, sysUser ); | |
} catch (Exception e) { | |
Logger.error(this,"Error pushing agent "+agentEmail+" from "+role+" to "+env.getName(),e); | |
return STATUS_FAIL+MSG_PUSH_FAIL; | |
} | |
// Check the response | |
if ( responseMap != null && !responseMap.isEmpty() ) { | |
int errors = (Integer) responseMap.get( "errors" ); | |
int total = (Integer) responseMap.get( "total" ); | |
Logger.debug(this, "Push Reponse is "+responseMap); | |
if(errors == 0 && total == 1) { | |
Logger.info(this, "Agent "+agentEmail+" was pushed from "+role+" to "+env.getName()); | |
return STATUS_SUCCESS; | |
} else { | |
Logger.error(this,"Error pushing agent "+agentEmail+" from "+role+" to "+env.getName()); | |
return STATUS_FAIL+MSG_PUSH_FAIL; | |
} | |
} else { | |
Logger.error(this,"Error pushing agent "+agentEmail+" from "+role+" to "+env.getName()); | |
return STATUS_FAIL+MSG_PUSH_FAIL; | |
} | |
} | |
@SuppressWarnings("unchecked") | |
private String updateAgent(String agentEmail, HttpServletRequest request) { | |
Gson gson = new Gson(); | |
AquentUtil au = AquentUtil.getInstance(); | |
// Get the agent | |
Contentlet agent = null; | |
Contentlet newAgent = null; | |
List<Category> cats = new ArrayList<Category>(); | |
String agentId=""; | |
String agentQuery = "+structureName:Agents +Agents.email:"+agentEmail; | |
Logger.debug(this, "Query = "+agentQuery); | |
try { | |
List<Contentlet> conts = conAPI.search(agentQuery, 1, 0, "modDate desc", sysUser, false); | |
if(conts.size() > 0) { | |
agent = conts.get(0); | |
agentId = agent.getStringProperty("agentId"); | |
// Determine Agent's Brand | |
Category brand = null; | |
try { | |
ArrayList<Category> brands = new ArrayList<Category>((Set<Category>)conAPI.getFieldValue(agent, getBrandField(agent))); | |
if(brands.size() > 0) { | |
Logger.debug(this, "brand = "+brands.get(0)); | |
brand = brands.get(0); | |
} else { | |
Logger.error(this,"Agent "+agentId+" does not have a brand"); | |
return STATUS_FAIL+MSG_NO_BRAND; | |
} | |
} catch (Exception e) { | |
Logger.error(this,"Unable to determine agent "+agentId+"'s Brand",e); | |
return STATUS_FAIL+MSG_NO_BRAND; | |
} | |
// Create a new contentlet and set the brand | |
newAgent = conAPI.checkout(agent.getInode(), sysUser, false); | |
newAgent.setStringProperty("brand", brand.getKey()); | |
cats.add(brand); | |
} else { | |
Logger.error(this, "Agent Tool Called but no agent content found for emailAddress="+agentEmail); | |
return STATUS_FAIL+MSG_NO_AGENT; | |
} | |
} catch(Exception e) { | |
Logger.error(this,"Exception searching for or checking out agent profile for emailAddress="+agentEmail,e); | |
return STATUS_FAIL+MSG_NO_AGENT; | |
} | |
Logger.debug(this, "agentId="+agentId); | |
// Process multipart data | |
Map<String, String> params = new HashMap<String, String>(); | |
Map<String, FileItem> uploads = new HashMap<String, FileItem>(); | |
List<String> missingFields = new ArrayList<String>(); | |
StringBuilder paramsBuff = new StringBuilder(); | |
List<String> markets = new ArrayList<String>(); | |
try { | |
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); | |
for(FileItem item : items) { | |
if(item.isFormField()) { | |
Logger.info(this, "param found: "+item.getFieldName()+"="+item.getString()); | |
if(item.getFieldName().equals("market")) markets.add(item.getString()); | |
if(item.getFieldName().equals("success_page")) | |
success_page = item.getString().contains("?") ? item.getString()+"&" : item.getString()+"?"; | |
else params.put(item.getFieldName(), au.cleanForXML(item.getString())); | |
paramsBuff.append("&"+item.getFieldName()+"="+item.getString()); | |
} else { | |
Logger.info(this, "file found: param="+item.getFieldName()+" filename="+item.getName()); | |
if(UtilMethods.isSet(item.getName()) && item.getSize() > 0) uploads.put(item.getFieldName(), item); | |
} | |
} | |
} catch (Exception e) { | |
Logger.error(this, "Exception parsing request", e); | |
} | |
// ** First Name - Required ** | |
if(UtilMethods.isSet(params.get("first_name"))) { | |
String val = params.get("first_name"); | |
Logger.debug(this, "first_name="+val); | |
if(UtilMethods.isSet(val)) newAgent.setStringProperty("firstName", val); | |
else missingFields.add("first_name"); | |
} else { | |
missingFields.add("first_name"); | |
} | |
// ** Last Name - Required ** | |
if(UtilMethods.isSet(params.get("last_name"))) { | |
String val = params.get("last_name"); | |
Logger.debug(this, "last_name="+val); | |
if(UtilMethods.isSet(val)) newAgent.setStringProperty("lastName", val); | |
else missingFields.add("last_name"); | |
} else { | |
missingFields.add("last_name"); | |
} | |
// ** About Me - Required ** | |
if(UtilMethods.isSet(params.get("about_me"))) { | |
String val = params.get("about_me"); | |
Logger.debug(this, "about_me="+val); | |
if(UtilMethods.isSet(val)) newAgent.setStringProperty("aboutMe", val); | |
else missingFields.add("about_me"); | |
} else { | |
missingFields.add("about_me"); | |
} | |
// ** Title or Focus ** | |
String titleOrFocus = UtilMethods.isSet(params.get("title_or_focus")) ? params.get("title_or_focus") : ""; | |
Logger.debug(this, "title_or_focus="+titleOrFocus); | |
newAgent.setStringProperty("titleOrFocus", titleOrFocus); | |
// ** Title or Focus ** | |
String salesTitle = UtilMethods.isSet(params.get("salesTitle")) ? params.get("salesTitle") : ""; | |
Logger.debug(this, "salesTitle="+salesTitle); | |
newAgent.setStringProperty("salesTitle", salesTitle); | |
// ** Phone ** | |
String phone = UtilMethods.isSet(params.get("phone")) ? params.get("phone") : ""; | |
Logger.debug(this, "phone="+phone); | |
newAgent.setStringProperty("phone", phone); | |
// ** Cell Phone ** | |
String cellPhone = UtilMethods.isSet(params.get("cellPhone")) ? params.get("cellPhone") : ""; | |
Logger.debug(this, "cellPhone="+cellPhone); | |
newAgent.setStringProperty("cellPhone", cellPhone); | |
// ** Department ** | |
String department = UtilMethods.isSet(params.get("department")) ? params.get("department") : ""; | |
Logger.debug(this, "department="+department); | |
newAgent.setStringProperty("department", department); | |
// ** Keywords ** | |
String keywords = UtilMethods.isSet(params.get("keywords")) ? params.get("keywords") : ""; | |
Logger.debug(this, "keywords="+keywords); | |
newAgent.setStringProperty("keywords", keywords); | |
// ** Location Keywords ** | |
String locationKeywords = UtilMethods.isSet(params.get("location_keywords")) ? params.get("location_keywords") : ""; | |
Logger.debug(this, "locationKeywords="+locationKeywords); | |
newAgent.setStringProperty("locationKeywords", locationKeywords); | |
// ** Agree Conditions ** | |
boolean agreeConditions = Boolean.parseBoolean(params.get("agree_conditions")); | |
Logger.info(this, "agreeConditions="+params.get("agree_conditions")+" and "+agreeConditions); | |
newAgent.setBoolProperty("agreeConditions", agreeConditions); | |
// ** Is Active ** | |
boolean isActive = Boolean.parseBoolean(params.get("is_active")); | |
Logger.info(this, "isActive="+params.get("is_active")+" and "+isActive); | |
newAgent.setBoolProperty("isActive", isActive); | |
// ** Social Media Links ** | |
Map<String, String> socialMap = new HashMap<String, String>(); | |
for(int i=0; i<=5; i++) { | |
if(UtilMethods.isSet(params.get("social_link"+i)) && UtilMethods.isSet(params.get("social_link_label"+i))) { | |
String key = params.get("social_link_label"+i); | |
String val = params.get("social_link"+i); | |
Logger.debug(this, "social"+i+"="+key+":"+val); | |
socialMap.put(key, val); | |
} | |
} | |
newAgent.setProperty("socialMediaLinks", gson.toJson(socialMap)); | |
// ** Office ** | |
String office = UtilMethods.isSet(params.get("affiliate_office")) ? params.get("affiliate_office") : ""; | |
Logger.debug(this, "office="+keywords); | |
newAgent.setStringProperty("office", office); | |
// ** Specialty ** | |
String spec = UtilMethods.isSet(params.get("specialty")) ? params.get("specialty") : ""; | |
Logger.debug(this, "specialty="+keywords); | |
newAgent.setStringProperty("specialty", spec); | |
// ** Industry ** | |
String industry = UtilMethods.isSet(params.get("industry")) ? params.get("industry") : ""; | |
Logger.debug(this, "industry="+keywords); | |
newAgent.setStringProperty("industry", industry); | |
// ** Markets ** | |
String marks = markets.size() > 0 ? StringUtils.join(markets, ",") : ""; | |
Logger.debug(this, "markets="+marks); | |
newAgent.setStringProperty("market", marks); | |
// ** Profile Type ** | |
String profileType = params.get("profile_type"); | |
if(UtilMethods.isSet(profileType)) { | |
try { | |
Category profType = catAPI.findByKey(profileType, sysUser, false); | |
newAgent.setStringProperty("profileType", profType.getKey()); | |
cats.add(profType); | |
} catch (Exception e) { | |
Logger.error(this, "Unable to find matching category for profile type: "+profileType, e); | |
return STATUS_FAIL+MSG_INV_PT+paramsBuff.toString(); | |
} | |
} | |
// ** Testimonials ** | |
Map<String, String> testMap = new HashMap<String, String>(); | |
for(int i=0; i<=3; i++) { | |
if(UtilMethods.isSet(params.get("testimonial_text"+i)) && UtilMethods.isSet(params.get("testimonial_author"+i))) { | |
String key = params.get("testimonial_author"+i); | |
String val = params.get("testimonial_text"+i); | |
Logger.debug(this, "testimonial"+i+"="+key+":"+val); | |
testMap.put(key, val); | |
} | |
} | |
newAgent.setProperty("testimonials", gson.toJson(testMap)); | |
// ** Profile Picture ** | |
FileItem item = uploads.get("profile_picture"); | |
if(item != null) { | |
String fileName = item.getName(); | |
String contentType = item.getContentType(); | |
long size = item.getSize(); | |
Logger.info(this, "Found Profile Picture [name="+fileName+", contentType="+contentType+", size="+size+"]"); | |
// restrict images to 8mb | |
if(size > 8388608) { | |
return STATUS_FAIL+MSG_PIC_SIZE+paramsBuff.toString(); | |
} | |
// restrict image types | |
if(! imageTypes.contains(contentType)) { | |
return STATUS_FAIL+MSG_PIC_TYPE+paramsBuff.toString(); | |
} | |
File uploadedFile = new File("/tmp/"+fileName); | |
try { | |
item.write(uploadedFile); | |
newAgent.setBinary("uploadedPicture", uploadedFile); | |
} catch (Exception e) { | |
Logger.error(this, "Unable to save upload file", e); | |
return STATUS_FAIL+MSG_PIC_FAIL+paramsBuff.toString(); | |
} | |
} | |
// Check for Validation errors | |
String missingFieldsStr = ""; | |
if(missingFields.size() > 0) { | |
missingFieldsStr = "&missing_fields=" + StringUtils.join(missingFields, ','); | |
} | |
if(missingFields.size() > 0) { | |
Logger.info(this, "Updating AgentID="+agentId+" Failed Validation with the following messages: " | |
+missingFieldsStr+" Parameters: "+paramsBuff.toString()); | |
return STATUS_FAIL+MSG_VALIDATION+missingFieldsStr+paramsBuff.toString(); | |
} | |
// Checkin the content | |
try { | |
newAgent = conAPI.checkin(newAgent, cats, new ArrayList<Permission>(), sysUser, false); | |
verAPI.setLive(newAgent); | |
conAPI.unlock(newAgent, sysUser, false); | |
// We need to wait for this to be indexed before redirecting back to the user. | |
conAPI.isInodeIndexed(newAgent.getInode(), 1000); | |
} catch(Exception e) { | |
Logger.error(this, "Agent Contentlet could not be updated for AgentID="+agentId, e); | |
return STATUS_FAIL+MSG_CONTENT_CHECKIN+paramsBuff.toString(); | |
} | |
return STATUS_SUCCESS; | |
} | |
private Field getBrandField(Contentlet agent) throws Exception { | |
if(!UtilMethods.isSet(brandField)) | |
brandField = UtilMethods.convertListToHashMap( | |
FieldsCache.getFieldsByStructureInode(agent.getStructureInode()), | |
"getVelocityVarName",String.class).get("brand"); | |
return brandField; | |
} | |
/** | |
* Retrieves the referer from the request | |
* | |
* @param request The request object | |
* @return The referer all cleaned up and ready to use | |
*/ | |
private String getReferer(HttpServletRequest request) { | |
String referer = UtilMethods.isSet(request.getHeader("referer")) ? request.getHeader("referer") : "/"; | |
if(referer.indexOf('?') > 0) referer = referer.substring(0, referer.indexOf('?')); | |
referer = referer + "?"; | |
return referer; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment