/**
   * Obtiene un documento XML con la información de la instancia de la documentación.
   *
   * @param request Obheto HTTPServletRequest para construir URLS
   * @param export Indica si la información en el documento XML estará procesada para exportación
   *     estática.
   * @return Documento XML con la información de la instancia de la documentación.
   */
  public Document getXMLDocument(HttpServletRequest request, boolean export) {
    Document doc = SWBUtils.XML.getNewDocument();
    Process p = getProcessRef();
    Element root = doc.createElement("root");
    root.setAttribute("title", p.getTitle());
    root.setAttribute("uri", p.getURI());
    root.setAttribute("export", String.valueOf(export));
    root.setAttribute("contextPath", SWBPortal.getContextPath());
    doc.appendChild(root);
    String colorTask = "";
    boolean hasModel = false;

    try {
      Iterator<DocumentSectionInstance> itdsi =
          SWBComparator.sortSortableObject(listDocumentSectionInstances());
      while (itdsi.hasNext()) { // Sections
        DocumentSectionInstance dsi = itdsi.next();
        if (!dsi.getSecTypeDefinition().isActive()) {
          continue;
        }
        SemanticClass cls =
            dsi.getSecTypeDefinition() != null
                    && dsi.getSecTypeDefinition().getSectionType() != null
                ? dsi.getSecTypeDefinition().getSectionType().transformToSemanticClass()
                : null;

        if (cls != null) {
          if (cls.equals(Model.sclass)) { // Model
            hasModel = true;
            continue;
          }
          root.appendChild(doc.createTextNode("\n\t"));
          Element section = doc.createElement("section");
          root.appendChild(section);
          section.setAttribute("className", cls.getName());
          section.setAttribute("title", dsi.getSecTypeDefinition().getTitle());
          section.setAttribute("uri", dsi.getURI());
          section.setAttribute("idSection", dsi.getId());
          section.setAttribute("url", cls.getName() + dsi.getId());

          Iterator<SectionElement> itse =
              SWBComparator.sortSortableObject(dsi.listDocuSectionElementInstances());
          int count = 1;
          while (itse.hasNext()) { // Instances
            boolean addInstance = true;
            section.appendChild(doc.createTextNode("\n\t\t"));
            SectionElement se = itse.next();
            //                        System.out.println("Procesando elemento "+se.getURI());
            Element instance = doc.createElement("instance");
            instance.setAttribute("id", se.getId());
            instance.setAttribute("uri", se.getURI());
            instance.setAttribute("className", cls.getName());
            if (cls.isSubClass(Instantiable.swpdoc_Instantiable, false)) { // Elements Instantiable
              //                            System.out.println("  Es un instanciable");
              String[] props = dsi.getSecTypeDefinition().getVisibleProperties().split("\\|");
              for (String propt : props) {
                //                                System.out.println("  -Agregando propiedad
                // "+propt);
                String idprop = propt.substring(propt.indexOf(";") + 1, propt.length());
                String titleprop = propt.substring(0, propt.indexOf(";"));
                SemanticProperty prop =
                    SWBPlatform.getSemanticMgr().getVocabulary().getSemanticPropertyById(idprop);
                String value = "";
                Element property = doc.createElement("property");
                instance.appendChild(property);
                property.setAttribute("title", titleprop);
                property.setAttribute("propid", idprop);
                //                                System.out.println("  -SemanticProperty: "+prop);
                if (prop != null && !prop.getPropId().equals(Referable.swpdoc_file.getPropId())) {
                  //                                    System.out.println("  -Prop is not file
                  // ref");
                  value =
                      (se.getSemanticObject().getProperty(prop) != null
                          ? se.getSemanticObject().getProperty(prop)
                          : "");
                  //                                    System.out.println("  -Prop value: "+value);
                } else { // Show URL download file
                  //                                    System.out.println("  -Prop is file ref");
                  if (se instanceof ElementReference) {
                    ElementReference er = (ElementReference) se;
                    if (er.getElementRef() == null) {
                      dsi.removeDocuSectionElementInstance(er);
                      er.remove();
                      continue;
                    }
                    se = (SectionElement) er.getElementRef();
                  }
                  Referable ref =
                      (Referable)
                          SWBPlatform.getSemanticMgr().getOntology().getGenericObject(se.getURI());
                  if (!ref.hasRepositoryReference()) addInstance = false;
                  //                                    System.out.println("addInstance:
                  // "+addInstance);
                  if (!addInstance) continue;

                  //                                    System.out.println("  ...Continue adding
                  // element");
                  RepositoryDirectory rd = ref.getRefRepository().getRepositoryDirectory();
                  SWBResourceURL urld =
                      new SWBResourceURLImp(
                          request, rd.getResource(), rd, SWBResourceModes.UrlType_RENDER);

                  RepositoryElement re = (RepositoryElement) ref.getRefRepository();
                  VersionInfo vi =
                      ref.getVersion() != null ? ref.getVersion() : re.getLastVersion();
                  urld.setMode(ProcessFileRepository.MODE_GETFILE)
                      .setCallMethod(SWBResourceURL.Call_DIRECT)
                      .setParameter("fid", ref.getRefRepository().getId());
                  urld.setParameter("verNum", vi.getVersionNumber() + "");
                  String urlDownload = urld.toString();
                  if (export) { // add file to zip
                    String basePath =
                        SWBPortal.getWorkPath()
                            + "/models/"
                            + p.getProcessSite().getId()
                            + "/swp_RepositoryFile/"
                            + ref.getRefRepository().getId()
                            + "/"
                            + vi.getVersionNumber()
                            + "/";
                    File baseDir = new File(basePath);
                    String basePathDest =
                        SWBPortal.getWorkPath()
                            + "/models/"
                            + p.getProcessSite().getId()
                            + "/Resource/"
                            + p.getId()
                            + "/download/";
                    File repFile =
                        new File(
                            basePathDest
                                + "rep_files/"
                                + ref.getRefRepository().getId()
                                + "/"
                                + vi.getVersionNumber()
                                + "/");
                    if (!repFile.exists()) {
                      repFile.mkdirs();
                    }
                    if (baseDir.isDirectory()) {
                      File[] files = baseDir.listFiles();
                      for (File file : files) {
                        urlDownload =
                            "rep_files/"
                                + ref.getRefRepository().getId()
                                + "/"
                                + vi.getVersionNumber()
                                + "/"
                                + file.getName();
                        SWPUtils.copyFile(
                            file.getAbsolutePath(),
                            repFile.getAbsolutePath() + "/" + file.getName());
                        break;
                      }
                    }
                  }
                  if (re instanceof RepositoryFile) {
                    value =
                        "<a target=\"_blank\" href=\""
                            + urlDownload
                            + "\">"
                            + ref.getRefRepository().getTitle()
                            + " <i class=\"fa fa-download\"></i></a>";
                  } else if (re instanceof RepositoryURL) {
                    value =
                        "<a target=\"_blank\" href=\""
                            + vi.getVersionFile()
                            + "\">"
                            + ref.getRefRepository().getTitle()
                            + " <i class=\"fa fa-external-link\"></i></a>";
                  }
                }
                //                                System.out.println("Adding property with val:
                // "+value);
                property.appendChild(doc.createTextNode(value));
              }

            } else if (cls.equals(FreeText.sclass)) { // FreeText
              // Validar el export
              FreeText ft = (FreeText) se;
              String html = ft.getText().replace("&ldquo;", "&quot;");
              html = html.replace("&rdquo;", "&quot;");
              html = html.replace("&ndash;", "-");
              html = html.replace("&mdash;", "-");
              html = html.replace("&bull;", "<li>");
              org.jsoup.nodes.Document d = null;
              if (html != null) {
                d = Jsoup.parse(html);
                Elements elements = d.select("[src]");
                for (org.jsoup.nodes.Element src : elements) {
                  if (src.tagName().equals("img") || src.tagName().equals("iframe")) {
                    String attr = src.attr("src");
                    if (attr.contains("../..")) {
                      src.attr("src", src.attr("src").substring(5));
                    }
                    if (export && !attr.contains("http")) {
                      File file =
                          new File(SWBPortal.getWorkPath() + "/" + src.attr("src").substring(5));
                      String basePathDest =
                          SWBPortal.getWorkPath()
                              + "/models/"
                              + p.getProcessSite().getId()
                              + "/Resource/"
                              + p.getId()
                              + "/download/";
                      File repFile = new File(basePathDest + "rep_files/" + se.getId() + "/");
                      if (!repFile.exists()) {
                        repFile.mkdirs();
                      }
                      SWPUtils.copyFile(
                          file.getAbsolutePath(), repFile.getAbsolutePath() + "/" + file.getName());
                      src.attr("src", "rep_files/" + se.getId() + "/" + file.getName());
                    }
                  }
                }
              }
              instance.appendChild(doc.createTextNode((d != null ? d.html() : "")));
            } else if (cls.equals(Activity.sclass)) { // Activity
              Activity a = (Activity) se;
              Element property = doc.createElement("property");
              instance.appendChild(property);
              property.setAttribute("title", Descriptiveable.swb_title.getLabel());
              property.setAttribute("propid", Descriptiveable.swb_title.getPropId());
              property.appendChild(doc.createTextNode(a.getTitle() != null ? a.getTitle() : ""));

              Element propertyd = doc.createElement("propertyd");
              instance.appendChild(propertyd);
              propertyd.setAttribute("title", Descriptiveable.swb_description.getLabel());
              propertyd.setAttribute("propid", Descriptiveable.swb_description.getPropId());

              String html = a.getDescription();
              org.jsoup.nodes.Document d = null;
              if (html != null) {
                d = Jsoup.parse(html);
                Elements elements = d.select("[src]");
                for (org.jsoup.nodes.Element src : elements) {
                  if (src.tagName().equals("img") || src.tagName().equals("iframe")) {
                    String attr = src.attr("src");
                    if (attr.contains("../..")) {
                      src.attr("src", src.attr("src").substring(5));
                    }
                    if (export && !attr.contains("http")) {
                      File file =
                          new File(SWBPortal.getWorkPath() + "/" + src.attr("src").substring(5));
                      String basePathDest =
                          SWBPortal.getWorkPath()
                              + "/models/"
                              + p.getProcessSite().getId()
                              + "/Resource/"
                              + p.getId()
                              + "/download/";
                      File repFile = new File(basePathDest + "rep_files/" + se.getId() + "/");
                      if (!repFile.exists()) {
                        repFile.mkdirs();
                      }
                      SWPUtils.copyFile(
                          file.getAbsolutePath(), repFile.getAbsolutePath() + "/" + file.getName());
                      src.attr("src", "rep_files/" + se.getId() + "/" + file.getName());
                    }
                  }
                }
              }
              propertyd.appendChild(doc.createTextNode(d != null ? d.html() : ""));

              instance.setAttribute("fill", a.getFill());
              instance.setAttribute("id", a.getActivityRef().getProcessActivity().getId());

              // Activity act = (Activity)
              // SWBPlatform.getSemanticMgr().getOntology().getGenericObject(se.getURI());
              if (a.getFill() != null) {
                if (colorTask.length() > 0) {
                  colorTask += "|";
                }
                colorTask += a.getActivityRef().getProcessActivity().getURI() + ";" + a.getFill();
              }
              Iterator<SectionElementRef> itser =
                  SWBComparator.sortSortableObject(a.listSectionElementRefs());
              if (itser.hasNext()) {
                instance.setAttribute("related", "true");
              } else {
                instance.setAttribute("related", "false");
              }
              Map mapSect = new HashMap();
              while (itser.hasNext()) {
                SectionElementRef ser = itser.next();
                if (ser.getSectionElement() != null) {
                  String uris;
                  if (mapSect.containsKey(ser.getSectionElement().getParentSection())) {
                    uris =
                        mapSect.get(ser.getSectionElement().getParentSection()).toString()
                            + "|"
                            + ser.getSectionElement();
                  } else {
                    uris = ser.getSectionElement().getURI();
                  }
                  mapSect.put(ser.getSectionElement().getParentSection(), uris);
                }
              }
              Iterator itset = mapSect.entrySet().iterator();
              while (itset.hasNext()) {
                Map.Entry e = (Map.Entry) itset.next();
                Element eds = doc.createElement("documentSection");
                instance.appendChild(eds);
                eds.setAttribute("uri", e.getKey().toString());
                DocumentSection ds = (DocumentSection) e.getKey();
                String[] props = ds.getVisibleProperties().split("\\|");
                eds.setAttribute("title", ds.getTitle());
                eds.setAttribute("url", "related" + ds.getId() + "act" + a.getId());

                String[] uris = e.getValue().toString().split("\\|");
                int i = 0;
                for (String uri : uris) {
                  Element related = doc.createElement("related");
                  related.setAttribute("count", i + "");
                  i++;
                  SemanticClass scls = ds.getSectionType().transformToSemanticClass();
                  eds.appendChild(related);
                  related.setAttribute("uri", uri);
                  related.setAttribute("className", scls.getName());
                  SectionElement ser =
                      (SectionElement)
                          SWBPlatform.getSemanticMgr().getOntology().getGenericObject(uri);
                  SemanticObject so = SemanticObject.createSemanticObject(uri);
                  if (so != null) {
                    for (String propt : props) {
                      String idprop = propt.substring(propt.indexOf(";") + 1, propt.length());
                      String titleprop = propt.substring(0, propt.indexOf(";"));
                      SemanticProperty prop =
                          SWBPlatform.getSemanticMgr()
                              .getVocabulary()
                              .getSemanticPropertyById(idprop);
                      Element erprop = doc.createElement("relatedprop");
                      related.appendChild(erprop);
                      erprop.setAttribute("title", titleprop);
                      erprop.setAttribute("propid", idprop);
                      String value = "";
                      if (prop != null
                          && !prop.getPropId().equals(Referable.swpdoc_file.getPropId())) {
                        value =
                            ser.getSemanticObject().getProperty(prop) != null
                                ? ser.getSemanticObject().getProperty(prop)
                                : "";
                      } else { // Show URL download file
                        if (ser instanceof ElementReference) {
                          ElementReference er = (ElementReference) ser;
                          if (er.getElementRef() == null) {
                            dsi.removeDocuSectionElementInstance(er);
                            er.remove();
                            continue;
                          }
                          ser = (SectionElement) er.getElementRef();
                        }
                        Referable ref =
                            (Referable)
                                SWBPlatform.getSemanticMgr()
                                    .getOntology()
                                    .getGenericObject(ser.getURI());
                        RepositoryDirectory rd = ref.getRefRepository().getRepositoryDirectory();
                        SWBResourceURL urld =
                            new SWBResourceURLImp(
                                request, rd.getResource(), rd, SWBResourceModes.UrlType_RENDER);
                        urld.setMode(ProcessFileRepository.MODE_GETFILE)
                            .setCallMethod(SWBResourceURL.Call_DIRECT)
                            .setParameter("fid", ref.getRefRepository().getId());
                        RepositoryElement re = (RepositoryElement) ref.getRefRepository();
                        VersionInfo vi =
                            ref.getVersion() != null ? ref.getVersion() : re.getLastVersion();
                        urld.setParameter("verNum", vi.getVersionNumber() + "");

                        String urlDownload = urld.toString();
                        if (export) { // add file to zip
                          String basePath =
                              SWBPortal.getWorkPath()
                                  + "/models/"
                                  + p.getProcessSite().getId()
                                  + "/swp_RepositoryFile/"
                                  + ref.getRefRepository().getId()
                                  + "/"
                                  + vi.getVersionNumber()
                                  + "/";
                          File baseDir = new File(basePath);
                          String basePathDest =
                              SWBPortal.getWorkPath()
                                  + "/models/"
                                  + p.getProcessSite().getId()
                                  + "/Resource/"
                                  + p.getId()
                                  + "/download/";
                          File repFile =
                              new File(
                                  basePathDest
                                      + "rep_files/"
                                      + ref.getRefRepository().getId()
                                      + "/"
                                      + vi.getVersionNumber()
                                      + "/");
                          if (!repFile.exists()) {
                            repFile.mkdirs();
                          }
                          if (baseDir.isDirectory()) {
                            File[] files = baseDir.listFiles();
                            for (File file : files) {
                              urlDownload =
                                  "rep_files/"
                                      + ref.getRefRepository().getId()
                                      + "/"
                                      + vi.getVersionNumber()
                                      + "/"
                                      + file.getName();
                              SWPUtils.copyFile(
                                  file.getAbsolutePath(),
                                  repFile.getAbsolutePath() + "/" + file.getName());
                              break;
                            }
                          }
                        }
                        if (re instanceof RepositoryFile) {
                          value =
                              "<a target=\"_blank\" href=\""
                                  + urlDownload
                                  + "\">"
                                  + ref.getRefRepository().getTitle()
                                  + " <i class=\"fa fa-download\"></i></a>";
                        } else if (re instanceof RepositoryURL) {
                          value =
                              "<a target=\"_blank\" href=\""
                                  + vi.getVersionFile()
                                  + "\">"
                                  + ref.getRefRepository().getTitle()
                                  + " <i class=\"fa fa-external-link\"></i></a>";
                        }
                        //                                                if (re instanceof
                        // RepositoryFile) {
                        //                                                    value = "<a href=\"" +
                        // urld + "\">" + ref.getRefRepository().getTitle() + " <i class=\"fa
                        // fa-download\"></i></a>";
                        //                                                } else if (re instanceof
                        // RepositoryURL) {
                        //                                                    value = "<a
                        // target=\"_blank\" href=\"" + vi.getVersionFile() + "\">" +
                        // ref.getRefRepository().getTitle() + " <i class=\"fa
                        // fa-external-link\"></i></a>";
                        //                                                }
                      }
                      erprop.appendChild(doc.createTextNode(value));
                    }
                  }
                }
              }
            }
            if (addInstance) {
              instance.setAttribute("count", count + "");
              count++;
              section.appendChild(instance);
            }
          }
        }
      }
      if (hasModel) {
        Process process = getProcessRef();
        Element model = doc.createElement("model");
        model.setAttribute("id", process.getId());
        root.appendChild(doc.createTextNode("\n\t"));
        String data = process.getData();
        model.appendChild(doc.createTextNode(data));
        root.appendChild(model);
        root.appendChild(doc.createTextNode("\n\t"));
        if (colorTask.length() > 0) {
          Element colorTaskE = doc.createElement("colorTask");
          root.appendChild(doc.createTextNode("\n\t"));

          String[] tasks = colorTask.split("\\|");
          int i = 1;
          String script = "<script>" + "$(document).ready(function(){";
          for (String task : tasks) {
            script +=
                "var colorTask"
                    + i
                    + " = $(document.getElementById('"
                    + task.substring(0, task.lastIndexOf(";"))
                    + "')).attr('style', 'fill:#"
                    + task.substring(task.lastIndexOf(";") + 1, task.length())
                    + "');";
            i++;
          }
          script += "});" + "</script>";
          colorTaskE.appendChild(doc.createTextNode(script + "\n\t\t"));
          root.appendChild(colorTaskE);
          root.appendChild(doc.createTextNode("\n\t"));
        }
      }

    } catch (DOMException doe) {
      log.error("Error on getDocument, DOMEXception" + doe);
    } catch (IOException ioe) {
      log.error("Error on getDocument, IOEXception" + ioe);
    }

    //        try {
    //            // Use a Transformer for output
    //            TransformerFactory tFactory = TransformerFactory.newInstance();
    //            Transformer transformer = tFactory.newTransformer();
    //
    //            DOMSource source = new DOMSource(doc);
    //            StreamResult result = new StreamResult(new FileOutputStream(new
    // File("/Users/hasdai/Documents/xmlDocumentation.xml")));
    //            transformer.transform(source, result);
    //        } catch (Exception ex) {
    //
    //        }

    return doc;
  }
  /**
   * Obtiene la instancia de documentación asociada al proceso especificado.
   *
   * @param process Proceso de interés
   * @param container Contenedor de versiones de la documentación asociado al proceso.
   * @return Instancia de la documentación del proceso especificado.
   */
  public static DocumentationInstance getDocumentationInstanceByProcess(
      Process process, TemplateContainer container) {
    DocumentationInstance di = null;
    ProcessSite model = process.getProcessSite();
    DocumentTemplate dt = container.getActualTemplate();
    Iterator<DocumentationInstance> itdi =
        DocumentationInstance.ClassMgr.listDocumentationInstanceByProcessRef(process);
    if (itdi.hasNext()) { // Obtener DocumentationInstance de plantilla actual
      while (itdi.hasNext()) {
        DocumentationInstance dit = itdi.next();
        if (dit.getDocTypeDefinition() != null
            && dt != null
            && dit.getDocTypeDefinition().getURI().equals(dt.getURI())) {
          di = dit;
          Map map = getDocumentSectionInstanceMap(di);
          Iterator<DocumentSection> itds = di.getDocTypeDefinition().listDocumentSections();
          while (itds.hasNext()) {
            DocumentSection ds = itds.next();
            if (!map.containsKey(ds.getURI())) {
              DocumentSectionInstance dsi =
                  DocumentSectionInstance.ClassMgr.createDocumentSectionInstance(model);
              dsi.setSecTypeDefinition(ds);
              dsi.setDocumentationInstance(dit);
              di.addDocumentSectionInstance(dsi);
              dsi.setIndex(ds.getIndex());

              SemanticClass cls =
                  SWBPlatform.getSemanticMgr()
                      .getVocabulary()
                      .getSemanticClass(dsi.getSecTypeDefinition().getSectionType().getURI());
              if (FreeText.sclass.getClassId().equals(cls.getClassId())) {
                FreeText ft = FreeText.ClassMgr.createFreeText(model);
                ft.setText("");
                ft.setDocumentTemplate(dt);
                ft.setDocumentSectionInst(dsi);
                SectionElement se = (SectionElement) ft.getSemanticObject().createGenericInstance();
                dsi.addDocuSectionElementInstance(se);
              }
              if (Activity.sclass.getClassId().equals(cls.getClassId())) {
                Iterator<GraphicalElement> itge = di.getProcessRef().listAllContaineds();
                while (itge.hasNext()) {
                  GraphicalElement ge = itge.next();
                  if (ge instanceof org.semanticwb.process.model.SubProcess || ge instanceof Task) {
                    String urige = ge.getURI();
                    org.semanticwb.process.model.Activity act =
                        (org.semanticwb.process.model.Activity)
                            SWBPlatform.getSemanticMgr().getOntology().getGenericObject(urige);
                    ActivityRef actRef = ActivityRef.ClassMgr.createActivityRef(model);
                    actRef.setProcessActivity(act);
                    Activity actFin = Activity.ClassMgr.createActivity(model);
                    actFin.setTitle(act.getTitle());
                    actFin.setDocumentTemplate(dt);
                    actFin.setActivityRef(actRef);
                    actFin.setIndex(ge.getIndex());
                    actFin.setDocumentSectionInst(dsi);
                    dsi.addDocuSectionElementInstance(actFin);
                  }
                }
              }
            }
          }
          break;
        }
      }
    }

    if (di == null) { // Crear DocumentationInstance
      di = DocumentationInstance.ClassMgr.createDocumentationInstance(process.getProcessSite());
      di.setDocTypeDefinition(dt);
      di.setProcessRef(process);

      Iterator<DocumentSection> itdsi = di.getDocTypeDefinition().listDocumentSections();
      while (itdsi.hasNext()) {
        DocumentSection ds = itdsi.next();
        DocumentSectionInstance dsi =
            DocumentSectionInstance.ClassMgr.createDocumentSectionInstance(model);
        dsi.setSecTypeDefinition(ds);
        dsi.setDocumentationInstance(di);
        di.addDocumentSectionInstance(dsi);
        dsi.setIndex(ds.getIndex());

        SemanticClass cls =
            SWBPlatform.getSemanticMgr()
                .getVocabulary()
                .getSemanticClass(dsi.getSecTypeDefinition().getSectionType().getURI());
        if (FreeText.sclass.getClassId().equals(cls.getClassId())) {
          FreeText ft = FreeText.ClassMgr.createFreeText(model);
          ft.setText("");
          dsi.addDocuSectionElementInstance(ft);
          ft.setParentSection(ds);
          ft.setDocumentTemplate(dt);
          ft.setDocumentSectionInst(dsi);
        }
        if (Activity.sclass.getClassId().equals(cls.getClassId())) {
          Iterator<GraphicalElement> itge = di.getProcessRef().listAllContaineds();
          while (itge.hasNext()) {
            GraphicalElement ge = itge.next();
            if (ge instanceof org.semanticwb.process.model.SubProcess || ge instanceof Task) {
              String urige = ge.getURI();
              org.semanticwb.process.model.Activity act =
                  (org.semanticwb.process.model.Activity)
                      SWBPlatform.getSemanticMgr().getOntology().getGenericObject(urige);

              ActivityRef actRef = ActivityRef.ClassMgr.createActivityRef(model);
              actRef.setProcessActivity(act);
              Activity actFin = Activity.ClassMgr.createActivity(model);
              actFin.setTitle(act.getTitle());
              actFin.setDocumentTemplate(dt);
              actFin.setActivityRef(actRef);
              actFin.setIndex(ge.getIndex());
              dsi.addDocuSectionElementInstance(actFin);
              actFin.setParentSection(ds);
              actFin.setDocumentSectionInst(dsi);
            }
          }
        }
      }
    }
    return di;
  }
