Checking in content and relating it to a File as Content using dotCMS Content API

Description

This code sample shows how to check-in content using Files as Content and a File field. The code allows to:

1) Check in a FileAsset (Files as Content)
2) Check in a piece of content
3) Associate that FileAsset with the piece of content using a "File" field.

Code

package com.dotcms;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.PermissionAPI;
import com.dotmarketing.cache.FieldsCache;
import com.dotmarketing.factories.InodeFactory;
import com.dotmarketing.portlets.contentlet.business.ContentletAPI;
import com.dotmarketing.portlets.contentlet.model.Contentlet;
import com.dotmarketing.portlets.structure.business.FieldAPI;
import com.dotmarketing.portlets.structure.factories.RelationshipFactory;
import com.dotmarketing.portlets.structure.model.ContentletRelationships;
import com.dotmarketing.portlets.structure.model.ContentletRelationships.ContentletRelationshipRecords;
import com.dotmarketing.portlets.structure.model.Field;
import com.dotmarketing.portlets.structure.model.Relationship;
import com.dotmarketing.portlets.structure.model.Structure;
import com.dotmarketing.util.InodeUtils;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import com.liferay.portal.model.User;

public class ContentExampleServlet extends HttpServlet implements Servlet {


	ContentletAPI conAPI = APILocator.getContentletAPI();

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;


	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();

		User user = null;
		try {
			if (session != null){
				user = (com.liferay.portal.model.User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);
			}
		} catch (Exception nsue) {
			Logger.warn(this, "Exception trying to getUser: " + nsue.getMessage(), nsue);
		}

