import org.xwiki.rendering.block.*;
import org.xwiki.rendering.renderer.*;
import org.xwiki.rendering.syntax.*;
import org.xwiki.rendering.parser.*;
import org.xwiki.rendering.renderer.printer.DefaultWikiPrinter;
import org.xwiki.rendering.renderer.printer.WikiPrinter;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.api.*;
import java.util.*;
import java.lang.reflect.*;

public class KanbanGroovy {
 def xwiki;
 def xcontext;

  public setXWiki(xcontext, xwiki) {
   this.xcontext = xcontext;
   this.xwiki = xwiki;
  }

  public String getContentFromXDOM(xdom) {
     WikiPrinter printer = new DefaultWikiPrinter();
     BlockRenderer renderer = (BlockRenderer) Utils.getComponent(BlockRenderer.class, Syntax.XWIKI_2_0.toIdString());
     renderer.render(xdom, printer);
     return printer.toString();
   }

  public int updateDocument(doc, macroName, nb, newContent) {
    try {
      XDOM xdom = (doc == null) ? null : doc.getDocument().getXDOM();
      xdom = (xdom == null) ? null : xdom.clone();

      def result = updateDocumentXDOM(xdom, macroName, nb, newContent);

       we updated the xdom, apply it
      if (result!=0) {
         doc.setContent(getContentFromXDOM(xdom));
         doc.save("Kanban content updated")
         return result;
      }

      return 0;
    } catch (e) {
      xcontext.getContext().put("exception", e);
      return 0;
    }
   }

  public int updateDocumentXDOM(xdom, macroName, nb, newContent) {
      def xdomchanged = false;
      Finding Macro Block
      int currentNb = 0;
      List<MacroBlock> macroBlocks = xdom.getChildrenByType(MacroBlock.class, true);
      for (MacroBlock macroBlock : macroBlocks) {
       def id = macroBlock.getId();
       System.out.println("Found macro " + id);
       if (id==macroName) {
        if (nb!=currentNb) {
          currentNb++;
        } else {
         System.out.println("Found macro number " + currentNb);
         def currentContent = macroBlock.getContent();
         if (currentContent!=newContent) {
             currentContent = newContent;
             System.out.println("Macro block " + macroBlock);
             
We need to use reflection until this exists: macroBlock.setContent(newContent);
             Field field;  
             try {
              field = macroBlock.getClass().getSuperclass().getDeclaredField("content");
             } catch (e) {
              field = macroBlock.getClass().getDeclaredField("content");
             }
             field.setAccessible(true);
             field.set(macroBlock, newContent);
             return 1;
          }
         }
        }
      }
      return 0;
     }
   }

Tags:
Partita IVA: 01131710376 - Copyright © 2008-2022 APICe@DISI Research Group - PRIVACY