Home > Uncategorized > Create a sitemap with a Custom deployer

Create a sitemap with a Custom deployer

January 25, 2012 Leave a comment Go to comments

This post is about creating a sitemap that will be updated after every page publish. At page publish a custom deployer will be trigered that
will the store page information into a custom table. We can then generate a custom sitemap provider that can be used to create a sitemap or
breadcrumb.

Step1: Create custom table


CREATE TABLE [dbo].[YourCompany_sitemap](
 [pub_id] [int] NOT NULL,
 [page_id] [int] NOT NULL,
 [parentid] [int] NOT NULL,
 [title] [nvarchar](255) NOT NULL,
 [metatitle] [nvarchar](255) NOT NULL,
 [url] [nvarchar](500) NOT NULL,
 [keywords] [varchar](500) NOT NULL,
 [excludefromseositemap] [varchar](500) NOT NULL,
 [showbreadcrumb] [varchar](500) NOT NULL,
 [lastupdated] [datetime] NOT NULL,
 CONSTRAINT [PK_YourCompany_sitemap] PRIMARY KEY CLUSTERED
(
 [pub_id] ASC,
 [page_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[YourCompany_sitemap] ADD CONSTRAINT [DF_YourCompany_sitemap_lastupdated] DEFAULT (getdate()) FOR [lastupdated]
GO

Step2: Create the custom deployer (java)

a) Create java project (Eclipse)
b) Add the following 2 files PageDeployer.java & PageUndeployer.java [see below]
c) Generate Jar file
d) Upload jar file to lib folder (ex: E:\Program Files (x86)\Tridion\lib)
e) Restart deployer windows service

 

Step3 : Modify cd_deployer.config

Change: <Module Type=”PageDeploy” Class=”com.tridion.Deployer.PageDeployer”> to  <Module Type=”PageDeploy” Class=”com.tridion.YourCompany.extensions.PageDeployer”>

Change: <Module Type=”PageUndeploy” Class=”com.tridion.unDeployer.PageDeployer”> to  <Module Type=”PageDeploy” Class=”com.tridion.YourCompany.extensions.PageUnDeployer”>

 

Deployer:

package com.tridion.YourCompany.extensions;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tridion.configuration.Configuration;
import com.tridion.configuration.ConfigurationException;
import com.tridion.deployer.ProcessingException;
import com.tridion.deployer.Processor;
import com.tridion.deployer.modules.PageDeploy;
import com.tridion.transport.transportpackage.Page;

@SuppressWarnings("deprecation")
public class PageDeployer extends PageDeploy {

	//when deploying a new version
	// build this as a jar file
	// copy the jar to YourCompany frontend servers (in tridion lib folder)
	// make sure the deployer_conf.xml is adapted correctly
	// restart the tridion services and the deployer application pool
	// check that publishing works fine 
	
	protected static Logger log = LoggerFactory.getLogger(PageDeployer.class);
	
	public PageDeployer(Configuration config, Processor processor) throws ConfigurationException {
		super(config, processor);
		log.debug("Constructor of PageDeployer");
	}
	
