protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");

    String fileType = request.getParameter("fileType");

    ItemVO itemVO = new ItemVO();
    itemVO.setItemClassNo(Integer.valueOf(request.getParameter("itemClassNo")));
    itemVO.setItemNo(Integer.valueOf(request.getParameter("itemNo")));
    itemVO.setItemName(request.getParameter("itemName"));
    itemVO.setDiscount(Double.valueOf(request.getParameter("discount")));
    itemVO.setItemDscrp(request.getParameter("itemDscrp"));
    itemVO.setPrice(Double.valueOf(request.getParameter("price")));
    ExportProcess ep = new ExportProcess();

    if (fileType.equals("doc")) {
      response.setContentType(
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
      XWPFDocument dFile = ep.exportWord(itemVO, request.getHeader("referer"));

      dFile.write(response.getOutputStream());
      return;
    }

    if (fileType.equals("pdf")) {
      response.setContentType("application/pdf");
      ServletOutputStream out = response.getOutputStream();
      Document pdfFile = ep.ExportPDF(itemVO, request.getHeader("referer"), out);

      out.flush();
      out.close();

      return;
    }
  }
  /**
   * 基本的写操作
   *
   * @throws Exception
   */
  public void testSimpleWrite() throws Exception {
    // 新建一个文档
    XWPFDocument doc = new XWPFDocument();
    // 创建一个段落
    XWPFParagraph para = doc.createParagraph();
    XWPFParagraph para1 = doc.createParagraph();

    // 一个XWPFRun代表具有相同属性的一个区域。
    XWPFRun run = para.createRun();
    run.setBold(true); // 加粗
    run.setText("加粗的内容");
    run = para.createRun();
    run.setColor("FF0000");
    run.setText("红色的字。");

    // 一个XWPFRun代表具有相同属性的一个区域。
    XWPFRun runa = para1.createRun();
    runa.setBold(true); // 加粗
    runa.setText("加粗的内容");
    runa = para1.createRun();
    runa.setText("红色的字。");
    OutputStream os = new FileOutputStream(SystemUtil.getSystemPath("testw111notable.docx"));
    // 把doc输出到输出流
    doc.write(os);
    this.close(os);
  }
Esempio n. 3
0
  private void generateWordDoc(String docName) throws FileNotFoundException, IOException {
    XWPFDocument doc = new XWPFDocument();
    for (Theme t : themes) {
      for (Keyword k : t.getKeywords()) {
        for (Occurrence c : k.getOccurrs()) {
          XWPFParagraph p = doc.createParagraph();
          p.setAlignment(ParagraphAlignment.LEFT);
          XWPFRun r = p.createRun();
          setRunAttributes(r);
          r.setText(c.getOccurInfo());
          r.addCarriageReturn();

          String[] strings = c.getSentece().split(k.getName());
          for (int i = 0; i < strings.length; i++) {
            XWPFRun r2 = p.createRun();
            setRunAttributes(r2);
            r2.setText(strings[i]);

            if (i < strings.length - 1) {
              XWPFRun r3 = p.createRun();
              setRunAttributes(r3);
              r3.setBold(true);
              r3.setItalic(true);
              r3.setColor(t.getHexColor());
              r3.setText(k.getName());
            }
          }
        }
      }
    }
    FileOutputStream outStream = new FileOutputStream(docName);
    doc.write(outStream);
    outStream.close();
  }
