Demo entry 6643271

Java

   

Submitted by anonymous on Sep 27, 2017 at 13:42
Language: Java. Code size: 18.7 kB.

import org.jahia.registries.ServicesRegistry
import org.jahia.services.content.JCRCallback
import org.jahia.services.content.JCRNodeWrapper
import org.jahia.services.content.JCRSessionWrapper
import org.jahia.services.content.JCRTemplate
import org.jahia.services.usermanager.JahiaUser
import org.jahia.services.importexport.LegacyImportHandler.PageContext
import org.jahia.services.content.nodetypes.ExtendedNodeType
import org.jahia.services.content.nodetypes.NodeTypeRegistry
import javax.jcr.Node
import javax.jcr.RepositoryException
import javax.jcr.nodetype.NoSuchNodeTypeException
import org.jahia.api.Constants
import java.util.HashMap
import java.util.List
import java.text.MessageFormat
import groovy.io.FileType
import groovy.transform.Field
import org.jahia.services.content.PropertyConstraintViolationException

def log = log;
def dir = new File("D:\\plnext_git_nce\\doc\\technical_doc\\target\\service-pack\\dyn\\superadmin"); //provide the path of the reference folder
def templatePath = "D:\\test.zip"; //put this template together with reference folder, it's better
def apidocTemplate = "D:\\test2.zip";
def assetsDir = "D:\\plnext_git_nce\\doc\\technical_doc\\target\\service-pack\\assets.zip";
def assetsPath = "/sites/at1/files";
def jahiaPath = "/sites/at1/home/support/dx";//customize to your need
def apidocDir = "D:\\plnext_git_nce\\doc\\technical_doc\\target\\service-pack\\apidoc.zip";
def apidocPath = "D:\\plnext_git_nce\\doc\\technical_doc\\target\\service-pack\\apidoc\\apidocs.html"
// def sideBar = new File("D:\\plnext_git_nce\\doc\\technical_doc\\target\\service-pack\\dyn\\superadmin\\leftsidebar.html");

// def count = 0;