	@Override
	protected void processPage(Page page, File pageFile)
		    throws ProcessingException
	  {
	    try
	    {
	    	log.debug("Starting to process");
	    		  
	    	 String id = "";
			 String pubid = "";
			 String parentid = "";
			 String url = "";
			 String title = "";
			 String roles = "";
			 String order = "";
			 String menutitle = "";
			 String target = "";
	    	 String[] menuzones = new String[0];
	    	
	    		 /*  Sets up a file reader to read the file passed on the command
	    		                line one character at a time */
	    		 FileReader input = new FileReader(pageFile);

	    		 /* Filter FileReader through a Buffered read to read a line at a
	    		            time */
	    		 BufferedReader bufRead = new BufferedReader(input);

	    		 String line;    // String that holds current file line
	    		 // Read first line
	    		 line = bufRead.readLine();
	    		 // Read through file one line at time. Print line # and line
	    		 Boolean inmetasection = false;
	    		 while (line != null){
	    			 
	    			 if(inmetasection)
	    			 {
	    				 if(line.startsWith("id:")) 		id=GetVal(line, "id:");
						 if(line.startsWith("pubid:")) 		pubid=GetVal(line, "pubid:");
						 if(line.startsWith("url:"))		url=GetVal(line, "url:");
						 if(line.startsWith("title:"))		title=GetVal(line, "title:");
						 if(line.startsWith("menutitle:"))	menutitle=GetVal(line, "menutitle:");
						 if(line.startsWith("parentid:"))	parentid=GetVal(line, "parentid:");
						 if(line.startsWith("roles:"))		roles=GetVal(line, "roles:");
						 if(line.startsWith("menuzones:"))	menuzones=GetValArray(line, "menuzones:");
						 if(line.startsWith("order:"))		order=GetVal(line, "order:");
						 if(line.startsWith("target:"))		target=GetVal(line, "target:");
						 
						 
	    			 }
	    			 
	    			 if(line.toLowerCase().startsWith(""))
	    				 inmetasection = true;
	    			 if(line.toLowerCase().startsWith(""))
	    				 inmetasection = false;
	    			 
	    			 
	    			 line = bufRead.readLine();
	    			
	    			 
	    			 /*



#This should contain all sitemap information
id:1
pubid:5
url:/default.aspx
parentid:0
title:homepage
roles:
menuzone:1,2

	    			  */
	    			 
	    		 }

	    		 bufRead.close();
	    		 input.close();
log.debug("id" + id);
log.debug("pubid" + pubid);
log.debug("url" + url);
log.debug("title" + title);
log.debug("parentid" + parentid);
log.debug("roles" + roles);
log.debug("menuzones" + menuzones);
log.debug("order" + order);
log.debug("target" + target);
	    	if(id != "")
	    	{
	    		InsertSQL(id,pubid,parentid,url,title,menutitle,roles, menuzones,order,target);
	    	}
	    	
	     super.processPage(page, pageFile);
	    } catch (ProcessingException e) {
	    	throw new ProcessingException("Could not deploy page - problem processing page " + page, e);
	    } catch (IOException e) {
	    	throw new ProcessingException("Could not deploy page - problem reading page file " + page, e);
		} catch (SQLException e) {
			throw new ProcessingException("Could not deploy page - problem with database " + page, e);
		} catch (Exception e) {
			throw new ProcessingException("Could not deploy page - problem with database " + page, e);
		}
	  }

	private String GetVal(String line, String string) {
		log.debug("getval for line " + line + " on string " + string);
		return line.trim().substring(string.length());
	}
	private String[] GetValArray(String line, String string) {
		return GetVal(line, string).split(",");
	}

	private void InsertSQL(String id, String pubid, String parentid, String url, String title,String menutitle, String roles, String[] menuzones, String order, String target) throws Exception
	{
		String connectionUrl = "jdbc:sqlserver://YourSever\\InstaceName;databaseName=YourCompany_data;user=YourCompanyUser;password=YourCompanyPsw;";
		Connection con = DriverManager.getConnection(connectionUrl);
		
 	    PreparedStatement stmt;
 	   PreparedStatement stmtDel;
 	  con.setAutoCommit(false); 
 	  try{ 
 		  String delete;
 		 delete= "delete from YourCompany_sitemap where pub_id=? and page_id=?";
 		stmtDel = con.prepareStatement(delete);
		stmtDel.setInt(1, Integer.parseInt(pubid.trim()));
		stmtDel.setInt(2, Integer.parseInt(id.trim()));
		stmtDel.executeUpdate();
		stmtDel.close();
	 	  for(int i =0;i&lt;menuzones.length;i++)
	 	    {
				String insert;
				insert = &quot;insert into YourCompany_sitemap(pub_id, page_id, parent_id,url, title, menutitle, roles, menuzone, menuorder, target) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)&quot;;
				stmt = con.prepareStatement(insert);
				stmt.setInt(1, Integer.parseInt(pubid.trim()));
				stmt.setInt(2, Integer.parseInt(id.trim()));
				stmt.setInt(3, Integer.parseInt(parentid.trim()));
				stmt.setString(4, url);
				stmt.setString(5, title);
				stmt.setString(6, menutitle);
				stmt.setString(7, roles);
				stmt.setInt(8, Integer.parseInt(menuzones[i].trim()));
				stmt.setInt(9, Integer.parseInt(order.trim()));
				stmt.setString(10, target.trim());
				stmt.executeUpdate();
				stmt.close();
				
	 	    }
	 	  con.commit();
 	  }
 	  catch(Exception ex)
 	  {
 		 con.rollback();
 		 throw ex;
	 }
		con.close();
		
	}
	

}