Beispiel #3
0
  @Override
  public void write(OutputStream ous) {
    WordprocessingMLPackage doc;

    try {
      doc = WordprocessingMLPackage.createPackage();
      MainDocumentPart content = doc.getMainDocumentPart();

      // Create header and footer
      createHeader(doc);
      createFooter(doc);

      // Add first page
      P docTitle = content.addStyledParagraphOfText("Heading1", p.getTitle());
      alignParagraph(docTitle, JcEnumeration.CENTER);
      addPageBreak(content);

      // Add sections
      Iterator<DocumentSectionInstance> itdsi =
          SWBComparator.sortSortableObject(di.listDocumentSectionInstances());
      while (itdsi.hasNext()) {
        DocumentSectionInstance dsi = itdsi.next();
        SemanticClass cls =
            dsi.getSecTypeDefinition() != null
                    && dsi.getSecTypeDefinition().getSectionType() != null
                ? dsi.getSecTypeDefinition().getSectionType().transformToSemanticClass()
                : null;

        if (null == cls || !dsi.getSecTypeDefinition().isActive()) continue;

        // Add section title
        content.addStyledParagraphOfText("Heading2", dsi.getSecTypeDefinition().getTitle());

        // Gather sectionElement instances
        Iterator<SectionElement> itse =
            SWBComparator.sortSortableObject(dsi.listDocuSectionElementInstances());
        List<SectionElement> sectionElementInstances = new ArrayList<SectionElement>();
        while (itse.hasNext()) {
          SectionElement se = itse.next();
          sectionElementInstances.add(se);
        }

        if (cls.isSubClass(Instantiable.swpdoc_Instantiable, false)) {
          // Get visible props from config
          String[] props = dsi.getSecTypeDefinition().getVisibleProperties().split("\\|");

          // Add properties table
          if (props.length > 0 && !sectionElementInstances.isEmpty()) {
            int writableWidthTwips =
                doc.getDocumentModel()
                    .getSections()
                    .get(0)
                    .getPageDimensions()
                    .getWritableWidthTwips();
            int cellWidthTwips =
                new Double(Math.floor((writableWidthTwips / props.length))).intValue();

            Tbl propsTable =
                TblFactory.createTable(
                    sectionElementInstances.size() + 1, props.length, cellWidthTwips);
            setStyle(propsTable, "TableGrid");

            // Add table header
            Tr headerRow = (Tr) propsTable.getContent().get(0);
            int c = 0;
            for (String prop : props) {
              Tc col = (Tc) headerRow.getContent().get(c++);
              P colContent = objectFactory.createP(); // (P) col.getContent().get(0);
              TcPr cellProps = col.getTcPr();
              cellProps.getTcW().setType(TblWidth.TYPE_DXA);

              Text colText = objectFactory.createText();
              colText.setValue(prop.substring(0, prop.indexOf(";")));
              R colRun = objectFactory.createR();
              colRun.getContent().add(colText);

              setFontStyle(colRun, false, true);

              colContent.getContent().add(colRun);
              col.getContent().set(0, colContent);
              // alignParagraph(colContent, JcEnumeration.CENTER);
              // fillTableCell(col);
            }

            // Add rows
            int r = 1;
            for (SectionElement se : sectionElementInstances) {
              Tr row = (Tr) propsTable.getContent().get(r++);
              c = 0;
              for (String prop : props) {
                Tc col = (Tc) row.getContent().get(c++);
                String idProperty = prop.substring(prop.indexOf(";") + 1, prop.length());
                SemanticProperty sprop =
                    SWBPlatform.getSemanticMgr()
                        .getVocabulary()
                        .getSemanticPropertyById(idProperty);
                P colContent;

                if (null == sprop) {
                  colContent = content.createParagraphOfText("");
                } else {
                  if (!sprop.getPropId().equals(Referable.swpdoc_file.getPropId())) {
                    colContent =
                        content.createParagraphOfText(
                            se.getSemanticObject().getProperty(sprop) != null
                                ? se.getSemanticObject().getProperty(sprop)
                                : "");
                  } else {
                    colContent = content.createParagraphOfText(se.getTitle());
                  }
                }
                col.getContent().set(0, colContent);
                alignParagraph(colContent, JcEnumeration.BOTH);
                setStyle(colContent, "Normal");
              }
            }

            // Add table to document
            content.addObject(propsTable);
          }
        } else if (cls.equals(FreeText.sclass)) {
          XHTMLImporterImpl importer = new XHTMLImporterImpl(doc);
          for (SectionElement se : sectionElementInstances) {
            FreeText freeText = (FreeText) se;
            if (null != se) {
              String sContent = freeText.getText();
              if (null != sContent && !sContent.isEmpty()) {
                sContent =
                    sContent.replace(
                        "<!DOCTYPE html>",
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
                sContent =
                    sContent.replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">");

                // Override styles and alignment
                List<Object> objects = importer.convert(sContent, null);
                for (Object o : objects) {
                  if (o instanceof Tbl) setStyle((Tbl) o, "TableGrid");
                  if (o instanceof P) {
                    // Fix harcoded runProperties
                    List<Object> pChilds = ((P) o).getContent();
                    for (Object child : pChilds) {
                      if (child instanceof R) {
                        // ((R)child).setRPr(objectFactory.createRPr());
                        RPr rpr = ((R) child).getRPr();
                        if (null != rpr) {
                          rpr.getRFonts().setAsciiTheme(null);
                          rpr.getRFonts().setAscii(null);
                          rpr.getRFonts().setHAnsiTheme(null);
                          rpr.getRFonts().setHAnsi(null);
                        }
                      }
                    }
                    alignParagraph((P) o, JcEnumeration.BOTH);
                    setStyle((P) o, "Normal");
                  }
                }
                content.getContent().addAll(objects);
              }
            }
          }
        } else if (cls.equals(Activity.sclass)) {
          for (SectionElement se : sectionElementInstances) {
            Activity a = (Activity) se;
            if (a.getDescription() != null && !a.getDescription().isEmpty()) {
              XHTMLImporterImpl importer = new XHTMLImporterImpl(doc);
              content.addStyledParagraphOfText("Heading3", a.getTitle());

              String sContent = a.getDescription();
              if (null != sContent && !sContent.isEmpty()) {
                sContent =
                    sContent.replace(
                        "<!DOCTYPE html>",
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
                sContent =
                    sContent.replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">");

                // Override styles and alignment
                List<Object> objects = importer.convert(sContent, null);
                for (Object o : objects) {
                  if (o instanceof Tbl) setStyle((Tbl) o, "TableGrid");
                  if (o instanceof P) {
                    // Fix harcoded runProperties
                    List<Object> pChilds = ((P) o).getContent();
                    for (Object child : pChilds) {
                      if (child instanceof R) {
                        // ((R)child).setRPr(null);
                        RPr rpr = ((R) child).getRPr();
                        if (null != rpr) {
                          rpr.getRFonts().setAsciiTheme(null);
                          rpr.getRFonts().setAscii(null);
                          rpr.getRFonts().setHAnsiTheme(null);
                          rpr.getRFonts().setHAnsi(null);
                        }
                      }
                    }
                    alignParagraph((P) o, JcEnumeration.BOTH);
                    setStyle((P) o, "Normal");
                  }
                }
                content.getContent().addAll(objects);
              }
            }
          }
        } else if (cls.equals(Model.sclass)) {
          File img = new File(assetsPath + "/" + p.getId() + ".png");
          if (img.exists()) {
            FileInputStream fis = new FileInputStream(img);
            long length = img.length();

            if (length > Integer.MAX_VALUE) {
              log.error("File too large in model generation");
            } else {
              // Read image bytes
              byte[] bytes = new byte[(int) length];
              int offset = 0;
              int numRead = 0;
              while (offset < bytes.length
                  && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
              }

              if (offset < bytes.length) {
                log.error("Could not completely read file " + img.getName());
              }

              fis.close();

              // Generate ImagePart
              BinaryPartAbstractImage imagePart =
                  BinaryPartAbstractImage.createImagePart(doc, bytes);
              Inline inline = imagePart.createImageInline("", "", 0, 1, false);

              // Add image to paragraph
              P p = objectFactory.createP();
              R run = objectFactory.createR();
              p.getContent().add(run);
              Drawing drawing = objectFactory.createDrawing();
              run.getContent().add(drawing);
              drawing.getAnchorOrInline().add(inline);
              content.getContent().add(p);
            }
          }
        }
        addPageBreak(content);
      }
      doc.save(ous);
    } catch (Docx4JException | FileNotFoundException ex) {
      log.error("Error creating DOCX document", ex);
    } catch (IOException ex) {
      log.error("Error creating DOCX document", ex);
    } catch (Exception ex) {
      log.error("Error creating DOCX document", ex);
    }
  }
 /**
  * Returns a list of org.semanticwb.process.model.WebServiceParameter for all models
  *
  * @return Iterator of org.semanticwb.process.model.WebServiceParameter
  */
 public static java.util.Iterator<org.semanticwb.process.model.WebServiceParameter>
     listWebServiceParameters() {
   java.util.Iterator it = sclass.listInstances();
   return new org.semanticwb.model.GenericIterator<
       org.semanticwb.process.model.WebServiceParameter>(it, true);
 }
 /**
  * Returns a list of org.semanticwb.process.model.ExclusiveGateway for all models
  *
  * @return Iterator of org.semanticwb.process.model.ExclusiveGateway
  */
 public static java.util.Iterator<org.semanticwb.process.model.ExclusiveGateway>
     listExclusiveGateways() {
   java.util.Iterator it = sclass.listInstances();
   return new org.semanticwb.model.GenericIterator<
       org.semanticwb.process.model.ExclusiveGateway>(it, true);
 }
 /**
  * Returns a list of org.semanticwb.process.model.ParallelIntermediateCatchEvent for all models
  *
  * @return Iterator of org.semanticwb.process.model.ParallelIntermediateCatchEvent
  */
 public static java.util.Iterator<org.semanticwb.process.model.ParallelIntermediateCatchEvent>
     listParallelIntermediateCatchEvents() {
   java.util.Iterator it = sclass.listInstances();
   return new org.semanticwb.model.GenericIterator<
       org.semanticwb.process.model.ParallelIntermediateCatchEvent>(it, true);
 }