コード例 #1
0
ファイル: DOCXWriter.java プロジェクト: haxdai/SWBPDocumenter
/** @author hasdai */
public class DOCXWriter implements DocumentWriter {
  private static final Logger log = SWBUtils.getLogger(DOCXWriter.class);
  private static final ObjectFactory objectFactory = new ObjectFactory();
  private final DocumentationInstance di;
  private final org.semanticwb.process.model.Process p;
  private final ProcessSite model;
  private final String assetsPath;

  /**
   * Creates a new DOCXWriter for the specified DocumentationInstance object.
   *
   * @param di DocumentationInstance object
   * @param assetsPath Path to additional assets required in docx generation.
   */
  public DOCXWriter(DocumentationInstance di, String assetsPath) {
    this.di = di;
    this.p = di.getProcessRef();
    this.model = p.getProcessSite();
    this.assetsPath = assetsPath;
  }

  @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);
    }
  }

  /**
   * Sets style of paragraph
   *
   * @param paragraph Paragraph to style
   * @param styleName Style name
   */
  private void setStyle(ContentAccessor element, String styleName) {
    if (element instanceof P) {
      PPrBase.PStyle style = objectFactory.createPPrBasePStyle();
      style.setVal(styleName);

      PPr ppr = objectFactory.createPPr();
      ppr.setPStyle(style);
      ((P) element).setPPr(ppr);
    } else if (element instanceof Tbl) {
      TblPr.TblStyle style = objectFactory.createCTTblPrBaseTblStyle();
      style.setVal(styleName);

      TblPr tpr = objectFactory.createTblPr();
      CTTblLook tblLook = objectFactory.createCTTblLook();
      tblLook.setFirstColumn(STOnOff.FALSE);
      tblLook.setFirstRow(STOnOff.TRUE);
      tblLook.setLastColumn(STOnOff.FALSE);
      tblLook.setLastRow(STOnOff.FALSE);
      tblLook.setNoHBand(STOnOff.FALSE);
      tblLook.setNoVBand(STOnOff.TRUE);
      tpr.setTblLook(tblLook);

      tpr.setTblStyle(style);
      ((Tbl) element).setTblPr(tpr);
    }
  }

  /**
   * Fija la alineación de un párrafo
   *
   * @param paragraph Párrafo a alinear
   * @param alignment Valor de alineamiento
   */
  private void alignParagraph(P paragraph, JcEnumeration alignment) {
    PPr parProps = paragraph.getPPr();
    if (null == parProps) parProps = objectFactory.createPPr();
    Jc al = objectFactory.createJc();
    al.setVal(alignment);
    parProps.setJc(al);

    paragraph.setPPr(parProps);
  }

  /**
   * Sets font style (bold/italic) for a paragraph run
   *
   * @param runElement Run
   * @param italic wheter to set italic style
   * @param bold wheter to set bold style
   */
  private void setFontStyle(R runElement, boolean italic, boolean bold) {
    RPr runProps = runElement.getRPr();
    if (null == runProps) runProps = objectFactory.createRPr();
    if (italic) runProps.setI(objectFactory.createBooleanDefaultTrue());
    if (bold) runProps.setB(objectFactory.createBooleanDefaultTrue());

    runElement.setRPr(runProps);
  }

  /**
   * Fills table cell with given hex color
   *
   * @param cell
   * @param hexColor
   */
  private void fillTableCell(Tc cell, String hexColor) {
    TcPr cellProps = cell.getTcPr();
    if (null == cellProps) cellProps = objectFactory.createTcPr();
    CTShd shd = objectFactory.createCTShd();
    shd.setFill(hexColor);
    shd.setThemeFill(STThemeColor.BACKGROUND_2);
    cellProps.setShd(shd);
    cell.setTcPr(cellProps);
  }

  /**
   * Adds page break to document
   *
   * @param content Document's main part
   * @throws Docx4JException
   */
  private void addPageBreak(MainDocumentPart content) throws Docx4JException {
    Br breakObj = objectFactory.createBr();
    breakObj.setType(STBrType.PAGE);

    P paragraph = objectFactory.createP();
    paragraph.getContent().add(breakObj);
    content.getContents().getBody().getContent().add(paragraph);
  }

  /**
   * Creates document footer including page number
   *
   * @param doc WordprocessingMLPackage for the document.
   * @throws InvalidFormatException
   */
  private void createFooter(WordprocessingMLPackage doc) throws InvalidFormatException {
    MainDocumentPart content = doc.getMainDocumentPart();

    // Create footer
    FooterPart footer = new FooterPart();

    Ftr ftr = objectFactory.createFtr();
    P footerParagraph = objectFactory.createP();

    setStyle(footerParagraph, "footer");

    PPr parProps = objectFactory.createPPr();
    Jc al = objectFactory.createJc();
    al.setVal(JcEnumeration.RIGHT);
    parProps.setJc(al);
    footerParagraph.setPPr(parProps);

    // Add field start
    R run = objectFactory.createR();
    FldChar fldChar = objectFactory.createFldChar();
    fldChar.setFldCharType(STFldCharType.BEGIN);
    run.getContent().add(fldChar);
    footerParagraph.getContent().add(run);

    // Add pageNumber field
    run = objectFactory.createR();
    Text txt = objectFactory.createText();
    txt.setSpace("preserve");
    txt.setValue(" PAGE   \\* MERGEFORMAT ");
    run.getContent().add(objectFactory.createRInstrText(txt));
    footerParagraph.getContent().add(run);

    // Add field end
    run = objectFactory.createR();
    fldChar = objectFactory.createFldChar();
    fldChar.setFldCharType(STFldCharType.END);
    run.getContent().add(fldChar);
    footerParagraph.getContent().add(run);

    ftr.getContent().add(footerParagraph);
    footer.setJaxbElement(ftr);

    Relationship rel = content.addTargetPart(footer);

    // Relate footer to document
    List<SectionWrapper> sections = doc.getDocumentModel().getSections();

    SectPr sectPr = sections.get(sections.size() - 1).getSectPr();

    if (null == sectPr) {
      sectPr = objectFactory.createSectPr();
      content.addObject(sectPr);
      sections.get(sections.size() - 1).setSectPr(sectPr);
    }

    FooterReference footerReference = objectFactory.createFooterReference();
    footerReference.setId(rel.getId());
    footerReference.setType(HdrFtrRef.DEFAULT);
    sectPr.getEGHdrFtrReferences().add(footerReference);
  }

  /**
   * Creates document header including process name
   *
   * @param doc WordprocessingMLPackage for the document.
   * @throws InvalidFormatException
   */
  private void createHeader(WordprocessingMLPackage doc) throws InvalidFormatException {
    MainDocumentPart content = doc.getMainDocumentPart();

    // Create header
    HeaderPart header = new HeaderPart();
    Relationship rel = content.addTargetPart(header);

    Hdr hdr = objectFactory.createHdr();

    P headerParagraph = content.createParagraphOfText(p.getTitle());
    hdr.getContent().add(headerParagraph);
    header.setJaxbElement(hdr);

    setStyle(headerParagraph, "Header");
    alignParagraph(headerParagraph, JcEnumeration.CENTER);

    // Relate to document
    List<SectionWrapper> sections = doc.getDocumentModel().getSections();
    SectPr sectPr = sections.get(sections.size() - 1).getSectPr();

    if (null == sectPr) {
      sectPr = objectFactory.createSectPr();
      content.addObject(sectPr);
      sections.get(sections.size() - 1).setSectPr(sectPr);
    }

    HeaderReference headerReference = objectFactory.createHeaderReference();
    headerReference.setId(rel.getId());
    headerReference.setType(HdrFtrRef.DEFAULT);
    sectPr.getEGHdrFtrReferences().add(headerReference);
  }

  @Override
  public void write(String path) throws FileNotFoundException {
    write(new FileOutputStream(path));
  }
}
コード例 #2
0
/**
 * Clase que encapsula las propiedades de una instancia particular de la documentación de un
 * proceso.
 */