Undeployer

package com.tridion.YourCompany.extensions;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tridion.configuration.Configuration;
import com.tridion.configuration.ConfigurationException;
import com.tridion.deployer.ProcessingException;
import com.tridion.deployer.Processor;
import com.tridion.deployer.modules.PageUndeploy;
import com.tridion.transport.transportpackage.PageKey;
import com.tridion.transport.transportpackage.ProcessorInstructions;
import com.tridion.transport.transportpackage.TransportPackage;

@SuppressWarnings("deprecation")
public class PageUndeployer extends PageUndeploy {

	//when deploying a new version
	// build this as a jar file
	// copy the jar to the YourCompany frontend servers (in tridion lib folder)
	// make sure the deployer_conf.xml is adapted correctly
	// restart the tridion services and the deployer application pool
	// check that publishing works fine 
	
	/*settings for deployer and undeployer
	 * 
            
            
            
            
            
            
            
            
            
                <!-- The transformer enables the TCDL Engine -->
                
            
            
            
            
            

            <!-- This module enables deployment of taxonomies -->
            

            
                <!-- The transformer enables the TCDL Engine -->
                
            

            <!-- This module enables deployment of structure groups -->
            
        
        
        
        
        
  	    
  	    
  	    
  	    
            

            <!-- This module enables the undeploy of taxonomies -->
            

            <!-- This module enables the undeploy of structure groups -->
            
        
	 */
	
	protected static Logger log = LoggerFactory.getLogger(PageUndeployer.class);
	
	public PageUndeployer(Configuration config, Processor processor)
			throws ConfigurationException {

			super(config, processor);	
			log.debug("Constructor of PageUndeployer"); 
	}

	@SuppressWarnings({ "rawtypes" })
	public void process(TransportPackage data) throws ProcessingException {
		ProcessorInstructions instructions = data.getProcessorInstructions();

		try {

			Iterator iterator = instructions.getArguments();
			while (iterator.hasNext()) {
				Object argument = iterator.next();
				if ((argument instanceof PageKey)) {
					PageKey key = (PageKey) argument;
					int pubid = key.getId().getPublicationId();

					int id = key.getId().getItemId();
					log.debug("pubid : " + pubid);
					log.debug("id : " + id);
					ExecuteSQL(pubid, id);
				}
			}
		} catch (Exception e) {
			throw new ProcessingException("Could not undeploy page", e);
		}

		super.process(data);

	}

	private void ExecuteSQL(int id, int pubid) throws Exception {
		String connectionUrl = "jdbc:sqlserver://YourServer\\Instace;databaseName=YourCompany_data;user=DbUser;password=DbPsw;";
		Connection con = DriverManager.getConnection(connectionUrl);

		PreparedStatement stmtDel;
		con.setAutoCommit(false);
		try {
			String delete;
			delete = "delete from YourCompany_sitemap where pub_id=? and page_id=?";
			stmtDel = con.prepareStatement(delete);
			stmtDel.setInt(1, pubid);
			stmtDel.setInt(2, id);
			stmtDel.executeUpdate();
			stmtDel.close();
			con.commit();
		} catch (Exception ex) {
			con.rollback();
			throw ex;
		}
		con.close();

	}
}

  1. February 7, 2012 at 9:33 am

    Isn’t this much easier to do within Tridion using a Component Template? Then you will not have the need to update the lib content when the handeling the sitemap-code as well.

  2. February 7, 2012 at 9:40 am

    The sitemap (in db) always gets updated now when you publish a page. You can use this information for a breadcrumb to if you would like.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: