Back

Import Content (ContentletAPI Example)

Description

From Chris Falzone - an example of importing content in dotCMS (1.7) using the ContentletAPI

Code

package com.cfalzone.jobs;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
import com.dotmarketing.business.APILocator;
import com.dotmarketing.cache.FieldsCache;
import com.dotmarketing.cache.StructureCache;
import com.dotmarketing.cms.factories.PublicUserFactory;
import com.dotmarketing.portlets.contentlet.business.ContentletAPI;
import com.dotmarketing.portlets.contentlet.model.Contentlet;
import com.dotmarketing.portlets.languagesmanager.business.LanguageAPI;
import com.dotmarketing.portlets.structure.model.Field;
import com.dotmarketing.portlets.structure.model.Structure;
import com.dotmarketing.util.Logger;
 
public class SimpleContentCreator implements Job {
 
	@SuppressWarnings("unchecked")
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		Logger.info(this, "SimpleContentCreator Starting up");
 
		/* Get the importStructure */
		Structure importStructure = StructureCache.getStructureByType('Import Structure');
		if (importStructure == null || importStructure.getName() == null) {
			Logger.error(this, "Could not find the Import Structure: " + importStructureStr);
			exit;
		}
 
		/* Get the Fields */
		Field myField = null;
		Field anotherField = null;
		List fields = FieldsCache.getFieldsByStructureInode(importStructure.getInode());
		for (Field f : fields) {
			if (f.getVelocityVarName().equals('myField')) {
				myField = f;
			}
			if (f.getVelocityVarName().equals('anotherField')) {
				anotherField = f;
			}
		}
		if (myField == null) {
			Logger.error(this, "myField not found in " + importStructure.getName());
			exit;
		}
		if (anotherField == null) {
			Logger.error(this, "anotherField not found in " + importStructure.getName());
			exit;
		}
 
		/* Create A New Contentlet */
		Contentlet con2 = new Contentlet();
		con2.setStructureInode(importStructure.getInode());
 
		LanguageAPI lAPI = APILocator.getLanguageAPI();
		con2.setArchived(false);
		con2.setWorking(true);
		con2.setLive(autoPub);
		con2.setLanguageId(lAPI.getDefaultLanguage().getId());
		conAPI.setContentletProperty(con2, myField, 'A Value');
		conAPI.setContentletProperty(con2, anotherField, 'Another Value');
 
		/* Now check the contentlet back in */
		try {
			conAPI.checkin(con2, PublicUserFactory.getSystemUser(), true);
		} catch (Exception e) {
			Logger.error(this, "Unable checkin the Contentlet. " + e.getMessage(), e);
			exit;
		}
 
		Logger.info(this, "SimpleContentCreator Finished");
		return;
	}
}