		try {


			// CHECK IN FILE ASSET
			Contentlet fileAsContent = new Contentlet();

			String selectedStructure = "33888b6f-7a8e-4069-b1b6-5c1aa9d0a48d"; // File Structure
			String folderInode = "1049e7fe-1553-4731-bdf9-ba069f1dc08b"; // some folder inode
			String languageId = "1";

			Structure st = (Structure) InodeFactory.getInode(selectedStructure, Structure.class);
			fileAsContent.setStructureInode(st.getInode());
			ContentletAPI contentletService = APILocator.getContentletAPI();
			ContentletRelationships cRelationships = contentletService.getAllRelationships(fileAsContent);
			fileAsContent.setHost(APILocator.getHostAPI().findSystemHost(user, false).getIdentifier());
			fileAsContent.setFolder(APILocator.getFolderAPI().find(folderInode, user, false).getIdentifier());
			fileAsContent.setLanguageId(Long.parseLong(languageId));



			HashMap<String, Object> contentletFormData = new java.util.HashMap<String, Object>();
			contentletFormData.put("text1", "1049e7fe-1553-4731-bdf9-ba069f1dc08b"); //  host or folder
			contentletFormData.put("binary1", "C:\\Users\\Whiz\\dotCMS\\tomcat\\webapps\\..\\.." +
					"\\dotCMS\\WEB-INF\\binary\\dotcms.org.1\\binary1\\48608ab6-1033-49db-a9cf-ff66fb91966b" +
					"\\b6472d83864f7db2d7fdd7e148b05e3f.jpg"); //  file asset

			contentletFormData.put("text2", "b6472d83864f7db2d7fdd7e148b05e3f.jpg"); // title
			contentletFormData.put("text3", "b6472d83864f7db2d7fdd7e148b05e3f.jpg"); // file name
			contentletFormData.put("integer1", "0"); // sort order

			setFieldValues(fileAsContent, contentletFormData);

			fileAsContent.setReviewInterval(null);

			ContentletRelationships contRel = retrieveRelationshipsData(fileAsContent,user, contentletFormData );

			// http://jira.dotmarketing.net/browse/DOTCMS-65
			// Coming from other contentlet to relate it automatically
			String relateWith = null;
			if(UtilMethods.isSet(contentletFormData.get("relwith")))
				relateWith = (String) contentletFormData.get("relwith");

			String relationType = null;
			if(UtilMethods.isSet(contentletFormData.get("reltype")))
				relationType = (String) contentletFormData.get("reltype");

			String relationHasParent = null;
			relationHasParent = (String) contentletFormData.get("relisparent");
			if(relateWith != null){
				try {

					List<ContentletRelationshipRecords> recordsList = contRel.getRelationshipsRecords();
					for(ContentletRelationshipRecords records : recordsList) {
						if(!records.getRelationship().getRelationTypeValue().equals(relationType))
							continue;
						if(RelationshipFactory.isSameStructureRelationship(records.getRelationship()) &&
								((!records.isHasParent() && relationHasParent.equals("no")) ||
								 (records.isHasParent() && relationHasParent.equals("yes"))))
							continue;
						records.getRecords().add(conAPI.find(relateWith, user, false));

					}


				} catch (Exception e) {
					Logger.error(this,"Contentlet failed while creating new relationship",e);
				}
			}

			PermissionAPI perAPI = APILocator.getPermissionAPI();
			List cats = new ArrayList();
			fileAsContent.setInode(null);
			fileAsContent = conAPI.checkin(fileAsContent, contRel,cats, perAPI.getPermissions(fileAsContent, false, true), user, false);


			// END CHECK IN FILE ASSET


			// CHECK IN CONTENT WITH FILE ASSET

			Contentlet contentlet = new Contentlet();
			selectedStructure = "2a3e91e4-fbbf-4876-8c5b-2233c1739b05";  // Content (Generic)
			st = (Structure) InodeFactory.getInode(selectedStructure, Structure.class);
			contentletService = APILocator.getContentletAPI();
			cRelationships = contentletService.getAllRelationships(contentlet);
			contentlet.setHost(APILocator.getHostAPI().findSystemHost(user, false).getIdentifier());
			contentlet.setLanguageId(Long.parseLong(languageId));

			contentletFormData = new java.util.HashMap<String, Object>();
			contentletFormData.put("text1", "My Content"); // Title
			contentletFormData.put("system_field1", "48190c8c-42c4-46af-8d1a-0cd5db894797"); // Host
			contentletFormData.put("text_area1", "<p>My Body</p>"); // Body
			contentletFormData.put("text2", "7755d7b1-bc56-4326-822a-e9d7da5c0dc6"); //  My File , Identifier of the FileAsset

			setFieldValues(fileAsContent, contentletFormData);

			fileAsContent.setReviewInterval(null);

			contRel = retrieveRelationshipsData(fileAsContent,user, contentletFormData );

			// http://jira.dotmarketing.net/browse/DOTCMS-65
			// Coming from other contentlet to relate it automatically
			relateWith = null;
			if(UtilMethods.isSet(contentletFormData.get("relwith")))
				relateWith = (String) contentletFormData.get("relwith");

			relationType = null;
			if(UtilMethods.isSet(contentletFormData.get("reltype")))
				relationType = (String) contentletFormData.get("reltype");

			relationHasParent = null;
			relationHasParent = (String) contentletFormData.get("relisparent");
			if(relateWith != null){
				try {

					List<ContentletRelationshipRecords> recordsList = contRel.getRelationshipsRecords();
					for(ContentletRelationshipRecords records : recordsList) {
						if(!records.getRelationship().getRelationTypeValue().equals(relationType))
							continue;
						if(RelationshipFactory.isSameStructureRelationship(records.getRelationship()) &&
								((!records.isHasParent() && relationHasParent.equals("no")) ||
								 (records.isHasParent() && relationHasParent.equals("yes"))))
							continue;
						records.getRecords().add(conAPI.find(relateWith, user, false));

					}


				} catch (Exception e) {
					Logger.error(this,"Contentlet failed while creating new relationship",e);
				}
			}

			fileAsContent.setInode(null);
			fileAsContent = conAPI.checkin(fileAsContent, contRel,cats, perAPI.getPermissions(fileAsContent, false, true), user, false);


			// END CHECKIN CONTENT WITH FILE ASSET




		} catch(Exception e) {
			Logger.debug(this, e.getMessage());
		}


	}


	private void setFieldValues(Contentlet c, HashMap<String, Object> contentletFormData) {
		FieldAPI fAPI = APILocator.getFieldAPI();
		ContentletAPI conAPI = APILocator.getContentletAPI();
		List<Field> fields = FieldsCache.getFieldsByStructureInode(c.getStructureInode());
		for (Field field : fields){
			if(fAPI.isElementConstant(field)){
				continue;
			}
			Object value = contentletFormData.get(field.getFieldContentlet());
			String typeField = field.getFieldType();

			//http://jira.dotmarketing.net/browse/DOTCMS-5334
			if(field.getFieldType().equals(Field.FieldType.CHECKBOX.toString())){
				if(field.getFieldContentlet().startsWith("float")
						|| field.getFieldContentlet().startsWith("integer")){

					if(UtilMethods.isSet((String)value)){
						value = String.valueOf(value);
						if(((String)value).endsWith(",")){
							value = ((String)value).substring(0, ((String)value).lastIndexOf(","));
						}
					}else{
						value = "0";
					}

				}
			}

			/* Validate if the field is read only, if so then check to see if it's a new contentlet
			 * and set the structure field default value, otherwise do not set the new value.
			 */
			if (!typeField.equals(Field.FieldType.HIDDEN.toString()) &&
					!typeField.equals(Field.FieldType.IMAGE.toString()) &&
					!typeField.equals(Field.FieldType.FILE.toString()))
			{
				if(field.isReadOnly() && !InodeUtils.isSet(c.getInode()))
					value = field.getDefaultValue();
				if (field.getFieldType().equals(Field.FieldType.WYSIWYG.toString())) {
					//WYSIWYG workaround because the WYSIWYG includes a <br> even if the field was left blank by the user
					//we have to check the value to leave it blank in that case.
					if (value instanceof String && ((String)value).trim().toLowerCase().equals("<br>")) {
						value = "";
					}
				}
			}
			if ((value != null || field.getFieldType().equals(Field.FieldType.BINARY.toString())) && APILocator.getFieldAPI().valueSettable(field) && !field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString()))
				try{
					conAPI.setContentletProperty(c, field, value);
				}catch (Exception e) {
					Logger.info(this, "Unable to set field " + field.getFieldName() + " to value " + value);
					Logger.debug(this, "Unable to set field " + field.getFieldName() + " to value " + value, e);
				}
		}
	}



	private ContentletRelationships retrieveRelationshipsData(Contentlet currentContentlet, User user, Map<String, Object> contentletFormData ){

		Set<String> keys = contentletFormData.keySet();

		ContentletRelationships relationshipsData = new ContentletRelationships(currentContentlet);
		List<ContentletRelationshipRecords> relationshipsRecords = new ArrayList<ContentletRelationshipRecords> ();
		relationshipsData.setRelationshipsRecords(relationshipsRecords);

		for (String key : keys) {
			if (key.startsWith("rel_") && key.endsWith("_inodes")) {
				boolean hasParent = key.contains("_P_");
				String inodesSt = (String) contentletFormData.get(key);
				if(!UtilMethods.isSet(inodesSt)){
					continue;
				}
				String[] inodes = inodesSt.split(",");

				Relationship relationship = (Relationship) InodeFactory.getInode(inodes[0], Relationship.class);
				ContentletRelationshipRecords records = relationshipsData.new ContentletRelationshipRecords(relationship, hasParent);
				ArrayList<Contentlet> cons = new ArrayList<Contentlet>();
				for (String inode : inodes) {
					/*long i = 0;
					try{
						i = Long.valueOf(inode);
					}catch (Exception e) {
						Logger.error(this, "Relationship not a number value : ",e);
					}*/
					if(relationship.getInode().equalsIgnoreCase(inode)){
						continue;
					}
					try{
						cons.add(conAPI.find(inode, user, false));
					}catch(Exception e){
						Logger.debug(this,"Couldn't look up contentlet.  Assuming inode" + inode + "is not content");
					}
				}
				records.setRecords(cons);
				relationshipsRecords.add(records);
			}
		}
		return relationshipsData;
	}





}