public class DocumentationInstance
    extends org.semanticwb.process.documentation.model.base.DocumentationInstanceBase {
  private static final Logger log = SWBUtils.getLogger(DocumentationInstance.class);
  /**
   * Constructor.
   *
   * @param base
   */
  public DocumentationInstance(org.semanticwb.platform.SemanticObject base) {
    super(base);
  }

  /**
   * Obtiene un mapa con las instancias de secciones asociadas a una instancia de documentación.
   *
   * @param instance Instancia de documentación.
   * @return Mapa con instancias de recciones asociadas a la instancia de documentación.
   */
  public static Map getDocumentSectionInstanceMap(DocumentationInstance instance) {
    Map map = new HashMap();
    Iterator<DocumentSectionInstance> itdsi = instance.listDocumentSectionInstances();
    while (itdsi.hasNext()) {
      DocumentSectionInstance dsit = itdsi.next();
      DocumentSection ds = dsit.getSecTypeDefinition();
      if (null != ds) {
        dsit.setIndex(ds.getIndex());
        map.put(dsit.getSecTypeDefinition().getURI(), dsit.getURI());
      } else {
        dsit.remove();
      }
    }
    return map;
  }

  //    public static DocumentationInstance createDocumentSectionInstance(ProcessSite model,
  // DocumentTemplate template, org.semanticwb.process.model.Process process) {
  //        //Crea una nueva instancia de documentación
  //        DocumentationInstance di =
  // DocumentationInstance.ClassMgr.createDocumentationInstance(model);
  //        di.setDocTypeDefinition(template);
  //        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);
  //            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(template);
  //            }
  //            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(template);
  ////                        actFin.setDescription(act.getDescription());
  //                        actFin.setActivityRef(actRef);
  //                        actFin.setIndex(ge.getIndex());
  //                        dsi.addDocuSectionElementInstance(actFin);
  //                        actFin.setParentSection(ds);
  //                    }
  //                }
  //            }
  //        }
  //        return di;
  //    }

  //    public static ArrayList listDocumentSections(DocumentTemplate dt, Map map,
  // DocumentationInstance di, ProcessSite model, String clsuri) {
  //        Iterator<DocumentSection> itdst =
  // SWBComparator.sortSemanticObjects(dt.listDocumentSections());
  //        ArrayList arr = new ArrayList();
  //        int i = 0;
  //        while (itdst.hasNext()) {
  //            DocumentSection dst = itdst.next();
  //            if (dst.isActive()) {
  //                SemanticClass semcls =
  // SWBPlatform.getSemanticMgr().getVocabulary().getSemanticClass(dst.getSectionType().getURI());
  //                if (!clsuri.contains(semcls.getClassId())) {
  //                    if (!map.containsKey(dst.getURI())) {
  //                        DocumentSectionInstance dsin =
  // DocumentSectionInstance.ClassMgr.createDocumentSectionInstance(model);
  //                        dsin.setSecTypeDefinition(dst);
  //                        dsin.setDocumentationInstance(di);
  //                        di.addDocumentSectionInstance(dsin);
  //                        SemanticClass cls =
  // SWBPlatform.getSemanticMgr().getVocabulary().getSemanticClass(dsin.getSecTypeDefinition().getSectionType().getURI());
  //                        if (FreeText.sclass.getClassId().equals(cls.getClassId())) {
  //                            FreeText ft = FreeText.ClassMgr.createFreeText(model);
  //                            ft.setText("");
  //                            ft.setDocumentTemplate(dt);
  //                            SectionElement se = (SectionElement)
  // ft.getSemanticObject().createGenericInstance();
  //                            dsin.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.setDescription(act.getDescription());
  //                                    actFin.setActivityRef(actRef);
  //                                    actFin.setIndex(ge.getIndex());
  //                                    dsin.addDocuSectionElementInstance(actFin);
  //                                    actFin.setParentSection(dst);
  //                                }
  //                            }
  //                        }
  //                        arr.add(i, dsin.getURI());
  //                    } else {
  //                        arr.add(i, map.get(dst.getURI()));
  //                    }
  //                    i++;
  //                }
  //            }
  //        }
  //        return arr;
  //    }

  //    public static ArrayList listDocumentSectionsForPE(DocumentTemplate dt, Map map,
  // DocumentationInstance di, ProcessSite model, String clsuri) {
  //        Iterator<DocumentSection> itdst =
  // SWBComparator.sortSortableObject(dt.listDocumentSections());
  //        ArrayList arr = new ArrayList();
  //        int i = 0;
  //        Iterator<DocumentSectionInstance> itdsi =
  // SWBComparator.sortSortableObject(di.listDocumentSectionInstances());
  //        while (itdsi.hasNext()) {
  //            DocumentSectionInstance dsi = itdsi.next();
  //            SemanticClass semcls =
  // SWBPlatform.getSemanticMgr().getVocabulary().getSemanticClass(dsi.getSecTypeDefinition().getSectionType().getURI());
  //            if (!clsuri.contains(semcls.getClassId())) {
  //                if (dsi.listDocuSectionElementInstances().hasNext()) {
  //                    DocumentSection documentSection = dsi.getSecTypeDefinition();
  //                    if (!map.containsKey(documentSection.getURI())) {
  //                        arr.add(i, itdst);
  //                    } else {
  //                        arr.add(i, map.get(documentSection.getURI()));
  //                    }
  //                    i++;
  //                }
  //            }
  //        }
  //        return arr;
  //    }

  //    public static void verifyActivitiesOfProcess(List<GraphicalElement> list, WebSite model,
  // DocumentSectionInstance dsi, org.semanticwb.process.model.Process process, DocumentTemplate dt)
  // {
  //
  //        Iterator<GraphicalElement> itge = process.listAllContaineds();
  //        while (itge.hasNext()) {
  //            GraphicalElement ge = itge.next();
  //            if ((ge instanceof org.semanticwb.process.model.SubProcess || ge instanceof Task)) {
  //                if (!list.contains(ge)) {
  //                    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.setDocumentTemplate(dt);
  //                    actFin.setTitle(act.getTitle());
  ////                    actFin.setDescription(act.getDescription());
  //                    actFin.setActivityRef(actRef);
  //                    actFin.setIndex(ge.getIndex());
  //                    dsi.addDocuSectionElementInstance(actFin);
  //                    actFin.setParentSection(dsi.getSecTypeDefinition());
  //                }
  //            }
  //        }
  //    }

  /**
   * 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;
  }

  /**
   * Actualiza la información asociada a las actividades de un proceso documentado.
   *
   * @param process Proceso asociado a la documentación.
   * @param container Contenedor de versiones asociado al proceso.
   * @param instance Instancia de la sección de actividades en la documentación.
   */
  public static void updateActivityFromProcess(
      Process process, TemplateContainer container, DocumentSectionInstance instance) {
    Iterator<SectionElement> itse =
        SWBComparator.sortSortableObject(instance.listDocuSectionElementInstances());
    List<GraphicalElement> listPa = new ArrayList<GraphicalElement>();
    while (itse.hasNext()) {
      SectionElement se = itse.next();
      Activity act = (Activity) se.getSemanticObject().createGenericInstance();
      if (act.getActivityRef().getProcessActivity() != null) {
        act.setTitle(act.getActivityRef().getProcessActivity().getTitle());
        act.setIndex(act.getActivityRef().getProcessActivity().getIndex());
        act.setParentSection(instance.getSecTypeDefinition());
        listPa.add(act.getActivityRef().getProcessActivity());
      } else {
        se.remove();
        instance.removeDocuSectionElementInstance(se);
      }
    }
    ProcessSite model = process.getProcessSite();
    DocumentTemplate dt = container.getActualTemplate();
    Iterator<GraphicalElement> itge = process.listAllContaineds();
    while (itge.hasNext()) {
      GraphicalElement ge = itge.next();
      if ((ge instanceof SubProcess || ge instanceof Task)) {
        if (!listPa.contains(ge)) {
          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.setDocumentTemplate(dt);
          actFin.setTitle(act.getTitle());
          actFin.setActivityRef(actRef);
          actFin.setIndex(ge.getIndex());
          actFin.setDocumentSectionInst(instance);
          instance.addDocuSectionElementInstance(actFin);
          actFin.setParentSection(instance.getSecTypeDefinition());
        }
      }
    }
  }

  /**
   * 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;
  }
}
コード例 #3
0
ファイル: SWBEmbedWidget.java プロジェクト: dnlmx/SWBEmbed
/** @author daniel.martinez */
public class SWBEmbedWidget extends GenericAdmResource {
  private static Logger log = SWBUtils.getLogger(SWBEmbedWidget.class);
  private PrintWriter out = null;

  @Override
  public void doView(
      HttpServletRequest request, HttpServletResponse response, SWBParamRequest paramsRequest)
      throws SWBResourceException {
    try {
      VelocityContext context = new VelocityContext();
      Resource base = paramsRequest.getResourceBase();
      String idPage = base.getAttribute("sitePage", base.getWebSite().getHomePage().getId());

      WebPage selPage = base.getWebSite().getWebPage(idPage);
      Iterator<WebPage> childs = selPage.listChilds("es", true, false, false, true, true);
      List<WebPage> ochilds = new ArrayList<WebPage>();
      while (childs.hasNext()) {
        WebPage child = childs.next();
        ochilds.add(child);
      }

      context.put("childs", ochilds);
      context.put("urlPage", selPage.getUrl());
      context.put("pageItems", base.getAttribute("pageItems", "0"));
      context.put("newWindow", base.getAttribute("newWindow", "0"));

      SWBEmbedTemplates.buildTemplate(response, context, "SWBEmbedWidget", base);

    } catch (Exception e) {
      log.error("Ocurrió un error en la construcción de la vista del recurso:\n " + e.getMessage());
      log.error(SWBEmbed.getStack(e));
      e.printStackTrace();
    }
  }

  @Override
  public void doAdmin(
      HttpServletRequest request, HttpServletResponse response, SWBParamRequest paramReq) {
    SWBResourceURL url = paramReq.getActionUrl();
    Resource base = getResourceBase();
    try {
      VelocityContext context = new VelocityContext();
      WebPage hp = base.getWebSite().getHomePage();
      LinkedHashMap<String, String> pages = SWBEmbedPages.getPages(hp, "-");
      context.put("pages", pages);
      context.put("actionURL", url);

      context.put("msg", request.getParameter("msg"));
      context.put("sitePage", base.getAttribute("sitePage", "0"));
      context.put("pageItems", base.getAttribute("pageItems", "0"));
      context.put("newWindow", base.getAttribute("newWindow", "0"));
      SWBEmbedTemplates.buildTemplate(response, context, "SWBEmbedWidgetAdmin", base);
    } catch (Exception e) {
      log.error(
          "Ocurrió un error durante la construcción de la vista de administración. "
              + e.getMessage());
      e.printStackTrace();
    }
  }

  @Override
  public void processAction(HttpServletRequest request, SWBActionResponse response)
      throws SWBResourceException, IOException {
    Resource base = getResourceBase();
    try {
      Enumeration names = request.getParameterNames();
      while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        base.setAttribute(name, request.getParameter(name));
      }
      base.updateAttributesToDB();
      response.setRenderParameter("msg", "true");
    } catch (SWBException e) {
      response.setRenderParameter("msg", "false");
      log.error(e);
    }
  }

  @Override
  public void install(ResourceType resourceType) throws SWBResourceException {
    String path = SWBPortal.getWorkPath() + resourceType.getWorkPath();

    // Estableciendo parametros de la instancia
    resourceType.setTitle("SWBEmbedWidget");
    resourceType.setDescription(
        "Recurso que inserta un widget para mostrar un listado de contenidos embebidos. ");
    // resourceType.get
    boolean mkDir = false;

    try {
      mkDir = SWBUtils.IO.createDirectory(path);
    } catch (Exception e) {
      log.error(
          "Error intentando crear directorio base o copiando archivos de trabajo para el recurso SWBEmbedWidget ",
          e);
    }
    if (mkDir) {
      try {
        JarFile thisJar = SWBEmbedUtils.getJarName(SWBEmbedWidget.class);
        if (thisJar != null) {
          try {
            SWBEmbedUtils.copyResourcesToDirectory(thisJar, "com/cap/apps/swbembed/assets", path);
            SWBEmbedUtils.copyResourcesToDirectory(thisJar, "com/cap/apps/swbembedw", path);
          } catch (IOException e) {
            log.error("Error intentando exportar el directorio assets. ", e);
          }
        }
      } catch (Exception e) {
        log.error(
            "Error intentando definir el path del archivo jar de trabajo o exportando directorio de assets. ",
            e);
      }
    }
  }
}