gt: 					if (f instanceof Folder) {
context: package com.dotcms.xmlsitemap;
  
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.OutputStreamWriter;
  import java.util.ArrayList;
  import java.util.Calendar;
  import java.util.Collections;
  import java.util.Comparator;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import java.util.zip.GZIPOutputStream;
  
  import org.quartz.Job;
  import org.quartz.JobExecutionContext;
  import org.quartz.JobExecutionException;
  import org.quartz.StatefulJob;
  
  import com.dotmarketing.beans.Host;
  import com.dotmarketing.beans.Identifier;
  import com.dotmarketing.beans.Inode;
  import com.dotmarketing.business.APILocator;
  import com.dotmarketing.business.FactoryLocator;
  import com.dotmarketing.business.IdentifierAPI;
  import com.dotmarketing.business.PermissionAPI;
  import com.dotmarketing.business.Permissionable;
  import com.dotmarketing.business.UserAPI;
  import com.dotmarketing.cache.StructureCache;
  import com.dotmarketing.db.DbConnectionFactory;
  import com.dotmarketing.db.HibernateUtil;
  import com.dotmarketing.exception.DotDataException;
  import com.dotmarketing.exception.DotHibernateException;
  import com.dotmarketing.exception.DotSecurityException;
  import com.dotmarketing.filters.CMSFilter;
  import com.dotmarketing.portlets.contentlet.business.ContentletAPI;
  import com.dotmarketing.portlets.contentlet.business.HostAPI;
  import com.dotmarketing.portlets.contentlet.model.Contentlet;
  import com.dotmarketing.portlets.fileassets.business.FileAssetAPI;
  import com.dotmarketing.portlets.files.business.FileAPI;
  import com.dotmarketing.portlets.files.business.FileFactory;
  import com.dotmarketing.portlets.folders.business.FolderAPI;
  import com.dotmarketing.portlets.folders.model.Folder;
  import com.dotmarketing.portlets.htmlpages.business.HTMLPageAPI;
  import com.dotmarketing.portlets.htmlpages.model.HTMLPage;
  import com.dotmarketing.portlets.links.model.Link;
  import com.dotmarketing.portlets.structure.factories.StructureFactory;
  import com.dotmarketing.portlets.structure.model.Structure;
  import com.dotmarketing.util.AssetsComparator;
  import com.dotmarketing.util.Config;
  import com.dotmarketing.util.InodeUtils;
  import com.dotmarketing.util.Logger;
  import com.dotmarketing.util.RegEX;
  import com.dotmarketing.util.RegExMatch;
  import com.dotmarketing.util.UtilMethods;
  import com.dotmarketing.util.XMLUtils;
  import com.liferay.portal.model.User;
  
  /**
   * This class manage the generation of the XMLSitemap<X>.xml.gz files from every
   * host in this dotCMS site
   *
   * @author Oswaldo
   *
   */
  public class XMLSitemapJob implements Job, StatefulJob {
  
  	private Host currentHost = null;
  	private User systemUser = null;
  	private File temporaryFile = null;
  	private File compressedFile = null;
  	private OutputStreamWriter out = null;
  
  	private int sitemapCounter = 1;
  	private int processedRegistries = 0;
  	private Map<String, Integer> hostFilesCounter = null;
  
  	private static String XML_SITEMAPS_FOLDER;
  	private ContentletAPI conAPI = APILocator.getContentletAPI();
  	private FileAPI fileAPI = APILocator.getFileAPI();
  	private FileFactory ffac = FactoryLocator.getFileFactory();
  	private FolderAPI folderAPI = APILocator.getFolderAPI();
  	private HTMLPageAPI htmlAPI = APILocator.getHTMLPageAPI();
  	private IdentifierAPI identAPI = APILocator.getIdentifierAPI();
  	private UserAPI userAPI = APILocator.getUserAPI();
  	private HostAPI hostAPI = APILocator.getHostAPI();
  	private FileAssetAPI fileAssetAPI = APILocator.getFileAssetAPI();
  	private boolean usePermalinks = false;
  	private boolean useStructureURLMap = true;
  	private String changeFrequencyConfig = "daily";
  	private String modifiedDateStringValue = UtilMethods.dateToHTMLDate(
  			new java.util.Date(), "yyyy-MM-dd");
  
  	private String structuresToIgnoreConfig = null;
  
  	public XMLSitemapJob() {
  		try {
  			systemUser = userAPI.getSystemUser();
  
  			hostFilesCounter = new HashMap<String, Integer>();
  
  			XML_SITEMAPS_FOLDER = Config.getStringProperty("org.dotcms.XMLSitemap.XML_SITEMAPS_FOLDER","/XMLSitemaps/");
  
  			String usePermalinksString = Config.getStringProperty("org.dotcms.XMLSitemap.USE_PERMALINKS=false","false");
  
  			String useStructureURLMapString = Config.getStringProperty("org.dotcms.XMLSitemap.USE_STRUCTURE_URL_MAP","false");
  
  			usePermalinks = (UtilMethods.isSet(usePermalinksString) ? Boolean
  					.parseBoolean(usePermalinksString) : false);
  
  			useStructureURLMap = (UtilMethods.isSet(useStructureURLMapString) ? Boolean
  					.parseBoolean(useStructureURLMapString)
  					: false);
  
  			modifiedDateStringValue = UtilMethods.dateToHTMLDate(
  					new java.util.Date(System.currentTimeMillis()),
  					"yyyy-MM-dd");
  
  			structuresToIgnoreConfig = Config.getStringProperty("org.dotcms.XMLSitemap.IGNORE_Structure_Ids","");
  
  			//generateSitemapPerHost();
  		} catch (Exception e) {
  			Logger.error(this, e.getMessage(), e);
  		}
  	}
  
  	public void execute(JobExecutionContext arg0) throws JobExecutionException {
  		try {
  			systemUser = userAPI.getSystemUser();
  			generateSitemapPerHost();
  
  		} catch (Exception e) {
  			Logger.error(this, e.getMessage(), e);
  		}
  		finally {
  		    try {
                  HibernateUtil.closeSession();
              } catch (DotHibernateException e) {
                  Logger.warn(this, e.getMessage(), e);
              }
  		    finally {
  		        DbConnectionFactory.closeConnection();
  		    }
  		}
  
  	}
  
  	private List<String> getIgnorableStrcutureIdsForHost(Host currentHost) {
  		List<String> ignorableStructureIds = new ArrayList<String>();
  		if (UtilMethods.isSet(structuresToIgnoreConfig)) {
  			String[] ignorableStructureNames = structuresToIgnoreConfig
  					.split(",");
  			for (String ignorableStructureName : ignorableStructureNames) {
  				ignorableStructureIds.add(ignorableStructureName.toLowerCase());
  			}
  		}
  		return ignorableStructureIds;
  	}
  
  	private String getUrlPatternReplacementText(Host currentHost,
  			String structureName) {
  		String replacingText = "";
  
  		try {
  			String replacementTextFromConfig = Config.getStringProperty("org.dotcms.XMLSitemap." + structureName
  							+ ".IGNORE_UrlText","");
  
  			if (UtilMethods.isSet(replacementTextFromConfig)) {
  				replacingText = replacementTextFromConfig;
  			}
  		} catch (Exception exception) {
  			// ignore this error and return the default text.
  		}
  		return replacingText;
  	}
  
  	/**
  	 * Generate the sitemap xml based on the show on menu pages, files, link and
  	 * folder
  	 */
  	@SuppressWarnings("unchecked")
  	public void generateSitemapPerHost() throws DotDataException,
  			DotSecurityException {
  
  		List<Host> hostsList = hostAPI.findAll(systemUser, false);
  
  		int orderDirection = 1;
  
  		List<String> structureVelocityVarNames = StructureFactory
  				.getAllVelocityVariablesNames();
  
  		for (Host host : hostsList) {
  
  			if(host.isSystemHost())
  				continue;
  
  			processedRegistries = 0;
  			currentHost = host;
  			sitemapCounter = 1;
  			String stringbuf = null;
  
  			try {
  				/**
  				 * mark all the existing sitemaps generated in the XMLSitemap
  				 * folder for the host specified to be removed upon creating new ones
  				 */
  				List<Object> oldSiteMapsToDel = new ArrayList<Object>();
  
  				Folder folder = folderAPI.findFolderByPath(XML_SITEMAPS_FOLDER, host, systemUser, false);
  
  				if (InodeUtils.isSet(folder.getIdentifier())) {
  					oldSiteMapsToDel.addAll(fileAPI.getFolderFiles(folder, false, systemUser, true));
  					oldSiteMapsToDel.addAll(conAPI.findContentletsByFolder(folder, systemUser, false));
  				}
  
  				hostFilesCounter.put(host.getHostname(), sitemapCounter);
  
  				/* adding host url */
  				stringbuf = "<url><loc>"
  						+ XMLUtils.xmlEscape("http://" + host.getHostname()
  								+ "/") + "</loc><lastmod>"
  						+ modifiedDateStringValue
  						+ "</lastmod><changefreq>daily</changefreq></url>\n";
  
  				writeFile(stringbuf);
  
  				addRegistryProcessed();
  
  				List<String> ignorableStructureIds = getIgnorableStrcutureIdsForHost(host);
  				/**
  				 * This part generate the detail pages sitemap links per
  				 * structure
  				 */
  				for (String stVelocityVarName : structureVelocityVarNames) {
  
  					if (ignorableStructureIds.contains(stVelocityVarName
  							.toLowerCase()))
  						continue;
  
  					Structure st = StructureFactory
  							.getStructureByVelocityVarName(stVelocityVarName);
  
  					if (!InodeUtils.isSet(st.getPagedetail()))
  						continue;
  
  					HTMLPage page = htmlAPI.loadLivePageById(
  							st.getPagedetail(), systemUser, true);
  
  					Logger.debug(this, " Creating Site Map for Structure "
  							+ stVelocityVarName);
  					Identifier pageIdentifier = identAPI.find(page
  							.getIdentifier());
  
  					Logger.debug(this,
  							" Performing Host Parameter validation Page Identifider Host ["
  									+ pageIdentifier.getHostId()
  									+ "], Host Identifider ["
  									+ host.getIdentifier() + "], Deleted ["
  									+ page.isDeleted() + "], Live ["
  									+ page.isLive() + "]");
  
  					if (!(host.getIdentifier().equals(
  							pageIdentifier.getHostId()) && (!page.isDeleted() && page
  							.isLive()))) {
  						Logger.debug(this,
  								"Host Parameter validation failed for structure ["
  										+ stVelocityVarName + "]");
  						continue;
  					}
  
  					String query = "+structureName:" + st.getVelocityVarName()
  							+ " +deleted:false +live:true";
  
  					List<Contentlet> hits = conAPI.search(query, -1, 0, "",
  							systemUser, true);
  
  					String structureURLMap = st.getUrlMapPattern();
  
  					List<RegExMatch> matches = null;
  
  					if (useStructureURLMap
  							&& UtilMethods.isSet(structureURLMap)) {
  						matches = RegEX.find(st.getUrlMapPattern(),
  								"({[^{}]+})");
  					}
  					for (Contentlet contenlet : hits) {
  						try {
  							if (usePermalinks) {
  								stringbuf = "<url><loc>"
  										+ XMLUtils.xmlEscape("http://"
  												+ host.getHostname()
  												+ "/permalink/"
  												+ contenlet.getIdentifier()
  												+ "/" + st.getPagedetail()
  												+ "/")
  										+ "</loc><lastmod>"
  										+ modifiedDateStringValue
  										+ "</lastmod><changefreq>daily</changefreq></url>\n";
  							} else if (useStructureURLMap
  									&& UtilMethods.isSet(structureURLMap)
  									&& (matches != null)) {
  								String uri = structureURLMap;
  								Logger.debug(this,
  										" Found the URL String for validation ["
  												+ uri + "]");
  								for (RegExMatch match : matches) {
  									String urlMapField = match.getMatch();
  									String urlMapFieldValue = contenlet
  											.getStringProperty(urlMapField
  													.substring(1, (urlMapField
  															.length() - 1)));
  									urlMapField = urlMapField.replaceFirst(
  											"\\{", "\\\\{");
  									urlMapField = urlMapField.replaceFirst(
  											"\\}", "\\\\}");
  
  									if (urlMapFieldValue != null) {
  										uri = uri.replaceAll(urlMapField,
  												urlMapFieldValue);
  									}
  									Logger.debug(this,
  											"Performing Variable replacement - urlMapField ["
  													+ match.getMatch()
  													+ "], urlMapField [ "
  													+ urlMapField
  													+ "], urlMapFieldValue ["
  													+ urlMapFieldValue
  													+ "], uri [" + uri + "]");
  								}
  
  								if (uri == null
  										&& UtilMethods
  												.isSet(st.getDetailPage())) {
  									if (page != null
  											&& UtilMethods.isSet(page
  													.getIdentifier())) {
  										uri = page.getURI() + "?id="
  												+ contenlet.getInode();
  									}
  								}
  								String urlRelacementText = getUrlPatternReplacementText(
  										host, stVelocityVarName);
  
  								uri = uri.replaceAll(urlRelacementText, "");
  
  								Logger.debug(this,
  										"Performing URL replacement - urlRelacementText ["
  												+ urlRelacementText
  												+ "], uri [" + uri + "]");
  
  								stringbuf = "<url><loc>"
  										+ XMLUtils.xmlEscape("http://"
  												+ host.getHostname() + uri)
  										+ "</loc><lastmod>"
  										+ modifiedDateStringValue
  										+ "</lastmod><changefreq>daily</changefreq></url>\n";
  							} else {
  								stringbuf = "<url><loc>"
  										+ XMLUtils.xmlEscape("http://"
  												+ host.getHostname()
  												+ pageIdentifier.getURI()
  												+ "?id="
  												+ contenlet.getIdentifier())
  										+ "</loc><lastmod>"
  										+ modifiedDateStringValue
  										+ "</lastmod><changefreq>daily</changefreq></url>\n";
  							}
  							writeFile(stringbuf);
  							addRegistryProcessed();
  
  						} catch (Exception e) {
  							Logger.error(this, e.getMessage(), e);
  						}
  					}
  				}
  				/**
  				 * This part add the show on menu pages. similar as we do in
  				 * navigationwebapi to generate sitemap
  				 * */
  				java.util.List<Folder> itemsList = new ArrayList<Folder>();
  
  				itemsList = folderAPI.findSubFolders(host, true);
  
  				//Logger.warn(this, "Finding Subfolders for referebce [" + itemsList.size() + "]");
  
  				Comparator<Folder> comparator = new AssetsComparator(
  						orderDirection);
  				Collections.sort(itemsList, comparator);
  
  				List<Inode> itemsList2 = new ArrayList<Inode>();
  
  				for (Folder f : itemsList) {
  