JahiaUser user = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupRootUser().getJahiaUser();


		JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(user, Constants.EDIT_WORKSPACE, null,
				new JCRCallback<Object>() {
					public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
						// read startpath (home page of my website)
						JCRNodeWrapper dxSupportPage = session.getNode(jahiaPath);
						List<Locale> locales = new ArrayList<Locale>();
						locales.add(Locale.ENGLISH);
						//add your languages/locales
						//do your logic to read the structure
                        uploadAssets(assetsDir,assetsPath,session,jahiaPath,locales, apidocTemplate,apidocDir,apidocPath);
						getFileStructure(dir,session,dxSupportPage,locales,templatePath);
						getFileaddContent(dir,session,dxSupportPage,jahiaPath);
						return null;
					}
				});

	private void uploadAssets(String assetsDir, String assetsPath, JCRSessionWrapper session, String jahiaPath, List<Locale> locales,String apidocTemplate,String apidocDir,String apidocPath){
		//have to upload apidoc.zip as well
		java.io.File fileAsset = new java.io.File(assetsDir);
		if(fileAsset.exists()) {
		   java.io.InputStream is = new java.io.FileInputStream(fileAsset);
		   JCRNodeWrapper parentNode = session.getNode(assetsPath);
		   JCRNodeWrapper fileNodeAsset = parentNode.uploadFile(fileAsset.getName(), is, "application/zip");
		   session.save();

		   boolean removeArchiveAfterUnzip = true;
		   java.util.List<String> paths = new java.util.ArrayList<String>();
		   paths.add(fileNodeAsset.getPath());
		   org.jahia.ajax.gwt.helper.ZipHelper.getInstance().unzip(paths, removeArchiveAfterUnzip, session, Locale.ENGLISH);
		   session.save();
		}
		else{

		}

		java.io.File fileApidoc = new java.io.File(apidocDir);
		if(fileApidoc.exists()) {
		   java.io.InputStream is = new java.io.FileInputStream(fileApidoc);
		   JCRNodeWrapper parentNode = session.getNode(assetsPath);
		   JCRNodeWrapper fileNodeApidoc = parentNode.uploadFile(fileApidoc.getName(), is, "application/zip");
		   session.save();

		   boolean removeArchiveAfterUnzip = true;
		   java.util.List<String> paths = new java.util.ArrayList<String>();
		   paths.add(fileNodeApidoc.getPath());
		   org.jahia.ajax.gwt.helper.ZipHelper.getInstance().unzip(paths, removeArchiveAfterUnzip, session, Locale.ENGLISH);
		   session.save();
		}
		else{

		}

		//add the page of apidoc, add parameter
        //JCRNodeWrapper apidocPage = createPage("apidocs", "apidoc", "apidocs", session.getNode(jahiaPath),session, locales, apidocTemplate);
        
        JCRNodeWrapper apidocParentNode = session.getNode(jahiaPath);
		// remove all unsupported characters
		// JCRNodeWrapper subPage = null;
		boolean hasthisNode = apidocParentNode.hasNode("apidocs");
		JCRNodeWrapper subPage = null;
		File zipfile = null;
		try {
			if(hasthisNode == false){
				zipfile = new File(apidocTemplate);
			
				ServicesRegistry.getInstance().getImportExportService().importZip(apidocParentNode.getPath(),
						new FileSystemResource(zipfile), DocumentViewImportHandler.ROOT_BEHAVIOUR_REPLACE,session);
				session.save()
				// session.refresh(false);
				subPage = apidocParentNode.getNode("test2");

		      
				for (Locale locale : locales) {
					Node translation = subPage.getOrCreateI18N(locale);
					// translation.setProperty("jcr:title", "");
					translation.setProperty("jcr:title", "apidocs");
					session.save();
				}

				// subPage.copy(parent.getPath(), pageKey);
	            subPage.rename("apidocs");
				session.save();
			 //    subPage = parent.getNode(pageKey);
			}
			else{
				subPage = apidocParentNode.getNode("apidocs");
				
					for (Locale locale : locales) {
						Node translation = subPage.getOrCreateI18N(locale);
						translation.setProperty("jcr:title", "");
						translation.setProperty("jcr:title", "apidocs");
						session.save();
					}
				session.save();
			}

			} catch (IOException ex) {

			log.error("Page cannot be imported!!");
		}
		    catch(ItemExistsException iee){

		    }

		session.save()

		//get apidocs.html content 
		String apidocFileContent = new File(apidocPath.toString()).getText('UTF-8')
		def (value1,value2) = apidocFileContent.split("<!--  css on top of the page : http://developer.yahoo.com/performance/rules.html -->");
		def (value3,value4) = value2.split("</body>");
        log.info(value3);
        //do the manual replacement finally
        // def value5 = value3.replaceAll(".xWidget .xOverflowXAuto .xOverflowYAuto .xPrintAdaptX .xPrintAdaptY{\nheight:92%;\n}","span#w2{height:94% !important;}#pagecontent1{padding-left:0px;}")
        // log.info(value5);
        try{
			JCRNodeWrapper nodeContentlist = subPage.getNode("pagecontent");
			JCRNodeWrapper subRichtext = nodeContentlist.addNode("rich-text", "jnt:bigText");
	        JCRNodeWrapper subText = subRichtext.addNode("j:translation_en", "jnt:translation");

	        subText.setProperty("jcr:language", "en");
	        subText.setProperty("text", value3);

	        session.save();            

		}catch(Exception ex){
                	if(ex instanceof ItemExistsException){
                		JCRNodeWrapper nodeContentlist = subPage.getNode("pagecontent");
		                JCRNodeWrapper subRichtext = nodeContentlist.getNode("rich-text");
		                JCRNodeWrapper subText = subRichtext.getNode("j:translation_en");

		                subText.setProperty("jcr:language", "en");
		                subText.setProperty("text", value3);
		                session.save();
		                
                	}
                	else if(ex instanceof PropertyConstraintViolationException){
                		session.save()
                		log.info()
                		
                	}
                	else{
                		//return;
                		log.info()
                	}
                }
            session.save()
		return;
	}

	private void getFileStructure(File dir,JCRSessionWrapper session, JCRNodeWrapper parent, List<Locale> locales,String templatePath) {
		dir.eachFile(FileType.ANY) { file->
  			if (file.name.endsWith(".html") ) {
                  def (value1, value2) = file.getName().tokenize( '.' );
                  String pageName = value1;
                  JCRNodeWrapper sub = readStructure(pageName,session, parent, locales, templatePath);
                  // addContent(file,sub,session);
                  session.save()
             }
             else{
             	 String pageName = file.getName();
                 JCRNodeWrapper subPage = readStructure(pageName,session, parent, locales, templatePath);
                 getFileStructure(new File(file.toString()),session, subPage, locales, templatePath);
                 session.save()
             }
			}	

		return;
	}

	private void getFileaddContent(File dir, JCRSessionWrapper session, JCRNodeWrapper parent,String jahiaPath) {
		dir.eachFile(FileType.ANY) { file->
  			if (file.name.endsWith(".html") ) {
                  def (value1, value2) = file.getName().tokenize( '.' );
                  String pageName = value1;
                  if(pageName == "documentation"){
                  	addCatalog(file,jahiaPath,session);
                  }
                  JCRNodeWrapper sub = parent.getNode(pageName);
                  addContent(file,sub,session);
                  session.save()
             }
             else{
             	 String pageName = file.getName();
                 JCRNodeWrapper subPage = parent.getNode(pageName);
                 getFileaddContent(new File(file.toString()),session, subPage, jahiaPath);
                 session.save()
             }
			}	

		return;
	}
	

	private void addContent(File file,JCRNodeWrapper pagenode,JCRSessionWrapper session){
        
        //modify the way to get the content   Catch exception
        
    	String fileContent = new File(file.toString()).getText('UTF-8')
    	boolean hasSidebar = fileContent.contains("<!-- Sidebar -->");

		if(hasSidebar == false){
			try{
			JCRNodeWrapper nodeContentlist = pagenode.getNode("landingpicture");
			JCRNodeWrapper subRichtext = nodeContentlist.addNode("rich-text", "jnt:bigText");
	        JCRNodeWrapper subText = subRichtext.addNode("j:translation_en", "jnt:translation");

	        subText.setProperty("jcr:language", "en");
	        subText.setProperty("text", fileContent);

	        session.save();            

		}catch(Exception ex){
                	if(ex instanceof ItemExistsException){
                		JCRNodeWrapper nodeContentlist = pagenode.getNode("landingpicture");
		                JCRNodeWrapper subRichtext = nodeContentlist.getNode("rich-text");
		                JCRNodeWrapper subText = subRichtext.getNode("j:translation_en");

		                subText.setProperty("jcr:language", "en");
		                subText.setProperty("text", fileContent);
		                session.save();
		                
                	}
                	else if(ex instanceof PropertyConstraintViolationException){
                		session.save()
                		log.info("ex PCVException "+pagenode+" "+ex)
                		
                	}
                	else{
                		//return;
                		log.info("ex otherException"+pagenode+" "+ex)
                	}
                }
            session.save()
            return ;
		}

		def (fileContent1,fileContent2) = fileContent.split("<!-- Sidebar -->");
		def (fileContent3,fileContent4) = fileContent2.split("<!-- /#sidebar -->");
		String filesideBar = fileContent3;
        String fileContents = fileContent1 + fileContent4;

		try{
			JCRNodeWrapper nodeContentlist = pagenode.getNode("section--container--row--grid-main");
			JCRNodeWrapper subRichtext = nodeContentlist.addNode("rich-text", "jnt:bigText");
	        JCRNodeWrapper subText = subRichtext.addNode("j:translation_en", "jnt:translation");

	        subText.setProperty("jcr:language", "en");
	        subText.setProperty("text", fileContents);

	        session.save();            

		}catch(Exception ex){
                	if(ex instanceof ItemExistsException){
                		JCRNodeWrapper nodeContentlist = pagenode.getNode("section--container--row--grid-main");
		                JCRNodeWrapper subRichtext = nodeContentlist.getNode("rich-text");
		                JCRNodeWrapper subText = subRichtext.getNode("j:translation_en");

		                subText.setProperty("jcr:language", "en");
		                subText.setProperty("text", fileContents);
		                session.save();
		                
                	}
                	else if(ex instanceof PropertyConstraintViolationException){
                		session.save()
                		log.info("ex PCVException "+pagenode+" "+ex)
                		
                	}
                	else{
                		//return;
                		log.info("ex otherException"+pagenode+" "+ex)
                	}
                }
            session.save()

        try{
	        	JCRNodeWrapper nodeContentlist2 = pagenode.getNode("section--container--row--grid-side");
				JCRNodeWrapper subRichtext2 = nodeContentlist2.addNode("rich-text", "jnt:bigText");
		        JCRNodeWrapper subText2 = subRichtext2.addNode("j:translation_en", "jnt:translation");

		        subText2.setProperty("jcr:language", "en");
		        subText2.setProperty("text", filesideBar);

		        session.save();
		        } catch(Exception ex2){

                	if(ex2 instanceof ItemExistsException){
                		JCRNodeWrapper nodeContentlist2 = pagenode.getNode("section--container--row--grid-side");
		                JCRNodeWrapper subRichtext2 = nodeContentlist2.getNode("rich-text");
		                JCRNodeWrapper subText2 = subRichtext2.getNode("j:translation_en");

		                subText2.setProperty("jcr:language", "en");
		                subText2.setProperty("text", filesideBar);
		                session.save();
                	}
                	else if(ex2 instanceof PropertyConstraintViolationException){
                		session.save()
                		log.info("ex2 PCVException"+pagenode+" "+ex2)
                		
                	}
                	else{
                		log.info("ex2 OtherException"+pagenode+" "+ex2)
                	}
                }

        session.save()
        return;
	}

	private void addCatalog(File file,String jahiaPath, JCRSessionWrapper session){
        
        //modify the way to get the content   Catch exception
        
    	String fileContent = new File(file.toString()).getText('UTF-8')
    	JCRNodeWrapper dxSupportPage = session.getNode(jahiaPath);
	
			try{
			JCRNodeWrapper nodeContentlist = dxSupportPage.getNode("landingpicture");
			JCRNodeWrapper subRichtext = nodeContentlist.addNode("rich-text", "jnt:bigText");
	        JCRNodeWrapper subText = subRichtext.addNode("j:translation_en", "jnt:translation");

	        subText.setProperty("jcr:language", "en");
	        subText.setProperty("text", fileContent);

	        session.save();            

			}catch(Exception ex){
	                	if(ex instanceof ItemExistsException){
	                		JCRNodeWrapper nodeContentlist = dxSupportPage.getNode("landingpicture");
			                JCRNodeWrapper subRichtext = nodeContentlist.getNode("rich-text");
			                JCRNodeWrapper subText = subRichtext.getNode("j:translation_en");

			                subText.setProperty("jcr:language", "en");
			                subText.setProperty("text", fileContent);
			                session.save();
			                
	                	}
	                	else if(ex instanceof PropertyConstraintViolationException){
	                		session.save()
	                		log.info()
	                		
	                	}
	                	else{
	                		//return;
	                		log.info()
	                	}
	                }
            session.save()
            return ;
		}

		
	private JCRNodeWrapper readStructure(String pageTitle,JCRSessionWrapper session, JCRNodeWrapper parent, List<Locale> locales,String templatePath) {
		
            JCRNodeWrapper subPage = createPage( pageTitle, "simple", pageTitle, parent, session, locales,templatePath);			
		    return subPage;
		
	}

	private JCRNodeWrapper createPage(String title, String template, String pageKey, JCRNodeWrapper parent,
			JCRSessionWrapper session, List<Locale> locales, String templatePath) throws RepositoryException {

		if (pageKey == null) {
			try {
				pageKey = JCRContentUtils.generateNodeName(title);
			} catch (NullPointerException npe) {
				pageKey = "untitled";
				log.error(MessageFormat.format(
						"Impossible to generate a system name from page title =[{0}], pageKey = [{1}]", title, pageKey),
						npe);
			}
		}

		// remove all unsupported characters
		pageKey = pageKey.replace('/', '_');
		pageKey = JCRContentUtils.replaceColon(pageKey);
		pageKey = pageKey.replace('[', '_');
		pageKey = pageKey.replace(']', '_');

		// JCRNodeWrapper subPage = null;
		boolean hasthisNode = parent.hasNode(pageKey);
		JCRNodeWrapper subPage = null;
		File zipfile = null;
		try {
			if(hasthisNode == false){
				zipfile = new File(templatePath);
			
				ServicesRegistry.getInstance().getImportExportService().importZip(parent.getPath(),
						new FileSystemResource(zipfile), DocumentViewImportHandler.ROOT_BEHAVIOUR_REPLACE,session);
				session.save()
				// session.refresh(false);
				subPage = parent.getNode("test");

		        if(title == null || title.length() == 0) {
			        	title = "untitled" + pageKey;
			        }
					for (Locale locale : locales) {
						Node translation = subPage.getOrCreateI18N(locale);
						// translation.setProperty("jcr:title", "");
						translation.setProperty("jcr:title", title);
						session.save();
					}

				// subPage.copy(parent.getPath(), pageKey);
	            subPage.rename(pageKey);
				session.save();
			 //    subPage = parent.getNode(pageKey);
			}
			else{
				subPage = parent.getNode(pageKey);
				if(title == null || title.length() == 0) {
			        	title = "untitled" + pageKey;
			        }
					for (Locale locale : locales) {
						Node translation = subPage.getOrCreateI18N(locale);
						translation.setProperty("jcr:title", "");
						translation.setProperty("jcr:title", title);
						session.save();
					}
				session.save();
			}

			

			} catch (IOException ex) {

			log.error("Page cannot be imported!!");
		}
		    catch(ItemExistsException iee){

		    }

		session.save()

		return subPage;


	}

This snippet took 0.03 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).