Esempio n. 4
0
  /*public static void main(String aaa[]){*/
  public boolean writeDataToMSWord(UserResume resumeData) {
    System.out.println("This is Word To Document Class");
    File file = null;
    XWPFDocument document = null;
    XWPFParagraph para = null;
    XWPFRun run = null;

    try {
      // Create the first paragraph and set it's text.
      document = new XWPFDocument();
      para = document.createParagraph();

      para.setAlignment(ParagraphAlignment.CENTER);

      para.setSpacingAfter(100);

      para.setSpacingAfterLines(10);
      run = para.createRun();
      run.addBreak(); // similar to new line
      run.addBreak();

      XWPFTable table = document.createTable(4, 3);
      table.setRowBandSize(1);
      table.setWidth(1);
      table.setColBandSize(1);
      table.setCellMargins(1, 1, 100, 30);

      table.setStyleID("finest");

      table.getRow(1).getCell(1).setText(resumeData.getName());
      table.getRow(2).getCell(1).setText("fine");
      XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0);
      p1.setAlignment(ParagraphAlignment.CENTER);
      XWPFRun r1 = p1.createRun();
      r1.setBold(true);
      r1.setText(resumeData.getInitial());
      r1.setItalic(true);
      r1.setFontFamily("Courier");
      r1.setTextPosition(100);
      table.getRow(0).getCell(0).setText(resumeData.getPhoneNumber());

      table.getRow(0).getCell(2).setText(resumeData.getEmail());
      System.out.println("Email:" + resumeData.getEmail());
      table.getRow(2).getCell(2).setText(resumeData.getAddress());
      table.setWidth(120); // done change from 120 to 200

      file = new File("e:/resume.doc");
      if (file.exists()) file.delete();

      FileOutputStream out = new FileOutputStream(file);
      document.write(out);
      out.close();
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
Esempio n. 5
0
 public void enterText(char c) {
   XWPFParagraph paragraph = document.createParagraph();
   XWPFRun run = paragraph.createRun();
   run.setText(c + "");
   try {
     document.write(out);
     out.close();
   } catch (Exception e) {
   }
 }
 /**
  * * 写一个表格
  *
  * @throws Exception
  */
 public void testWriteTable() throws Exception {
   XWPFDocument doc = new XWPFDocument();
   // 创建一个5行5列的表格
   XWPFTable table = doc.createTable(5, 5);
   // 这里增加的列原本初始化创建的那5行在通过getTableCells()方法获取时获取不到,但通过row新增的就可以。
   // table.addNewCol(); //给表格增加一列,变成6列
   table.createRow(); // 给表格新增一行,变成6行
   List<XWPFTableRow> rows = table.getRows();
   // 表格属性
   CTTblPr tablePr = table.getCTTbl().addNewTblPr();
   // 表格宽度
   CTTblWidth width = tablePr.addNewTblW();
   width.setW(BigInteger.valueOf(8000));
   XWPFTableRow row;
   List<XWPFTableCell> cells;
   XWPFTableCell cell;
   int rowSize = rows.size();
   int cellSize;
   for (int i = 0; i < rowSize; i++) {
     row = rows.get(i);
     // 新增单元格
     row.addNewTableCell();
     // 设置行的高度
     row.setHeight(500);
     // 行属性
     // CTTrPr rowPr = row.getCtRow().addNewTrPr();
     // 这种方式是可以获取到新增的cell的。
     // List<CTTc> list = row.getCtRow().getTcList();
     cells = row.getTableCells();
     cellSize = cells.size();
     for (int j = 0; j < cellSize; j++) {
       cell = cells.get(j);
       if ((i + j) % 2 == 0) {
         // 设置单元格的颜色
         cell.setColor("ff0000"); // 红色
       } else {
         cell.setColor("0000ff"); // 蓝色
       }
       // 单元格属性
       CTTcPr cellPr = cell.getCTTc().addNewTcPr();
       cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
       if (j == 3) {
         // 设置宽度
         cellPr.addNewTcW().setW(BigInteger.valueOf(3000));
       }
       cell.setText(i + ", " + j);
     }
   }
   // 文件不存在时会自动创建
   OutputStream os = new FileOutputStream(SystemUtil.getSystemPath("testw111withtable.docx"));
   // 写入文件
   doc.write(os);
   this.close(os);
 }
Esempio n. 7
0
 /** @param args the command line arguments */
 public void ReadParagraph(String path, String filename) {
   try {
     FileInputStream fis = new FileInputStream(path + filename + ".docx");
     XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
     List<XWPFParagraph> paragraphList = xdoc.getParagraphs();
     for (XWPFParagraph paragraph : paragraphList) {
       System.out.println(paragraph.getText());
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Esempio n. 8
0
  public DocxParser(String path) throws IOException {
    XWPFDocument document = new XWPFDocument(new FileInputStream(path));

    List<XWPFTable> tableList = document.getTables();
    if (tableList.isEmpty()) {
      throw new IOException("Table is not found");
    }
    XWPFTable table = tableList.get(0);
    for (int rowId = 1; rowId < table.getNumberOfRows(); ++rowId) {
      XWPFTableRow row = table.getRow(rowId);
      String email = row.getCell(0).getText();
      String name = row.getCell(1).getText();

      addItem(new Item(email, name));
    }
  }
Esempio n. 9
0
 public void ReadTable(String path, String filename) {
   try {
     FileInputStream fis = new FileInputStream(path + filename + ".docx");
     XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
     Iterator<IBodyElement> bodyElementIterator = xdoc.getBodyElementsIterator();
     while (bodyElementIterator.hasNext()) {
       IBodyElement element = bodyElementIterator.next();
       if ("TABLE".equalsIgnoreCase(element.getElementType().name())) {
         List<XWPFTable> tableList = element.getBody().getTables();
         for (XWPFTable table : tableList) {
           System.out.println("Total Number of Rows of Table:" + table.getNumberOfRows());
           System.out.println(table.getText());
         }
       }
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Esempio n. 10
0
  public static String readFileDocx(String filePath) {

    StringBuilder text = new StringBuilder();
    try {

      FileInputStream fileInputStream = new FileInputStream(new File(filePath));
      XWPFDocument doc = new XWPFDocument(fileInputStream);

      XWPFParagraph[] paragraphs = doc.getParagraphs();
      for (XWPFParagraph paragraph : paragraphs) {
        text.append(" ");
        text.append(paragraph.getText());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return text.toString();
  }
Esempio n. 11
0
File: Main.java Progetto: 8CAKE/ALE
  public void saveDocument(XWPFDocument document, Stage stage) {
    try {
      FileChooser saveDocument = new FileChooser();
      saveDocument.setTitle("Save Document");
      saveDocument
          .getExtensionFilters()
          .add(new FileChooser.ExtensionFilter("Word Document(*.docx)", "*.docx"));
      File file = saveDocument.showSaveDialog(stage);
      document.write(new FileOutputStream(file));

    } catch (IOException ioExcep) {
      System.out.println("<----- IO Exception in Save Document ----->");
      ioExcep.printStackTrace();
      System.out.println("<---------->\n");
    }
  }
Esempio n. 12
0
  public Output() throws Exception {
    // Blank Document
    document = new XWPFDocument();
    // Write the Document in file system
    out = new FileOutputStream(new File("ProjectMOut.docx"));
    document.write(out);
    out.close();

    try {
      if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().open(new File("ProjectMOut.docx"));
      }
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
    /* while(true){
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run=paragraph.createRun();
    run.setText(outputString);
    document.write(out);
    out.close();
    }*/

  }
  /**
   * Tests that parsing errors from AQL template tag (conditional here) are placed next to the start
   * tag. The tested tag is <{m:wrong->.}ajout de value1{m:endif}> The expected tag is :
   * <{m:wrong->.} Expression wrong->. is invalid ajout de value1{m:endif}> After the run with the
   * end '}' char, the following runs must be present : A run must contains blanks char. The next
   * one must contains the error message. The next one must contains blank char and the next one the
   * static content of the conditional.
   *
   * @throws InvalidFormatException
   * @throws IOException
   * @throws DocumentParserException
   * @throws DocumentGenerationException
   */
  @Test
  public void testErrorInStartTag()
      throws InvalidFormatException, IOException, DocumentParserException,
          DocumentGenerationException {
    FileInputStream is = new FileInputStream("templates/testParsingErrorStartTag.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    TemplateValidationGenerator validator = new TemplateValidationGenerator();
    validator.doSwitch(template);
    createDestinationDocument(document, "results/testParsingErrorStartTag.docx");

    // scan the destination document
    assertEquals(2, document.getParagraphs().size());
    assertEquals(16, document.getParagraphs().get(0).getRuns().size());
    assertEquals(1, document.getParagraphs().get(1).getRuns().size());
    assertEquals("    ", document.getParagraphs().get(0).getRuns().get(5).getText(0));
    assertEquals("<---", document.getParagraphs().get(0).getRuns().get(6).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(6).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(6).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document.getParagraphs().get(0).getRuns().get(7).getCTR().getRPr().getHighlight().getVal());
    assertEquals(
        "Expression \"wrong->.\" is invalid: missing collection service call",
        document.getParagraphs().get(0).getRuns().get(7).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(7).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(7).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document.getParagraphs().get(0).getRuns().get(7).getCTR().getRPr().getHighlight().getVal());
    assertEquals("    ", document.getParagraphs().get(0).getRuns().get(8).getText(0));
    assertEquals("ajout de value1", document.getParagraphs().get(0).getRuns().get(9).getText(0));
    assertEquals(
        "Unexpected tag m:endif at this location",
        document.getParagraphs().get(0).getRuns().get(13).getText(0));
  }
 /**
  * Creates a WORD document at the given path and returns the memory representation.
  *
  * @param theDocument
  * @param inputDocumentFilePath
  * @return
  * @throws IOException
  * @throws InvalidFormatException
  */
 private void createDestinationDocument(XWPFDocument theDocument, String inputDocumentFilePath)
     throws IOException, InvalidFormatException {
   FileOutputStream os = new FileOutputStream(inputDocumentFilePath);
   theDocument.write(os);
 }
 /**
  * Tests that parsing errors from AQL template tag (conditional here) are placed next to the start
  * tag when no following text exists. The tested tag is <{m:diagram provider:"noExistingProvider"
  * width:"500" height:"500" title="representationTitle"}> The expected tag is : <{m:diagram
  * provider:"noExistingProvider" width:"500" height:"500" title="representationTitle"}<---The
  * image tag is referencing an unknown diagram provider : 'noExistingProvider' > After the run
  * with the end '}' char, the following runs must be present : A run must contains blanks char.
  * The next one must contains the error message. The next one is a blank separator. The next one
  * must contains the other error message. The next one must contains blank char and the next one
  * the static content after the tag in the original template.
  *
  * @throws InvalidFormatException
  * @throws IOException
  * @throws DocumentParserException
  * @throws DocumentGenerationException
  */
 @Test
 public void testErrorInSimpleTagWithoutFollowing()
     throws InvalidFormatException, IOException, DocumentParserException,
         DocumentGenerationException {
   FileInputStream is =
       new FileInputStream("templates/testParsingErrorSimpleTagWithoutFollowingText.docx");
   OPCPackage oPackage = OPCPackage.open(is);
   XWPFDocument document = new XWPFDocument(oPackage);
   BodyParser parser = new BodyParser(document, env);
   Template template = parser.parseTemplate();
   TemplateValidationGenerator validator = new TemplateValidationGenerator();
   validator.doSwitch(template);
   createDestinationDocument(
       document, "results/testParsingErrorSimpleTagWithoutFollowingText.docx");
   // scan the destination document
   assertEquals(1, document.getParagraphs().size());
   assertEquals(11, document.getParagraphs().get(0).getRuns().size());
   assertEquals("    ", document.getParagraphs().get(0).getRuns().get(2).getText(0));
   assertEquals("<---", document.getParagraphs().get(0).getRuns().get(3).getText(0));
   assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(3).getColor());
   assertEquals(16, document.getParagraphs().get(0).getRuns().get(3).getFontSize());
   assertEquals(
       STHighlightColor.LIGHT_GRAY,
       document.getParagraphs().get(0).getRuns().get(5).getCTR().getRPr().getHighlight().getVal());
   assertEquals(
       "The image tag is referencing an unknown diagram provider : 'noExistingProvider'",
       document.getParagraphs().get(0).getRuns().get(5).getText(0));
   assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(5).getColor());
   assertEquals(16, document.getParagraphs().get(0).getRuns().get(5).getFontSize());
   assertEquals(
       STHighlightColor.LIGHT_GRAY,
       document.getParagraphs().get(0).getRuns().get(5).getCTR().getRPr().getHighlight().getVal());
 }
  /**
   * Tests that parsing errors from AQL template tag (conditional here) are placed next to the start
   * tag. The tested tag is <{m:diagram provider:"noExistingProvider" width:"500" height:"500"
   * title="representationTitle"}Some text> The expected tag is : <{m:diagram
   * provider:"noExistingProvider" width:"500" height:"500" title="representationTitle"}<---The
   * image tag is referencing an unknown diagram provider : 'noExistingProvider' Some text> After
   * the run with the end '}' char, the following runs must be present : A run must contains blanks
   * char. The next one must contains the error message. The next one is a blank separator. The next
   * one must contains the other error message. The next one must contains blank char and the next
   * one the static content after the tag in the original template.
   *
   * @throws InvalidFormatException
   * @throws IOException
   * @throws DocumentParserException
   * @throws DocumentGenerationException
   */
  @Test
  public void testErrorInEndTag()
      throws InvalidFormatException, IOException, DocumentParserException,
          DocumentGenerationException {
    FileInputStream is = new FileInputStream("templates/testParsingErrorEndTag.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    TemplateValidationGenerator validator = new TemplateValidationGenerator();
    validator.doSwitch(template);
    createDestinationDocument(document, "results/testParsingErrorEndTag.docx");
    // scan the destination document
    assertEquals(1, document.getParagraphs().size());
    assertEquals(24, document.getParagraphs().get(0).getRuns().size());
    assertEquals("    ", document.getParagraphs().get(0).getRuns().get(9).getText(0));
    assertEquals("<---", document.getParagraphs().get(0).getRuns().get(10).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(10).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(10).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document
            .getParagraphs()
            .get(0)
            .getRuns()
            .get(10)
            .getCTR()
            .getRPr()
            .getHighlight()
            .getVal());
    assertEquals(
        "Unexpected tag m:endlet at this location",
        document.getParagraphs().get(0).getRuns().get(11).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(11).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(11).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document
            .getParagraphs()
            .get(0)
            .getRuns()
            .get(11)
            .getCTR()
            .getRPr()
            .getHighlight()
            .getVal());

    assertEquals("<---", document.getParagraphs().get(0).getRuns().get(10).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(10).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(10).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document
            .getParagraphs()
            .get(0)
            .getRuns()
            .get(10)
            .getCTR()
            .getRPr()
            .getHighlight()
            .getVal());
    assertEquals(
        "Unexpected tag m:endlet at this location",
        document.getParagraphs().get(0).getRuns().get(11).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(11).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(11).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document
            .getParagraphs()
            .get(0)
            .getRuns()
            .get(11)
            .getCTR()
            .getRPr()
            .getHighlight()
            .getVal());

    assertEquals("    ", document.getParagraphs().get(0).getRuns().get(15).getText(0));
    assertEquals("<---", document.getParagraphs().get(0).getRuns().get(16).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(16).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(16).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document
            .getParagraphs()
            .get(0)
            .getRuns()
            .get(16)
            .getCTR()
            .getRPr()
            .getHighlight()
            .getVal());
    assertEquals(
        "gd:elseif, gd:else or gd:endif expected here.",
        document.getParagraphs().get(0).getRuns().get(17).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(17).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(17).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document
            .getParagraphs()
            .get(0)
            .getRuns()
            .get(17)
            .getCTR()
            .getRPr()
            .getHighlight()
            .getVal());

    assertEquals("Some", document.getParagraphs().get(0).getRuns().get(18).getText(0));
    assertEquals(" t", document.getParagraphs().get(0).getRuns().get(19).getText(0));
    assertEquals("ext", document.getParagraphs().get(0).getRuns().get(20).getText(0));
    assertEquals("<---", document.getParagraphs().get(0).getRuns().get(22).getText(0));
    assertEquals(
        "Unexpected tag EOF at this location",
        document.getParagraphs().get(0).getRuns().get(23).getText(0));
  }
  /**
   * Tests that parsing errors from AQL template tag (conditional here) are placed next to the start
   * tag. The tested tag is <{m:diagram provider:"noExistingProvider" width:"500" height:"500"
   * title="representationTitle"}Some text> The expected tag is : <{m:diagram
   * provider:"noExistingProvider" width:"500" height:"500" title="representationTitle"}<---The
   * image tag is referencing an unknown diagram provider : 'noExistingProvider' <---The start of an
   * option's key has been read but the end of it and the value were missing : '
   * title="representationTitle"'. Some text> After the run with the end '}' char, the following
   * runs must be present : A run must contains blanks char. The next one must contains the error
   * message. The next one is a blank separator. The next one must contains the other error message.
   * The next one must contains blank char and the next one the static content after the tag in the
   * original template.
   *
   * @throws InvalidFormatException
   * @throws IOException
   * @throws DocumentParserException
   * @throws DocumentGenerationException
   */
  @Test
  public void testMultiErrorInSimpleTag()
      throws InvalidFormatException, IOException, DocumentParserException,
          DocumentGenerationException {
    FileInputStream is = new FileInputStream("templates/testMultiParsingErrorSimpleTag.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    TemplateValidationGenerator validator = new TemplateValidationGenerator();
    validator.doSwitch(template);
    createDestinationDocument(document, "results/testMultiParsingErrorSimpleTag.docx");
    // scan the destination document
    assertEquals(1, document.getParagraphs().size());
    assertEquals(14, document.getParagraphs().get(0).getRuns().size());
    assertEquals("    ", document.getParagraphs().get(0).getRuns().get(2).getText(0));
    assertEquals("<---", document.getParagraphs().get(0).getRuns().get(3).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(3).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(3).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document.getParagraphs().get(0).getRuns().get(3).getCTR().getRPr().getHighlight().getVal());
    assertEquals(
        "The image tag is referencing an unknown diagram provider : 'noExistingProvider'",
        document.getParagraphs().get(0).getRuns().get(6).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(6).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(6).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document.getParagraphs().get(0).getRuns().get(6).getCTR().getRPr().getHighlight().getVal());

    assertEquals("    ", document.getParagraphs().get(0).getRuns().get(10).getText(0));
    assertEquals("<---", document.getParagraphs().get(0).getRuns().get(11).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(11).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(11).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document
            .getParagraphs()
            .get(0)
            .getRuns()
            .get(11)
            .getCTR()
            .getRPr()
            .getHighlight()
            .getVal());
    assertEquals(
        "The start of an option's key has been read but the end of it and the value were missing : ' title=\"representationTitle\"'.",
        document.getParagraphs().get(0).getRuns().get(12).getText(0));
    assertEquals("FF0000", document.getParagraphs().get(0).getRuns().get(12).getColor());
    assertEquals(16, document.getParagraphs().get(0).getRuns().get(12).getFontSize());
    assertEquals(
        STHighlightColor.LIGHT_GRAY,
        document
            .getParagraphs()
            .get(0)
            .getRuns()
            .get(11)
            .getCTR()
            .getRPr()
            .getHighlight()
            .getVal());

    assertEquals("Some text", document.getParagraphs().get(0).getRuns().get(13).getText(0));
  }
Esempio n. 18
0
File: Main.java Progetto: 8CAKE/ALE
  @Override
  public void start(Stage primaryStage) throws Exception {

    try {
      screenSize = Screen.getPrimary().getVisualBounds();
      width = screenSize.getWidth(); // gd.getDisplayMode().getWidth();
      height = screenSize.getHeight(); // gd.getDisplayMode().getHeight();
    } catch (Exception excep) {
      System.out.println("<----- Exception in  Get Screen Size ----->");
      excep.printStackTrace();
      System.out.println("<---------->\n");
    }

    try {
      dbCon =
          DriverManager.getConnection(
              "jdbc:mysql://192.168.1.6:3306/ale", "Root", "oqu#$XQgHFzDj@1MGg1G8");
      estCon = true;
    } catch (SQLException sqlExcep) {
      System.out.println("<----- SQL Exception in Establishing Database Connection ----->");
      sqlExcep.printStackTrace();
      System.out.println("<---------->\n");
    }

    xmlParser.generateUserInfo();
    superUser = xmlParser.getSuperUser();

    // ----------------------------------------------------------------------------------------------------> Top Panel Start

    closeBtn = new Button("");
    closeBtn.getStyleClass().add("systemBtn");
    closeBtn.setOnAction(
        e -> {
          systemClose();
        });

    minimizeBtn = new Button("");
    minimizeBtn.getStyleClass().add("systemBtn");
    minimizeBtn.setOnAction(
        e -> {
          primaryStage.setIconified(true);
        });

    miscContainer = new HBox();

    calcBtn = new Button();
    calcBtn.getStyleClass().addAll("calcBtn");
    calcBtn.setOnAction(
        e -> {
          calculator calculator = new calculator();
          scientificCalculator scientificCalculator = new scientificCalculator();
          calculator.start(calculatorName);
        });

    miscContainer.getChildren().add(calcBtn);

    topPanel = new HBox(1);
    topPanel.getStyleClass().add("topPanel");
    topPanel.setPrefWidth(width);
    topPanel.setAlignment(Pos.CENTER_RIGHT);
    topPanel.setPadding(new Insets(0, 0, 0, 0));
    topPanel.getChildren().addAll(miscContainer, minimizeBtn, closeBtn);

    // ------------------------------------------------------------------------------------------------------> Top Panel End

    // ----------------------------------------------------------------------------------------------> Navigation Panel Start

    Line initDivider = new Line();
    initDivider.setStartX(0.0f);
    initDivider.setEndX(205.0f);
    initDivider.setStroke(Color.GRAY);

    // <----- Dashboard ----->
    dashboardToolTip = new Tooltip("Dashboard");

    dashboardBtn = new Button("");
    dashboardBtn.getStyleClass().add("dashboardBtn");
    dashboardBtn.setTooltip(dashboardToolTip);
    dashboardBtn.setOnAction(
        e -> {
          resetBtns();
          rootPane.setCenter(dashBoardBase);
        });

    // <----- Profile ----->
    profileToolTip = new Tooltip("Profile");

    profileBtn = new Button();
    profileBtn.getStyleClass().add("profileBtn");
    profileBtn.setTooltip(profileToolTip);
    profileBtn.setOnAction(
        e -> {
          resetBtns();
          rootPane.setCenter(profilePanel);
        });

    // <----- Courses ----->
    courseToolTip = new Tooltip("Courses");

    coursesBtn = new Button("");
    coursesBtn.getStyleClass().add("coursesBtn");
    coursesBtn.setTooltip(courseToolTip);
    coursesBtn.setOnAction(
        e -> {
          resetBtns();
          rootPane.setCenter(coursesPanel);
          // miscContainer.getChildren().addAll(watchVidBtn);
          coursesPanel.setContent(coursesGridPanel);
        });

    Line mainDivider = new Line();
    mainDivider.setStartX(0.0f);
    mainDivider.setEndX(205.0f);
    mainDivider.setStroke(Color.GRAY);

    // <----- Simulations ----->
    simsToolTip = new Tooltip("Simulations");

    simsBtn = new Button();
    simsBtn.getStyleClass().add("simsBtn");
    simsBtn.setTooltip(simsToolTip);
    simsBtn.setOnAction(
        e -> {
          resetBtns();
          rootPane.setCenter(simsPanel);
          simsPanel.setContent(simsGridPanel);
        });

    // <----- Text Editor ----->
    textEditorToolTip = new Tooltip("Text Editor");

    textEditorBtn = new Button();
    textEditorBtn.getStyleClass().add("textEditorBtn");
    textEditorBtn.setTooltip(textEditorToolTip);
    textEditorBtn.setOnAction(
        e -> {
          resetBtns();
          rootPane.setCenter(textEditorPanel);
          miscContainer.getChildren().addAll(saveDocBtn);
        });

    Line toolsDivider = new Line();
    toolsDivider.setStartX(0.0f);
    toolsDivider.setEndX(205.0f);
    toolsDivider.setStroke(Color.GRAY);

    // <----- Wolfram Alpha ----->
    wolframToolTip = new Tooltip("Wolfram Alpha");

    wolframBtn = new Button();
    wolframBtn.getStyleClass().add("wolframBtn");
    wolframBtn.setTooltip(wolframToolTip);
    wolframBtn.setOnAction(
        e -> {
          resetBtns();
          rootPane.setCenter(wolframPanel);
        });

    // <----- Wikipedia ----->
    wikipediaToolTip = new Tooltip();

    wikipediaBtn = new Button();
    wikipediaBtn.getStyleClass().add("wikipediaBtn");
    wikipediaBtn.setTooltip(wikipediaToolTip);
    wikipediaBtn.setOnAction(
        e -> {
          resetBtns();
          rootPane.setCenter(wikipediaPanel);
        });

    Line sitesDivider = new Line();
    sitesDivider.setStartX(0.0f);
    sitesDivider.setEndX(205.0f);
    sitesDivider.setStroke(Color.GRAY);

    // <----- Settings ----->
    settingsToolTip = new Tooltip("Settings");

    settingsBtn = new Button();
    settingsBtn.getStyleClass().add("settingsBtn");
    settingsBtn.setTooltip(settingsToolTip);
    settingsBtn.setOnAction(
        e -> {
          resetBtns();
          rootPane.setCenter(settingsPanel);
        });

    leftPanel = new VBox(0);
    // leftPanel.setPrefWidth(1);
    leftPanel.getStyleClass().add("leftPane");
    leftPanel
        .getChildren()
        .addAll(
            initDivider,
            dashboardBtn,
            profileBtn,
            coursesBtn,
            mainDivider,
            simsBtn,
            textEditorBtn,
            toolsDivider,
            wolframBtn,
            wikipediaBtn,
            sitesDivider,
            settingsBtn);

    topPanel = new HBox(1);
    topPanel.getStyleClass().add("topPanel");
    topPanel.setPrefWidth(width);
    topPanel.setAlignment(Pos.CENTER_RIGHT);
    topPanel.setPadding(new Insets(0, 0, 0, 0));
    topPanel.getChildren().addAll(miscContainer, minimizeBtn, closeBtn);

    // ------------------------------------------------------------------------------------------------> Navigation Panel End

    // -----------------------------------------------------------------------------------------------> Dashboard Pane Start

    final WebView webVid = new WebView();
    final WebEngine webVidEngine = webVid.getEngine();
    webVid.setPrefHeight(860);
    webVid.setPrefWidth(width - 118);
    webVidEngine.loadContent("");

    final NumberAxis xAxis = new NumberAxis();
    final NumberAxis yAxis = new NumberAxis();
    xAxis.setLabel("Day");
    yAxis.setLabel("Score");
    final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);

    lineChart.setTitle("Line Chart");
    XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();
    series.setName("My Data");

    // populating the series with data
    series.getData().add(new XYChart.Data<Number, Number>(0.25, 36));
    series.getData().add(new XYChart.Data<Number, Number>(1, 23));
    series.getData().add(new XYChart.Data<Number, Number>(2, 114));
    series.getData().add(new XYChart.Data<Number, Number>(3, 15));
    series.getData().add(new XYChart.Data<Number, Number>(4, 124));
    lineChart.getData().add(series);
    lineChart.setPrefWidth(400);
    lineChart.setPrefHeight(300);
    lineChart.setLegendVisible(false);

    chatRoomField = new TextField();
    chatRoomField.getStyleClass().add("textField");
    chatRoomField.setPromptText("Enter Chat Room");
    chatRoomField.setOnKeyPressed(
        new EventHandler<KeyEvent>() {
          @Override
          public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.ENTER) {
              chatRoom = chatRoomField.getText();
              client.connect(messageArea, messageInputArea, superUser, chatRoom);
            }
          }
        });

    messageArea = new TextArea();
    messageArea.getStyleClass().add("textArea");
    messageArea.setWrapText(true);
    messageArea.setPrefHeight(740);
    messageArea.setEditable(false);

    messageInputArea = new TextArea();
    messageInputArea.getStyleClass().add("textArea");
    messageInputArea.setWrapText(true);
    messageInputArea.setPrefHeight(100);
    messageInputArea.setPromptText("Enter Message");
    messageInputArea.setOnKeyPressed(
        new EventHandler<KeyEvent>() {
          @Override
          public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.ENTER) {
              client.send(messageArea, messageInputArea, superUser, chatRoom);
              event.consume();
            }
          }
        });

    chatBox = new VBox();
    chatBox.setPrefWidth(250);
    chatBox.setMaxWidth(250);
    chatBox.getStyleClass().add("chatBox");
    chatBox.getChildren().addAll(chatRoomField, messageArea, messageInputArea);

    // client.test(messageArea, messageInputArea);

    dashboardGridPanel = new GridPane();
    dashboardGridPanel.getStyleClass().add("gridPane");
    dashboardGridPanel.setVgap(5);
    dashboardGridPanel.setHgap(5);
    dashboardGridPanel.setGridLinesVisible(false);
    dashboardGridPanel.setPrefWidth(width - 430);
    dashboardGridPanel.setPrefHeight(860);

    dashboardGridPanel.setColumnIndex(lineChart, 0);
    dashboardGridPanel.setRowIndex(lineChart, 0);
    dashboardGridPanel.getChildren().addAll(lineChart);

    dashboardPanel = new ScrollPane();
    dashboardPanel.getStyleClass().add("scrollPane");
    dashboardPanel.setPrefWidth(width - 400);
    dashboardPanel.setPrefHeight(860);
    dashboardPanel.setContent(dashboardGridPanel);

    dashBoardBase = new HBox();
    dashBoardBase.setPrefWidth(width - (leftPanel.getWidth() + chatBox.getWidth()));
    dashBoardBase.setPrefHeight(860);
    dashBoardBase.getChildren().addAll(dashboardPanel, chatBox);

    // -------------------------------------------------------------------------------------------------> Dashboard Pane End

    // -------------------------------------------------------------------------------------------------> Profile Pane Start

    profilePictureBtn = new Button();
    profilePictureBtn.getStyleClass().addAll("profilePictureBtn");

    String profileUserName = xmlParser.getSuperUser();

    String profileEmail = xmlParser.getEmail();
    String profileAge = xmlParser.getAge();
    String profileSchool = xmlParser.getSchool();
    String profileCountry = "";
    String profileCity = "";

    userNameLbl = new Label(profileUserName);
    userNameLbl.getStyleClass().add("profileLbl");
    userNameLbl.setAlignment(Pos.CENTER);

    emailLbl = new Label(profileEmail);
    emailLbl.getStyleClass().add("profileLbl");

    ageLbl = new Label(profileAge);
    ageLbl.getStyleClass().add("profileLbl");

    schoolLbl = new Label(profileSchool);
    schoolLbl.getStyleClass().add("profileLbl");

    profileGridPanel = new GridPane();
    profileGridPanel.getStyleClass().add("gridPane");
    profileGridPanel.setVgap(5);
    profileGridPanel.setHgap(5);
    profileGridPanel.setGridLinesVisible(false);
    profileGridPanel.setPrefWidth(width - 208);
    profileGridPanel.setPrefHeight(860);
    profileGridPanel.setAlignment(Pos.TOP_CENTER);

    profileGridPanel.setRowIndex(profilePictureBtn, 0);
    profileGridPanel.setColumnIndex(profilePictureBtn, 0);
    profileGridPanel.setRowIndex(userNameLbl, 1);
    profileGridPanel.setColumnIndex(userNameLbl, 0);
    profileGridPanel.setRowIndex(emailLbl, 2);
    profileGridPanel.setColumnIndex(emailLbl, 0);
    profileGridPanel.setRowIndex(ageLbl, 3);
    profileGridPanel.setColumnIndex(ageLbl, 0);
    profileGridPanel.setRowIndex(schoolLbl, 4);
    profileGridPanel.setColumnIndex(schoolLbl, 0);
    profileGridPanel
        .getChildren()
        .addAll(profilePictureBtn, userNameLbl, emailLbl, ageLbl, schoolLbl);

    profilePanel = new ScrollPane();
    profilePanel.getStyleClass().add("scrollPane");
    profilePanel.setContent(profileGridPanel);

    // ---------------------------------------------------------------------------------------------------> Profile Pane End

    // -------------------------------------------------------------------------------------------------> Courses Pane Start

    String course = "";

    // Media media = new Media("media.mp4");

    // mediaPlayer = new MediaPlayer(media);
    // mediaPlayer.setAutoPlay(true);

    // mediaView = new MediaView(mediaPlayer);

    watchVidBtn = new Button("Watch Video");
    watchVidBtn.getStyleClass().add("btn");
    watchVidBtn.setOnAction(
        e -> {

          // coursesPanel.setContent(mediaView);
        });

    chemistryBtn = new Button();
    chemistryBtn.getStyleClass().add("chemistryBtn");
    chemistryBtn.setOnAction(
        e -> {
          displayCourse("chemistry");
        });

    physicsBtn = new Button();
    physicsBtn.getStyleClass().add("physicsBtn");
    physicsBtn.setOnAction(
        e -> {
          displayCourse("physics");
        });

    mathsBtn = new Button();
    mathsBtn.getStyleClass().add("mathsBtn");

    bioBtn = new Button();
    bioBtn.getStyleClass().add("bioBtn");
    bioBtn.setOnAction(
        e -> {
          rootPane.setCenter(biologyCourse.biologyPane());
        });

    // Course Web View
    try {
      courseView = new WebView();
      courseWebEngine = courseView.getEngine();
      courseView.setPrefHeight(860);
      courseView.setPrefWidth(width - 208);
    } catch (Exception excep) {
      System.out.println("<----- Exception in Course Web ----->");
      excep.printStackTrace();
      System.out.println("<---------->\n");
    }

    coursesGridPanel = new GridPane();
    coursesGridPanel.getStyleClass().add("gridPane");
    coursesGridPanel.setVgap(5);
    coursesGridPanel.setHgap(5);
    coursesGridPanel.setGridLinesVisible(false);
    coursesGridPanel.setPrefWidth(width - 208);
    coursesGridPanel.setPrefHeight(860);

    coursesGridPanel.setRowIndex(chemistryBtn, 1);
    coursesGridPanel.setColumnIndex(chemistryBtn, 1);
    coursesGridPanel.setRowIndex(physicsBtn, 1);
    coursesGridPanel.setColumnIndex(physicsBtn, 2);
    coursesGridPanel.setRowIndex(mathsBtn, 1);
    coursesGridPanel.setColumnIndex(mathsBtn, 3);
    coursesGridPanel.setRowIndex(bioBtn, 1);
    coursesGridPanel.setColumnIndex(bioBtn, 4);
    coursesGridPanel.getChildren().addAll(chemistryBtn, physicsBtn, mathsBtn, bioBtn);

    coursesPanel = new ScrollPane();
    coursesPanel.getStyleClass().add("scrollPane");
    coursesPanel.setPrefWidth(width - 118);
    coursesPanel.setPrefHeight(860);
    coursesPanel.setContent(coursesGridPanel);

    // ---------------------------------------------------------------------------------------------------> Courses Pane End

    // ---------------------------------------------------------------------------------------------> Simulations Pane Start
    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();
    browser.setPrefHeight(860);
    browser.setPrefWidth(width - 208);

    /*
    File phetImageFile = new File("img/styleDark/poweredByPHET.png");
    String phetImageURL = phetImageFile.toURI().toURL().toString();
    Image phetImage = new Image(phetImageURL, false);
    */

    final ImageView phetImageView = new ImageView();
    final Image phetImage =
        new Image(Main.class.getResourceAsStream("img/styleDark/poweredByPHET.png"));
    phetImageView.setImage(phetImage);

    Label motionLbl = new Label("Motion");
    motionLbl.getStyleClass().add("lbl");

    forcesAndMotionBtn = new Button();
    forcesAndMotionBtn.getStyleClass().add("forcesAndMotionBtn");
    forcesAndMotionBtn.setOnAction(
        e -> {
          webEngine.load(
              "https://phet.colorado.edu/sims/html/balancing-act/latest/balancing-act_en.html");
          simsPanel.setContent(browser);
        });

    balancingActBtn = new Button();
    balancingActBtn.getStyleClass().add("balancingActBtn");
    balancingActBtn.setOnAction(
        e -> {
          webEngine.load(
              "https://phet.colorado.edu/sims/html/balancing-act/latest/balancing-act_en.html");
          simsPanel.setContent(browser);
        });

    energySkateParkBtn = new Button();
    energySkateParkBtn.getStyleClass().add("energySkateParkBtn");
    energySkateParkBtn.setOnAction(
        e -> {
          webEngine.load(
              "https://phet.colorado.edu/sims/html/energy-skate-park-basics/latest/"
                  + "energy-skate-park-basics_en.html");
          simsPanel.setContent(browser);
        });

    balloonsAndStaticElectricityBtn = new Button();
    balloonsAndStaticElectricityBtn.getStyleClass().add("balloonsAndStaticElectricityBtn");
    balloonsAndStaticElectricityBtn.setOnAction(
        e -> {
          webEngine.load(
              "https://phet.colorado.edu/sims/html/balloons-and-static-electricity/latest/"
                  + "balloons-and-static-electricity_en.html");
          simsPanel.setContent(browser);
        });

    buildAnAtomBtn = new Button();
    buildAnAtomBtn.getStyleClass().add("buildAnAtomBtn");
    buildAnAtomBtn.setOnAction(
        e -> {
          webEngine.load(
              "https://phet.colorado.edu/sims/html/build-an-atom/latest/build-an-atom_en.html");
          simsPanel.setContent(browser);
        });

    colorVisionBtn = new Button();
    colorVisionBtn.getStyleClass().add("colorVisionBtn");
    colorVisionBtn.setOnAction(
        e -> {
          webEngine.load(
              "https://phet.colorado.edu/sims/html/color-vision/latest/color-vision_en.html");
          simsPanel.setContent(browser);
        });

    Label soundAndWavesLbl = new Label("Sound and Waves");
    soundAndWavesLbl.getStyleClass().add("lbl");

    wavesOnAStringBtn = new Button();
    wavesOnAStringBtn.getStyleClass().add("wavesOnAStringBtn");
    wavesOnAStringBtn.setOnAction(
        e -> {
          webEngine.load(
              "https://phet.colorado.edu/sims/html/wave-on-a-string/latest/wave-on-a-string_en.html");
          simsPanel.setContent(browser);
        });

    /*
    motionSimsFlowPane = new FlowPane();
    motionSimsFlowPane.getStyleClass().add("flowPane");
    motionSimsFlowPane.setVgap(5);
    motionSimsFlowPane.setHgap(5);
    motionSimsFlowPane.setAlignment(Pos.TOP_LEFT);
    motionSimsFlowPane.getChildren().addAll(forcesAndMotionBtn, balancingActBtn, energySkateParkBtn,
            buildAnAtomBtn, colorVisionBtn, wavesOnAStringBtn);


    soundAndWavesFlowPane = new FlowPane();
    soundAndWavesFlowPane.getStyleClass().add("flowPane");
    soundAndWavesFlowPane.setVgap(5);
    soundAndWavesFlowPane.setHgap(5);
    soundAndWavesFlowPane.setAlignment(Pos.TOP_LEFT);
    soundAndWavesFlowPane.getChildren().addAll(wavesOnAStringBtn);


    simsBox = new VBox();
    simsBox.getStyleClass().add("vbox");
    simsBox.setPrefHeight(height);
    simsBox.setPrefWidth(width);
    simsBox.getChildren().addAll(motionLbl, motionSimsFlowPane, soundAndWavesLbl, soundAndWavesFlowPane);
    */

    simsGridPanel = new GridPane();
    simsGridPanel.getStyleClass().add("gridPane");
    simsGridPanel.setVgap(5);
    simsGridPanel.setHgap(5);
    simsGridPanel.setGridLinesVisible(false);
    simsGridPanel.setPrefWidth(width - 208);
    simsGridPanel.setPrefHeight(860);

    simsGridPanel.setRowIndex(phetImageView, 0);
    simsGridPanel.setColumnIndex(phetImageView, 4);

    simsGridPanel.setRowIndex(motionLbl, 0);
    simsGridPanel.setColumnIndex(motionLbl, 0);
    simsGridPanel.setRowIndex(forcesAndMotionBtn, 1);
    simsGridPanel.setColumnIndex(forcesAndMotionBtn, 0);
    simsGridPanel.setRowIndex(balancingActBtn, 1);
    simsGridPanel.setColumnIndex(balancingActBtn, 1);
    simsGridPanel.setRowIndex(energySkateParkBtn, 1);
    simsGridPanel.setColumnIndex(energySkateParkBtn, 2);
    simsGridPanel.setRowIndex(buildAnAtomBtn, 1);
    simsGridPanel.setColumnIndex(buildAnAtomBtn, 3);
    simsGridPanel.setRowIndex(colorVisionBtn, 1);
    simsGridPanel.setColumnIndex(colorVisionBtn, 4);

    simsGridPanel.setRowIndex(soundAndWavesLbl, 2);
    simsGridPanel.setColumnIndex(soundAndWavesLbl, 0);
    simsGridPanel.setColumnSpan(soundAndWavesLbl, 4);
    simsGridPanel.setRowIndex(wavesOnAStringBtn, 3);
    simsGridPanel.setColumnIndex(wavesOnAStringBtn, 0);

    simsGridPanel
        .getChildren()
        .addAll(
            phetImageView,
            motionLbl,
            forcesAndMotionBtn,
            balancingActBtn,
            energySkateParkBtn,
            buildAnAtomBtn,
            colorVisionBtn,
            soundAndWavesLbl,
            wavesOnAStringBtn);

    simsPanel = new ScrollPane();
    simsPanel.getStyleClass().add("scrollPane");
    simsPanel.setContent(simsGridPanel);

    // -----------------------------------------------------------------------------------------------> Simulations Pane End

    // ---------------------------------------------------------------------------------------------> Text Editor Pane Start

    htmlEditor = new HTMLEditor();
    htmlEditor.setPrefHeight(860);
    htmlEditor.setPrefWidth(width - 208);

    // Prevents Scroll on Space Pressed
    htmlEditor.addEventFilter(
        KeyEvent.KEY_PRESSED,
        new EventHandler<KeyEvent>() {
          @Override
          public void handle(KeyEvent event) {
            if (event.getEventType() == KeyEvent.KEY_PRESSED) {
              if (event.getCode() == KeyCode.SPACE) {
                event.consume();
              }
            }
          }
        });

    XWPFDocument document = new XWPFDocument();
    XWPFParagraph tmpParagraph = document.createParagraph();
    XWPFRun tmpRun = tmpParagraph.createRun();

    saveDocBtn = new Button();
    saveDocBtn.getStyleClass().add("btn");
    saveDocBtn.setText("Save");
    saveDocBtn.setOnAction(
        e -> {
          tmpRun.setText(tools.stripHTMLTags(htmlEditor.getHtmlText()));
          tmpRun.setFontSize(12);
          saveDocument(document, primaryStage);
        });

    textEditorPanel = new ScrollPane();
    textEditorPanel.getStyleClass().add("scrollPane");
    textEditorPanel.setContent(htmlEditor);

    // -----------------------------------------------------------------------------------------------> Text Editor Pane End

    // -------------------------------------------------------------------------------------------------> Wolfram Pane Start

    Boolean wolframActive = false;
    try {
      final WebView wolframWeb = new WebView();
      wolframWeb.getStyleClass().add("webView");
      final WebEngine wolframWebEngine = wolframWeb.getEngine();
      wolframWeb.setPrefHeight(860);
      wolframWeb.setPrefWidth(width - 208);
      if (wolframActive == false) {
        wolframWebEngine.load("http://www.wolframalpha.com/");
        wolframActive = true;
      }
      wolframPanel = new ScrollPane();
      wolframPanel.setContent(wolframWeb);
    } catch (Exception excep) {
      System.out.println("<----- Exception in Wolfram Alpha Web ----->");
      excep.printStackTrace();
      System.out.println("<---------->\n");
    }

    // ---------------------------------------------------------------------------------------------------> Wolfram Pane End

    // ------------------------------------------------------------------------------------------------> Wikipedia Pane Start

    Boolean wikipediaActive = false;
    try {
      final WebView wikipediaWeb = new WebView();
      wikipediaWeb.getStyleClass().add("scrollPane");
      wikipediaWebEngine = wikipediaWeb.getEngine();
      wikipediaWeb.setPrefHeight(860);
      wikipediaWeb.setPrefWidth(width - 208);
      if (wikipediaActive == false) {
        wikipediaWebEngine.load("https://en.wikipedia.org/wiki/Main_Page");
        wikipediaActive = true;
      }
      wikipediaPanel = new ScrollPane();
      wikipediaPanel.setContent(wikipediaWeb);
    } catch (Exception e) {
      e.printStackTrace();
    }

    // --------------------------------------------------------------------------------------------------> Wikipedia Pane End

    // -------------------------------------------------------------------------------------------------> Settings Pane Start

    settingsGridPanel = new GridPane();
    settingsGridPanel.getStyleClass().add("gridPane");
    settingsGridPanel.setPrefWidth(width - 208);
    settingsGridPanel.setPrefHeight(height);
    settingsGridPanel.setVgap(5);
    settingsGridPanel.setHgap(5);

    settingsPanel = new ScrollPane();
    settingsPanel.getStyleClass().add("scrollPane");
    settingsPanel.setContent(settingsGridPanel);

    // ---------------------------------------------------------------------------------------------------> Settings Pane End
    rootPane = new BorderPane();
    rootPane.setLeft(leftPanel);
    rootPane.setTop(topPanel);
    rootPane.setCenter(dashBoardBase);
    rootPane.getStyleClass().add("rootPane");
    rootPane.getStylesheets().add(Main.class.getResource("css/styleDark.css").toExternalForm());

    programWidth = primaryStage.getWidth();
    programHeight = primaryStage.getHeight();

    primaryStage.setTitle("ALE");
    primaryStage.initStyle(StageStyle.UNDECORATED);
    primaryStage
        .getIcons()
        .add(new javafx.scene.image.Image(Main.class.getResourceAsStream("img/aleIcon.png")));
    primaryStage.setScene(new Scene(rootPane, width, height));
    primaryStage.show();
  }
  public void formatTo(String code, Map<String, Object> args, OutputStream out) {
    Template tpl = loadByCode(code);
    if (tpl == null) logger.warn("没有找到编码为'" + code + "'的模板!");
    if (tpl.isFormatted()) logger.warn("code=" + code + ",模板不可格式化。");

    // 纯文本类型
    if (tpl.isPureText()) {
      String source = this.getContent(code);
      String r = TemplateUtils.format(source, args);
      try {
        out.write(r.getBytes());
        out.flush();
      } catch (IOException e) {
        logger.warn("formatTo 写入数据到流错误:" + e.getMessage());
      } finally {
        try {
          out.close();
        } catch (IOException ex) {
        }
      }
    } else {
      InputStream is = tpl.getInputStream();

      // 附件的扩展名
      String extension = StringUtils.getFilenameExtension(tpl.getPath());

      if ("word-docx".equals(tpl.getTemplateType().getCode()) && "docx".equals(extension)) {
        XWPFDocument docx = DocxUtils.format(is, args);
        try {
          docx.write(out);
          out.flush();
        } catch (IOException e) {
          logger.warn("formatTo 写入数据到流错误:" + e.getMessage());
        } finally {
          try {
            is.close();
            out.close();
          } catch (IOException ex) {
          }
        }

      } else if ("xls".equals(tpl.getTemplateType().getCode()) && "xls".equals(extension)) {
        HSSFWorkbook xls = XlsUtils.format(is, args);
        try {
          xls.write(out);
          out.flush();
        } catch (IOException e) {
          e.printStackTrace();
          logger.warn("formatTo 写入数据到流错误:" + e.getMessage());
        } finally {
          try {
            is.close();
            out.close();
          } catch (IOException ex) {
          }
        }

      } else if ("xlsx".equals(tpl.getTemplateType().getCode())
          && "xlsx".equals(extension)) { // Excel2007+

        XSSFWorkbook xlsx = XlsxUtils.format(is, args);
        try {
          xlsx.write(out);
          out.flush();
        } catch (IOException e) {
          e.printStackTrace();
          logger.warn("formatTo 写入数据到流错误:" + e.getMessage());
        } finally {
          try {
            is.close();
            out.close();
          } catch (IOException ex) {
          }
        }

      } else if ("html".equals(tpl.getTemplateType().getCode())
          && "html".equals(extension)) { // html
        String source = FreeMarkerUtils.format(TemplateUtils.loadText(is), args);
        try {
          out.write(source.getBytes());
          out.flush();
        } catch (IOException e) {
          e.printStackTrace();
          logger.warn("formatTo 写入数据到流错误:" + e.getMessage());
        } finally {
          try {
            is.close();
            out.close();
          } catch (IOException ex) {
          }
        }
      } else {
        logger.warn("文件后缀名:" + extension + ",不能formatTo");
        try {
          is.close();
          out.close();
        } catch (IOException ex) {
        }
      }
    }
  }
Esempio n. 20
0
  /**
   * Main method: reads the Word document and extracts the information about entities.
   *
   * @throws IOException In case of error while reading the document.
   */
  public void readGAMSODocument() throws IOException {

    // Read the document with POI and get the list of paragraphs
    XWPFDocument document = new XWPFDocument(new FileInputStream(GAMSO_DOCX));
    List<XWPFParagraph> paragraphs = document.getParagraphs();

    int paragraphNumber = 0;
    int paragraphStylingNumber = 0;
    int[] currentNumber = {0, 0, 0};
    List<String> currentDescription = null;
    String currentLabel = null;

    // Creation of the concept scheme resource.
    gamsoCS = gamsoModel.createResource(GAMSO_BASE_URI + "gamso", SKOS.ConceptScheme);

    // Iteration through the document paragraphs
    logger.debug(
        "Document read from " + GAMSO_DOCX + ", starting to iterate through the paragraphs.");
    for (XWPFParagraph paragraph : paragraphs) {

      if (paragraph.getParagraphText() == null) continue; // skipping empty paragraphs
      paragraphNumber++;

      // Styling number will be strictly positive for headings and list elements (eg. bullet points)
      paragraphStylingNumber = (paragraph.getNumID() == null) ? 0 : paragraph.getNumID().intValue();

      // Add the paragraph text to the CS description if its number corresponds
      if (descriptionIndexes.contains(paragraphNumber)) {
        // TODO normalize white spaces
        if (gamsoDescription == null) gamsoDescription = paragraph.getParagraphText();
        else gamsoDescription += " " + paragraph.getParagraphText();
      }

      if (LEVEL1_STYLING.equals(paragraph.getStyle())) {
        // The first headings are in the introduction: we skip those
        if (paragraphStylingNumber == 0) continue;
        // If paragraph has a number styling, we have a new level 1 activity
        currentNumber[2] = 0; // Because third number may have been modified by level 3 operations
        if (currentDescription != null) {
          // Previous description is complete: record in the model
          this.addActivityToModel(currentNumber, currentLabel, currentDescription);
        }
        currentNumber[0]++;
        currentNumber[1] = 0;
        currentDescription = new ArrayList<String>();
        currentLabel = normalizeActivityName(paragraph);
      } else if (LEVEL2_STYLING.equals(paragraph.getStyle())) {
        // Start of a new level 2 activity
        currentNumber[2] = 0;
        // Record previous description (which exists since we are at level 2) in the model
        this.addActivityToModel(currentNumber, currentLabel, currentDescription);
        currentNumber[1]++;
        currentDescription = new ArrayList<String>();
        currentLabel = normalizeActivityName(paragraph); // Strip code for 3.x activities
      } else {
        if (currentNumber[0] == 0) continue; // Skip paragraphs that are before the first activity
        // Not a heading, so part of a description
        String descriptionPart = normalizeDescriptionItem(paragraph, paragraphStylingNumber);
        if (descriptionPart.length() > 0) currentDescription.add(descriptionPart);
        // Transform bullet points of level 2 activities into level 3 activities
        if ((paragraphStylingNumber > 0) && (currentNumber[1] > 0)) {
          currentNumber[2]++;
          this.addActivityToModel(currentNumber, paragraph.getParagraphText().trim(), null);
        }
      }
    }
    // The last activity read has not been added to the model yet: we do it here
    this.addActivityToModel(currentNumber, currentLabel, currentDescription);

    document.close();

    logger.debug("Iteration through the paragraphs finished, completing the Jena model.");

    // Add the properties of the concept scheme (the description is now complete)
    gamsoCS.addProperty(SKOS.notation, gamsoModel.createLiteral("GAMSO v1.0"));
    gamsoCS.addProperty(
        SKOS.prefLabel,
        gamsoModel.createLiteral(
            "Generic Activity Model for Statistical Organisations v 1.0", "en"));
    gamsoCS.addProperty(SKOS.scopeNote, gamsoModel.createLiteral(gamsoDescription, "en"));
  }
Esempio n. 21
0
  /**
   * 生成word,表格
   *
   * @param data
   * @throws Exception
   */
  public static void productWordForm(
      Map<String, String> tableinfo,
      Map<String, LinkedHashMap<String, LinkedHashMap<String, String>>> data,
      Parameters parameters)
      throws Exception {
    XWPFDocument xDocument = new XWPFDocument();

    Iterator<String> tableNameIter = data.keySet().iterator();
    while (tableNameIter.hasNext()) {
      String table_name = tableNameIter.next();
      XWPFParagraph xp = xDocument.createParagraph();
      XWPFRun r1 = xp.createRun();
      r1.setText(table_name + " " + tableinfo.get(table_name));
      r1.setFontSize(18);
      r1.setTextPosition(10);

      XWPFParagraph p = xDocument.createParagraph();
      p.setAlignment(ParagraphAlignment.CENTER);
      p.setWordWrap(true);

      LinkedHashMap<String, LinkedHashMap<String, String>> columns = data.get(table_name);
      int rows = columns.size();
      XWPFTable xTable = xDocument.createTable(rows + 1, 7);
      // 表格属性
      CTTblPr tablePr = xTable.getCTTbl().addNewTblPr();
      // 表格宽度
      CTTblWidth width = tablePr.addNewTblW();
      width.setW(BigInteger.valueOf(8600));

      int i = 0;

      xTable.getRow(i).setHeight(380);
      setCellText(xDocument, xTable.getRow(i).getCell(0), "代码", "CCCCCC", getCellWidth(0));
      setCellText(xDocument, xTable.getRow(i).getCell(1), "注释", "CCCCCC", getCellWidth(1));
      setCellText(xDocument, xTable.getRow(i).getCell(2), "类型", "CCCCCC", getCellWidth(2));
      setCellText(xDocument, xTable.getRow(i).getCell(3), "默认值", "CCCCCC", getCellWidth(3));
      setCellText(xDocument, xTable.getRow(i).getCell(4), "标识", "CCCCCC", getCellWidth(4));
      setCellText(xDocument, xTable.getRow(i).getCell(5), "主键", "CCCCCC", getCellWidth(5));
      setCellText(xDocument, xTable.getRow(i).getCell(6), "空值", "CCCCCC", getCellWidth(6));

      i = i + 1; // 下一行
      int j = 0; // 列column索引

      Map<String, LinkedHashMap<String, String>> keyColumnMap = keyColumns(columns);
      for (Iterator<String> columnNameIter = keyColumnMap.keySet().iterator();
          columnNameIter.hasNext(); ) {
        String column_name = columnNameIter.next();
        LinkedHashMap<String, String> columnsAtt = keyColumnMap.get(column_name);
        int cwidth = getCellWidth(j);
        setCellText(xDocument, xTable.getRow(i).getCell(j), column_name, "FFFFFF", cwidth);
        ++j;

        Iterator<String> columnTypeIter = columnsAtt.keySet().iterator();

        while (columnTypeIter.hasNext()) {
          String colum_type = columnTypeIter.next();
          cwidth = getCellWidth(j);
          setCellText(
              xDocument, xTable.getRow(i).getCell(j), columnsAtt.get(colum_type), "FFFFFF", cwidth);
          j++;
        }

        ++i; // 下一行
        j = 0; // 恢复第一列
      }

      Iterator<String> cloumnsNameIter = columns.keySet().iterator();

      while (cloumnsNameIter.hasNext()) {
        xTable.getRow(i).setHeight(380);
        String colum_name = cloumnsNameIter.next();
        LinkedHashMap<String, String> columnsAtt = columns.get(colum_name);
        int cwidth = getCellWidth(j);
        if (xTable.getRow(i) == null) continue;
        setCellText(xDocument, xTable.getRow(i).getCell(j), colum_name, "FFFFFF", cwidth);

        j++;

        Iterator<String> columnTypeIter = columnsAtt.keySet().iterator();

        while (columnTypeIter.hasNext()) {
          String colum_type = columnTypeIter.next();
          cwidth = getCellWidth(j);
          setCellText(
              xDocument, xTable.getRow(i).getCell(j), columnsAtt.get(colum_type), "FFFFFF", cwidth);
          j++;
        }
        j = 0; // 恢复第一列
        ++i; // 下一行
      }

      XWPFTableRow row = xTable.insertNewTableRow(0);
      row.setHeight(380);
      row.addNewTableCell();
      CTTcPr cellPr = row.getCell(0).getCTTc().addNewTcPr();
      cellPr.addNewTcW().setW(BigInteger.valueOf(1600));
      row.getCell(0).setColor("CCCCCC");
      row.getCell(0).setText("中文名称");
      row.addNewTableCell();
      cellPr = row.getCell(0).getCTTc().addNewTcPr();
      cellPr.addNewTcW().setW(BigInteger.valueOf(3000));
      row.getCell(1).setColor("FFFFFF");
      row.getCell(1).setText(tableinfo.get(table_name));
      row.addNewTableCell();
      cellPr = row.getCell(0).getCTTc().addNewTcPr();
      cellPr.addNewTcW().setW(BigInteger.valueOf(1200));
      row.getCell(2).setColor("CCCCCC");
      row.getCell(2).setText("英文名称");
      row.addNewTableCell();
      CTTc cttc = row.getCell(3).getCTTc();
      CTTcPr ctPr = cttc.addNewTcPr();
      cellPr = row.getCell(0).getCTTc().addNewTcPr();
      cellPr.addNewTcW().setW(BigInteger.valueOf(2800));
      ctPr.addNewGridSpan().setVal(BigInteger.valueOf(4));
      ctPr.addNewHMerge().setVal(STMerge.CONTINUE);
      cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
      cttc.getPList().get(0).addNewR().addNewT().setStringValue(table_name);

      row = xTable.insertNewTableRow(1);
      row.setHeight(380);
      row.addNewTableCell();
      cellPr = row.getCell(0).getCTTc().addNewTcPr();
      cellPr.addNewTcW().setW(BigInteger.valueOf(1600));
      row.getCell(0).setColor("CCCCCC");
      row.getCell(0).setText("功能描述");
      row.addNewTableCell();
      cellPr = row.getCell(0).getCTTc().addNewTcPr();
      cellPr.addNewTcW().setW(BigInteger.valueOf(7000));
      cttc = row.getCell(1).getCTTc();
      ctPr = cttc.addNewTcPr();
      ctPr.addNewGridSpan().setVal(BigInteger.valueOf(6));
      ctPr.addNewHMerge().setVal(STMerge.CONTINUE);
      cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.LEFT);
      cttc.getPList().get(0).addNewR().addNewT().setStringValue("");
    }

    FileOutputStream fos =
        new FileOutputStream(parameters.getPath() + parameters.getDatabase() + "_doc.docx");

    xDocument.write(fos);
    fos.close();
  }