List of usage examples for com.itextpdf.text Paragraph add
@Override public boolean add(Element o)
Element
to the Paragraph
. From source file:fenix.planner.pdf.PDFGenerator.java
License:Open Source License
private void parseAndAddBodyTextLineToParagraph(Paragraph paragraph, String line, Font font) { // TODO add support for additional styles // TODO add better error checking and reporting Font currentFont = new Font(font); StringBuilder sb = new StringBuilder(); for (char c : line.toCharArray()) { if (c == '*') { if (sb.length() > 0) { paragraph.add(new Phrase(sb.toString(), currentFont)); sb = new StringBuilder(); }/* www. j a v a 2 s. c om*/ if (currentFont.isBold()) { currentFont = deriveWithStyle(currentFont, currentFont.getStyle() & ~Font.BOLD); } else { currentFont = deriveWithStyle(currentFont, currentFont.getStyle() | Font.BOLD); } } else if (c == '_') { if (sb.length() > 0) { paragraph.add(new Phrase(sb.toString(), currentFont)); sb = new StringBuilder(); } if (currentFont.isItalic()) { currentFont = deriveWithStyle(currentFont, currentFont.getStyle() & ~Font.ITALIC); } else { currentFont = deriveWithStyle(currentFont, currentFont.getStyle() | Font.ITALIC); } } else { sb.append(c); } } paragraph.add(new Phrase(sb.toString(), currentFont)); }
From source file:fll.scheduler.TournamentSchedule.java
License:Open Source License
/** * Output the detailed schedule for a team for the day. * /*from w w w .j av a2 s. com*/ * @throws DocumentException */ private void outputTeamSchedule(final SchedParams params, final Document detailedSchedules, final TeamScheduleInfo si) throws DocumentException { final Paragraph para = new Paragraph(); para.add(new Chunk( String.format("Detailed schedule for Team #%d - %s", si.getTeamNumber(), si.getTeamName()), TEAM_TITLE_FONT)); para.add(Chunk.NEWLINE); para.add(new Chunk(String.format("Organization: %s", si.getOrganization()), TEAM_TITLE_FONT)); para.add(Chunk.NEWLINE); para.add(new Chunk("Division: ", TEAM_HEADER_FONT)); para.add(new Chunk(si.getAwardGroup(), TEAM_VALUE_FONT)); para.add(Chunk.NEWLINE); for (final String subjectiveStation : subjectiveStations) { para.add(new Chunk(subjectiveStation + ": ", TEAM_HEADER_FONT)); final LocalTime start = si.getSubjectiveTimeByName(subjectiveStation).getTime(); final LocalTime end = start.plus(params.getStationByName(subjectiveStation).getDuration()); para.add(new Chunk(String.format("%s - %s", formatTime(start), formatTime(end)), TEAM_VALUE_FONT)); para.add(Chunk.NEWLINE); } for (int round = 0; round < getNumberOfRounds(); ++round) { para.add(new Chunk(String.format(PERF_HEADER_FORMAT, round + 1) + ": ", TEAM_HEADER_FONT)); final LocalTime start = si.getPerfTime(round); final LocalTime end = start.plus(Duration.ofMinutes(params.getPerformanceMinutes())); para.add(new Chunk(String.format("%s - %s %s %d", formatTime(start), formatTime(end), si.getPerfTableColor(round), si.getPerfTableSide(round)), TEAM_VALUE_FONT)); para.add(Chunk.NEWLINE); } para.add(Chunk.NEWLINE); para.add(new Chunk( "Performance rounds must start on time, and will start without you. Please ensure your team arrives at least 5 minutes ahead of scheduled time, and checks in.", TEAM_HEADER_FONT)); para.add(Chunk.NEWLINE); para.add(new Chunk( "Note that there may be more judging and a head to head round after this judging, please see the main tournament schedule for these details.", TEAM_HEADER_FONT)); para.add(Chunk.NEWLINE); para.add(Chunk.NEWLINE); para.add(Chunk.NEWLINE); para.setKeepTogether(true); detailedSchedules.add(para); }
From source file:fll.web.playoff.ScoresheetGenerator.java
License:Open Source License
public void writeFile(final OutputStream out, final boolean orientationIsPortrait) throws DocumentException { // This creates our new PDF document and declares its orientation Document pdfDoc;//from w w w . j a va 2 s . c o m if (orientationIsPortrait) { pdfDoc = new Document(PageSize.LETTER); // portrait } else { pdfDoc = new Document(PageSize.LETTER.rotate()); // landscape } PdfWriter.getInstance(pdfDoc, out); // Measurements are always in points (72 per inch) // This sets up 1/2 inch margins side margins and 0.35in top and bottom // margins pdfDoc.setMargins(0.5f * POINTS_PER_INCH, 0.5f * POINTS_PER_INCH, 0.35f * POINTS_PER_INCH, 0.35f * POINTS_PER_INCH); pdfDoc.open(); // Header cell with challenge title to add to both scoresheets final Paragraph titleParagraph = new Paragraph(); final Chunk titleChunk = new Chunk(m_pageTitle, FontFactory.getFont(FontFactory.HELVETICA_BOLD, 14, Font.NORMAL, BaseColor.WHITE)); titleParagraph.setAlignment(Element.ALIGN_CENTER); titleParagraph.add(titleChunk); titleParagraph.add(Chunk.NEWLINE); final Chunk swVersionChunk = new Chunk("SW version: " + Version.getVersion(), FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, BaseColor.WHITE)); titleParagraph.add(swVersionChunk); if (null != m_revision) { final Chunk revisionChunk = new Chunk(" Descriptor revision: " + m_revision, FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, BaseColor.WHITE)); titleParagraph.add(revisionChunk); } final PdfPCell head = new PdfPCell(); head.setColspan(2); head.setBorder(1); head.setPaddingTop(0); head.setPaddingBottom(3); head.setBackgroundColor(new BaseColor(64, 64, 64)); head.setVerticalAlignment(Element.ALIGN_TOP); head.addElement(titleParagraph); // Cells for score field, and 2nd check initials final Phrase des = new Phrase("Data Entry Score _______", ARIAL_8PT_NORMAL); final PdfPCell desC = new PdfPCell(des); desC.setBorder(0); desC.setPaddingTop(9); desC.setPaddingRight(36); desC.setHorizontalAlignment(Element.ALIGN_RIGHT); final Phrase sci = new Phrase("2nd Check Initials _______", ARIAL_8PT_NORMAL); final PdfPCell sciC = new PdfPCell(sci); sciC.setBorder(0); sciC.setPaddingTop(9); sciC.setPaddingRight(36); sciC.setHorizontalAlignment(Element.ALIGN_RIGHT); // Create a table with a grid cell for each scoresheet on the page PdfPTable wholePage = getTableForPage(orientationIsPortrait); wholePage.setWidthPercentage(100); for (int i = 0; i < m_numSheets; i++) { if (i > 0 && (orientationIsPortrait || (i % 2) == 0)) { pdfDoc.newPage(); wholePage = getTableForPage(orientationIsPortrait); wholePage.setWidthPercentage(100); } // This table is a single score sheet final PdfPTable scoreSheet = new PdfPTable(2); // scoreSheet.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.BOTTOM // | Rectangle.RIGHT | Rectangle.TOP); //FIXME DEBUG should be NO_BORDER scoreSheet.getDefaultCell().setBorder(Rectangle.NO_BORDER); scoreSheet.getDefaultCell().setPaddingRight(1); scoreSheet.getDefaultCell().setPaddingLeft(0); scoreSheet.addCell(head); final PdfPTable teamInfo = new PdfPTable(7); teamInfo.setWidthPercentage(100); teamInfo.setWidths(new float[] { 1f, 1f, 1f, 1f, 1f, 1f, .9f }); // Time label cell final Paragraph timeP = new Paragraph("Time:", ARIAL_10PT_NORMAL); timeP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell timeLc = new PdfPCell(scoreSheet.getDefaultCell()); timeLc.addElement(timeP); teamInfo.addCell(timeLc); // Time value cell final Paragraph timeV = new Paragraph(null == m_time[i] ? SHORT_BLANK : m_time[i], COURIER_10PT_NORMAL); final PdfPCell timeVc = new PdfPCell(scoreSheet.getDefaultCell()); timeVc.addElement(timeV); teamInfo.addCell(timeVc); // Table label cell final Paragraph tblP = new Paragraph("Table:", ARIAL_10PT_NORMAL); tblP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell tblLc = new PdfPCell(scoreSheet.getDefaultCell()); tblLc.addElement(tblP); teamInfo.addCell(tblLc); // Table value cell final Paragraph tblV = new Paragraph(m_table[i], COURIER_10PT_NORMAL); final PdfPCell tblVc = new PdfPCell(scoreSheet.getDefaultCell()); tblVc.addElement(tblV); teamInfo.addCell(tblVc); // Round number label cell final Paragraph rndP = new Paragraph("Round:", ARIAL_10PT_NORMAL); rndP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell rndlc = new PdfPCell(scoreSheet.getDefaultCell()); rndlc.addElement(rndP); teamInfo.addCell(rndlc); // Round number value cell final Paragraph rndV = new Paragraph(m_round[i], COURIER_10PT_NORMAL); final PdfPCell rndVc = new PdfPCell(scoreSheet.getDefaultCell()); // rndVc.setColspan(2); rndVc.addElement(rndV); teamInfo.addCell(rndVc); final PdfPCell temp1 = new PdfPCell(scoreSheet.getDefaultCell()); // temp1.setColspan(2); temp1.addElement(new Paragraph("Judge ____", ARIAL_8PT_NORMAL)); teamInfo.addCell(temp1); // Team number label cell final Paragraph nbrP = new Paragraph("Team #:", ARIAL_10PT_NORMAL); nbrP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell nbrlc = new PdfPCell(scoreSheet.getDefaultCell()); nbrlc.addElement(nbrP); teamInfo.addCell(nbrlc); // Team number value cell final Paragraph nbrV = new Paragraph(null == m_number[i] ? SHORT_BLANK : String.valueOf(m_number[i]), COURIER_10PT_NORMAL); final PdfPCell nbrVc = new PdfPCell(scoreSheet.getDefaultCell()); nbrVc.addElement(nbrV); teamInfo.addCell(nbrVc); // Team division label cell final Paragraph divP = new Paragraph(m_divisionLabel[i], ARIAL_10PT_NORMAL); divP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell divlc = new PdfPCell(scoreSheet.getDefaultCell()); divlc.addElement(divP); divlc.setColspan(2); teamInfo.addCell(divlc); // Team division value cell final Paragraph divV = new Paragraph(m_division[i], COURIER_10PT_NORMAL); final PdfPCell divVc = new PdfPCell(scoreSheet.getDefaultCell()); divVc.setColspan(2); divVc.addElement(divV); teamInfo.addCell(divVc); final PdfPCell temp2 = new PdfPCell(scoreSheet.getDefaultCell()); // temp2.setColspan(2); temp2.addElement(new Paragraph("Team ____", ARIAL_8PT_NORMAL)); teamInfo.addCell(temp2); // Team name label cell final Paragraph nameP = new Paragraph("Team Name:", ARIAL_10PT_NORMAL); nameP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell namelc = new PdfPCell(scoreSheet.getDefaultCell()); namelc.setColspan(2); namelc.addElement(nameP); teamInfo.addCell(namelc); // Team name value cell final Paragraph nameV = new Paragraph(m_name[i], COURIER_10PT_NORMAL); final PdfPCell nameVc = new PdfPCell(scoreSheet.getDefaultCell()); nameVc.setColspan(5); nameVc.addElement(nameV); teamInfo.addCell(nameVc); // add team info cell to the team table final PdfPCell teamInfoCell = new PdfPCell(scoreSheet.getDefaultCell()); teamInfoCell.addElement(teamInfo); teamInfoCell.setColspan(2); scoreSheet.addCell(teamInfoCell); if (null != m_goalsTable) { final PdfPCell goalCell = new PdfPCell(m_goalsTable); goalCell.setBorder(0); goalCell.setPadding(0); goalCell.setColspan(2); scoreSheet.addCell(goalCell); } scoreSheet.addCell(desC); scoreSheet.addCell(sciC); if (null != m_copyright) { final Phrase copyright = new Phrase("\u00A9" + m_copyright, f6i); final PdfPCell copyrightC = new PdfPCell(scoreSheet.getDefaultCell()); copyrightC.addElement(copyright); copyrightC.setBorder(0); copyrightC.setHorizontalAlignment(Element.ALIGN_CENTER); copyrightC.setColspan(2); scoreSheet.addCell(copyrightC); } // the cell in the whole page table that will contain the single score // sheet final PdfPCell scoresheetCell = new PdfPCell(scoreSheet); scoresheetCell.setBorder(0); scoresheetCell.setPadding(0); // Interior borders between scoresheets on a page if (!orientationIsPortrait) { if (i % 2 == 0) { scoresheetCell.setPaddingRight(0.1f * POINTS_PER_INCH); } else { scoresheetCell.setPaddingLeft(0.1f * POINTS_PER_INCH); } } // Add the current scoresheet to the page wholePage.addCell(scoresheetCell); // Add the current table of scoresheets to the document if (orientationIsPortrait || (i % 2 != 0)) { pdfDoc.add(wholePage); } } // Add a blank cells to complete the table of the last page if (!orientationIsPortrait && m_numSheets % 2 != 0) { final PdfPCell blank = new PdfPCell(); blank.setBorder(0); wholePage.addCell(blank); pdfDoc.add(wholePage); } pdfDoc.close(); }
From source file:fll.web.report.FinalComputedScores.java
License:Open Source License
/** * @throws ParseException// w ww . jav a 2 s .com */ private void writeColumnHeaders(final TournamentSchedule schedule, final double[] weights, final ScoreCategory[] subjectiveCategories, final float[] relativeWidths, final ChallengeDescription challengeDescription, final PdfPTable divTable) throws ParseException { // ///////////////////////////////////////////////////////////////////// // Write the table column headers // ///////////////////////////////////////////////////////////////////// // team information final PdfPCell organizationCell = new PdfPCell(new Phrase("Organization", ARIAL_8PT_BOLD)); organizationCell.setBorder(0); organizationCell.setVerticalAlignment(com.itextpdf.text.Element.ALIGN_MIDDLE); divTable.addCell(organizationCell); // judging group if (null != schedule) { final Paragraph judgingGroup = new Paragraph("Judging", ARIAL_8PT_BOLD); judgingGroup.add(Chunk.NEWLINE); judgingGroup.add(new Chunk("Group")); final PdfPCell osCell = new PdfPCell(judgingGroup); osCell.setBorder(0); osCell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER); osCell.setVerticalAlignment(com.itextpdf.text.Element.ALIGN_MIDDLE); divTable.addCell(osCell); } divTable.addCell(""); // weight/raw&scaled for (int cat = 0; cat < subjectiveCategories.length; cat++) { if (weights[cat] > 0.0) { final String catTitle = subjectiveCategories[cat].getTitle(); final Paragraph catPar = new Paragraph(catTitle, ARIAL_8PT_BOLD); final PdfPCell catCell = new PdfPCell(catPar); catCell.setBorder(0); catCell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER); catCell.setVerticalAlignment(com.itextpdf.text.Element.ALIGN_MIDDLE); divTable.addCell(catCell); } } final Paragraph perfPar = new Paragraph("Performance", ARIAL_8PT_BOLD); final PdfPCell perfCell = new PdfPCell(perfPar); perfCell.setBorder(0); perfCell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER); perfCell.setVerticalAlignment(com.itextpdf.text.Element.ALIGN_MIDDLE); divTable.addCell(perfCell); final Paragraph overallScore = new Paragraph("Overall", ARIAL_8PT_BOLD); overallScore.add(Chunk.NEWLINE); overallScore.add(new Chunk("Score")); final PdfPCell osCell = new PdfPCell(overallScore); osCell.setBorder(0); osCell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER); osCell.setVerticalAlignment(com.itextpdf.text.Element.ALIGN_MIDDLE); divTable.addCell(osCell); // ///////////////////////////////////////////////////////////////////// // Write a table row with the relative weights of the subjective scores // ///////////////////////////////////////////////////////////////////// final PdfPCell teamCell = new PdfPCell(new Phrase("Team # / Team Name", ARIAL_8PT_BOLD)); teamCell.setBorder(0); teamCell.setVerticalAlignment(com.itextpdf.text.Element.ALIGN_MIDDLE); divTable.addCell(teamCell); final Paragraph wPar = new Paragraph("Weight:", ARIAL_8PT_NORMAL); final PdfPCell wCell = new PdfPCell(wPar); if (null != schedule) { wCell.setColspan(2); } wCell.setBorder(0); wCell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_RIGHT); divTable.addCell(wCell); final PdfPCell[] wCells = new PdfPCell[subjectiveCategories.length]; final Paragraph[] wPars = new Paragraph[subjectiveCategories.length]; for (int cat = 0; cat < subjectiveCategories.length; cat++) { if (weights[cat] > 0.0) { wPars[cat] = new Paragraph(Double.toString(weights[cat]), ARIAL_8PT_NORMAL); wCells[cat] = new PdfPCell(wPars[cat]); wCells[cat].setBorder(0); wCells[cat].setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER); divTable.addCell(wCells[cat]); } } final PerformanceScoreCategory performanceElement = challengeDescription.getPerformance(); final double perfWeight = performanceElement.getWeight(); final Paragraph perfWeightPar = new Paragraph(Double.toString(perfWeight), ARIAL_8PT_NORMAL); final PdfPCell perfWeightCell = new PdfPCell(perfWeightPar); perfWeightCell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER); perfWeightCell.setBorder(0); divTable.addCell(perfWeightCell); divTable.addCell(""); PdfPCell blankCell = new PdfPCell(); blankCell.setBorder(0); blankCell.setBorderWidthBottom(1.0f); blankCell.setColspan(relativeWidths.length); divTable.addCell(blankCell); // Cause the first 4 rows to be repeated on // each page - 1 row for box header, 2 rows text headers and 1 for // the horizontal line. divTable.setHeaderRows(4); }
From source file:fll.web.report.finalist.AbstractFinalistSchedule.java
License:Open Source License
/** * Create a page for the specified category. * //from ww w . j a v a 2 s . c o m * @throws DocumentException * @throws SQLException */ private void createCategoryPage(final Document document, final Connection connection, final String category, final String room, final FinalistSchedule schedule) throws DocumentException, SQLException { // header name final Paragraph para = new Paragraph(); para.add(Chunk.NEWLINE); para.add(new Chunk(String.format("Finalist schedule for %s", category), TITLE_FONT)); para.add(Chunk.NEWLINE); if (null != room && !"".equals(room)) { para.add(new Chunk(String.format("Room: %s", room), TITLE_FONT)); } document.add(para); final PdfPTable schedTable = new PdfPTable(new float[] { 12.5f, 12.5f, 37.5f, 37.5f }); schedTable.setWidthPercentage(100); schedTable.getDefaultCell().setBorder(0); schedTable.getDefaultCell().enableBorderSide(Rectangle.BOTTOM); schedTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); schedTable.addCell(new Phrase("Time", SCHEDULE_HEADER_FONT)); schedTable.addCell(new Phrase("Team #", SCHEDULE_HEADER_FONT)); schedTable.addCell(new Phrase("Team Name", SCHEDULE_HEADER_FONT)); schedTable.addCell(new Phrase("Organization", SCHEDULE_HEADER_FONT)); // foreach information output for (final FinalistDBRow row : schedule.getScheduleForCategory(category)) { // time, number, name, organization schedTable.addCell(new Phrase(String.format("%d:%02d", row.getHour(), row.getMinute()), SCHEDULE_FONT)); final Team team = Team.getTeamFromDatabase(connection, row.getTeamNumber()); schedTable.addCell(new Phrase(String.valueOf(team.getTeamNumber()), SCHEDULE_FONT)); schedTable.addCell(new Phrase(team.getTeamName(), SCHEDULE_FONT)); schedTable.addCell(new Phrase(team.getOrganization(), SCHEDULE_FONT)); } document.add(schedTable); document.add(Chunk.NEXTPAGE); }
From source file:fll.web.report.finalist.TeamFinalistSchedule.java
License:Open Source License
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { Connection connection = null; try {//w w w . j av a 2s . c o m final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final ChallengeDescription challengeDescription = ApplicationAttributes .getChallengeDescription(application); // create simple doc and write to a ByteArrayOutputStream final Document document = new Document(PageSize.LETTER); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new ReportPageEventHandler(HEADER_FONT, "Finalist Callback Schedule", challengeDescription.getTitle(), Queries.getCurrentTournamentName(connection))); document.open(); document.addTitle("Ranking Report"); // add content final int currentTournament = Queries.getCurrentTournament(connection); final Collection<String> divisions = FinalistSchedule.getAllDivisions(connection, currentTournament); final Collection<FinalistSchedule> schedules = new LinkedList<FinalistSchedule>(); for (final String division : divisions) { final FinalistSchedule schedule = new FinalistSchedule(connection, currentTournament, division); schedules.add(schedule); } final Map<Integer, TournamentTeam> tournamentTeams = Queries.getTournamentTeams(connection, currentTournament); final List<Integer> teamNumbers = new LinkedList<Integer>(tournamentTeams.keySet()); Collections.sort(teamNumbers); for (final int teamNum : teamNumbers) { final TournamentTeam team = tournamentTeams.get(teamNum); for (final FinalistSchedule schedule : schedules) { final List<FinalistDBRow> finalistTimes = schedule.getScheduleForTeam(teamNum); final Map<String, String> rooms = schedule.getRooms(); if (!finalistTimes.isEmpty()) { final Paragraph para = new Paragraph(); para.add(Chunk.NEWLINE); para.add(new Chunk("Finalist times for Team " + teamNum, TITLE_FONT)); para.add(Chunk.NEWLINE); para.add(new Chunk(team.getTeamName() + " / " + team.getOrganization(), TITLE_FONT)); para.add(Chunk.NEWLINE); para.add(new Chunk("Award Group: " + team.getAwardGroup(), TITLE_FONT)); para.add(Chunk.NEWLINE); para.add(Chunk.NEWLINE); final PdfPTable table = new PdfPTable(3); // table.getDefaultCell().setBorder(0); table.setWidthPercentage(100); table.addCell(new Phrase(new Chunk("Time", HEADER_FONT))); table.addCell(new Phrase(new Chunk("Room", HEADER_FONT))); table.addCell(new Phrase(new Chunk("Category", HEADER_FONT))); for (final FinalistDBRow row : finalistTimes) { final String categoryName = row.getCategoryName(); String room = rooms.get(categoryName); if (null == room) { room = ""; } table.addCell(new Phrase(String.format("%d:%02d", row.getHour(), row.getMinute()), VALUE_FONT)); table.addCell(new Phrase(new Chunk(room, VALUE_FONT))); table.addCell(new Phrase(new Chunk(categoryName, VALUE_FONT))); } // foreach row para.add(table); document.add(para); document.add(Chunk.NEXTPAGE); } // non-empty list of teams } // foreach schedule } // foreach team document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "filename=teamFinalistSchedule.pdf"); // the content length is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream final ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (final SQLException e) { LOG.error(e, e); throw new RuntimeException(e); } catch (final DocumentException e) { LOG.error(e, e); throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }
From source file:fll.web.report.PerformanceScoreReport.java
License:Open Source License
@Override protected void processRequest(HttpServletRequest request, HttpServletResponse response, ServletContext application, HttpSession session) throws IOException, ServletException { Connection connection = null; try {/*from w w w .j a v a 2s. c o m*/ final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final ChallengeDescription challengeDescription = ApplicationAttributes .getChallengeDescription(application); final int tournamentId = Queries.getCurrentTournament(connection); final Tournament tournament = Tournament.findTournamentByID(connection, tournamentId); final int numSeedingRounds = TournamentParameters.getNumSeedingRounds(connection, tournament.getTournamentID()); // create simple doc and write to a ByteArrayOutputStream final Document document = new Document(PageSize.LETTER, 36, 36, 72, 36); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PdfWriter writer = PdfWriter.getInstance(document, baos); final PerformanceScoreReportPageEventHandler headerHandler = new PerformanceScoreReportPageEventHandler( HEADER_FONT, REPORT_TITLE, challengeDescription.getTitle(), tournament.getName()); writer.setPageEvent(headerHandler); document.open(); document.addTitle(REPORT_TITLE); final Map<Integer, TournamentTeam> teams = Queries.getTournamentTeams(connection); if (teams.isEmpty()) { final Paragraph para = new Paragraph(); para.add(Chunk.NEWLINE); para.add(new Chunk("No teams in the tournament.")); document.add(para); } else { for (Map.Entry<Integer, TournamentTeam> entry : teams.entrySet()) { headerHandler.setTeamInfo(entry.getValue()); outputTeam(connection, document, tournament, challengeDescription, numSeedingRounds, entry.getValue()); document.add(Chunk.NEXTPAGE); } } document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "filename=performanceScoreReport.pdf"); // the content length is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream final ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (final SQLException e) { LOG.error(e, e); throw new RuntimeException(e); } catch (final DocumentException e) { LOG.error(e, e); throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }
From source file:fll.web.report.PerformanceScoreReport.java
License:Open Source License
private void outputTeam(final Connection connection, final Document document, final Tournament tournament, final ChallengeDescription challenge, final int numSeedingRounds, final TournamentTeam team) throws DocumentException, SQLException { // output first row for header final PdfPTable table = new PdfPTable(numSeedingRounds + 1); table.addCell(""); for (int runNumber = 1; runNumber <= numSeedingRounds; ++runNumber) { table.addCell(new Phrase("Run " + runNumber, HEADER_FONT)); }// w w w . j a v a 2 s . co m final PerformanceScoreCategory performance = challenge.getPerformance(); final TeamScore[] scores = getScores(connection, tournament, team, numSeedingRounds); for (final AbstractGoal goal : performance.getGoals()) { final double bestScore = bestScoreForGoal(scores, goal); final StringBuilder goalTitle = new StringBuilder(); goalTitle.append(goal.getTitle()); if (goal.isComputed()) { goalTitle.append(" (computed)"); } table.addCell(new Phrase(goalTitle.toString(), HEADER_FONT)); for (final TeamScore score : scores) { if (!score.scoreExists() || score.isBye() || score.isNoShow()) { table.addCell(""); } else { final double computedValue = goal.getComputedScore(score); final StringBuilder cellStr = new StringBuilder(); if (!goal.isComputed()) { if (goal.isEnumerated()) { final String enumValue = score.getEnumRawScore(goal.getName()); boolean found = false; for (final EnumeratedValue ev : goal.getValues()) { if (ev.getValue().equals(enumValue)) { cellStr.append(ev.getTitle() + " -> "); found = true; break; } } if (!found) { LOG.warn("Could not find enumerated title for " + enumValue); cellStr.append(enumValue + " -> "); } } else { if (goal.isYesNo()) { if (FP.greaterThan(score.getRawScore(goal.getName()), 0, ChallengeParser.INITIAL_VALUE_TOLERANCE)) { cellStr.append("Yes -> "); } else { cellStr.append("No -> "); } } else { final double rawValue = goal.getRawScore(score); cellStr.append(Utilities.NUMBER_FORMAT_INSTANCE.format(rawValue) + " -> "); } } // not enumerated } // not computed cellStr.append(Utilities.NUMBER_FORMAT_INSTANCE.format(computedValue)); if (FP.equals(bestScore, computedValue, ChallengeParser.INITIAL_VALUE_TOLERANCE)) { table.addCell(new Phrase(cellStr.toString(), BEST_SCORE_FONT)); } else { table.addCell(new Phrase(cellStr.toString(), SCORE_FONT)); } } // exists, non-bye, non-no show } // foreach score } // foreach goal // totals table.addCell(new Phrase("Total", HEADER_FONT)); final double bestTotalScore = bestTotalScore(performance, scores); for (final TeamScore score : scores) { if (!score.scoreExists()) { table.addCell(""); } else if (score.isBye()) { table.addCell(new Phrase("Bye", SCORE_FONT)); } else if (score.isNoShow()) { table.addCell(new Phrase("No Show", SCORE_FONT)); } else { final double totalScore = performance.evaluate(score); if (FP.equals(bestTotalScore, totalScore, ChallengeParser.INITIAL_VALUE_TOLERANCE)) { table.addCell(new Phrase(Utilities.NUMBER_FORMAT_INSTANCE.format(totalScore), BEST_SCORE_FONT)); } else { table.addCell(new Phrase(Utilities.NUMBER_FORMAT_INSTANCE.format(totalScore), SCORE_FONT)); } } } document.add(table); final Paragraph definitionPara = new Paragraph(); definitionPara.add(Chunk.NEWLINE); definitionPara.add(new Chunk("The team's top score for each goal and overall are in bold.")); document.add(definitionPara); }
From source file:fll.web.report.PlayoffReport.java
License:Open Source License
/** * Create the paragraph for the specified division. * //from w ww .j a v a 2 s .c o m * @throws SQLException */ private Paragraph processDivision(final Connection connection, final Tournament tournament, final String division) throws SQLException { PreparedStatement teamPrep = null; ResultSet teamResult = null; PreparedStatement scorePrep = null; ResultSet scoreResult = null; try { final Paragraph para = new Paragraph(); para.add(Chunk.NEWLINE); para.add(new Chunk("Results for head to head bracket " + division, TITLE_FONT)); para.add(Chunk.NEWLINE); final int maxRun = Playoff.getMaxRunNumber(connection, tournament.getTournamentID(), division); if (maxRun < 1) { para.add("Cannot determine max run number for this playoff bracket. This is an internal error"); } else { teamPrep = connection.prepareStatement("SELECT Teams.TeamNumber, Teams.TeamName, Teams.Organization" // + " FROM PlayoffData, Teams" // + " WHERE PlayoffData.Tournament = ?" // + " AND PlayoffData.event_division = ?" // + " AND PlayoffData.run_number = ?" // + " AND Teams.TeamNumber = PlayoffData.team"// + " ORDER BY PlayoffData.linenumber" // ); teamPrep.setInt(1, tournament.getTournamentID()); teamPrep.setString(2, division); scorePrep = connection.prepareStatement("SELECT ComputedTotal" // + " FROM Performance" // + " WHERE Tournament = ?" // + " AND TeamNumber = ?" // + " AND RunNumber = ?"// ); // figure out the last teams final List<String> lastTeams = new LinkedList<>(); teamPrep.setInt(3, maxRun - 1); scorePrep.setInt(1, tournament.getTournamentID()); scorePrep.setInt(3, maxRun - 1); teamResult = teamPrep.executeQuery(); while (teamResult.next()) { final int teamNumber = teamResult.getInt(1); final String teamName = teamResult.getString(2); final String organization = teamResult.getString(3); scorePrep.setInt(2, teamNumber); scoreResult = scorePrep.executeQuery(); final String scoreStr; if (scoreResult.next()) { scoreStr = Utilities.NUMBER_FORMAT_INSTANCE.format(scoreResult.getDouble(1)); } else { scoreStr = "unknown"; } lastTeams.add(String.format("Team %d from %s - %s with a score of %s", teamNumber, organization, teamName, scoreStr)); SQLFunctions.close(scoreResult); scoreResult = null; } SQLFunctions.close(teamResult); teamResult = null; // determine the winners int lastTeamsIndex = 0; teamPrep.setInt(3, maxRun); teamResult = teamPrep.executeQuery(); while (teamResult.next()) { final int teamNumber = teamResult.getInt(1); final String teamName = teamResult.getString(2); para.add(String.format("Competing for places %d and %d", lastTeamsIndex + 1, lastTeamsIndex + 2)); para.add(Chunk.NEWLINE); if (lastTeamsIndex < lastTeams.size()) { para.add(lastTeams.get(lastTeamsIndex)); } else { para.add("Internal error, unknown team competing"); } para.add(Chunk.NEWLINE); ++lastTeamsIndex; if (lastTeamsIndex < lastTeams.size()) { para.add(lastTeams.get(lastTeamsIndex)); } else { para.add("Internal error, unknown team competing"); } para.add(Chunk.NEWLINE); ++lastTeamsIndex; para.add(String.format("The winner is team %d - %s", teamNumber, teamName)); para.add(Chunk.NEWLINE); para.add(Chunk.NEWLINE); } } return para; } finally { SQLFunctions.close(teamResult); SQLFunctions.close(teamPrep); SQLFunctions.close(scoreResult); SQLFunctions.close(scorePrep); } }
From source file:fll.web.report.RankingReport.java
License:Open Source License
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { if (PromptSummarizeScores.checkIfSummaryUpdated(response, application, session, "/report/RankingReport")) { return;//w w w .ja v a2 s . c om } Connection connection = null; try { final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final boolean useQuartiles = GlobalParameters.getUseQuartilesInRankingReport(connection); final ChallengeDescription challengeDescription = ApplicationAttributes .getChallengeDescription(application); // create simple doc and write to a ByteArrayOutputStream final Document document = new Document(PageSize.LETTER); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new ReportPageEventHandler(HEADER_FONT, "Final Computed Rankings", challengeDescription.getTitle(), Queries.getCurrentTournamentName(connection))); document.open(); document.addTitle("Ranking Report"); // add content final Map<Integer, TeamRanking> teamRankings = Queries.getTeamRankings(connection, challengeDescription); final List<Integer> teamNumbers = new LinkedList<Integer>(teamRankings.keySet()); Collections.sort(teamNumbers); final Map<Integer, TournamentTeam> tournamentTeams = Queries.getTournamentTeams(connection); for (final int teamNum : teamNumbers) { final TournamentTeam team = tournamentTeams.get(teamNum); final Paragraph para = new Paragraph(); para.add(Chunk.NEWLINE); para.add(new Chunk("Ranks for Team " + teamNum, TITLE_FONT)); para.add(Chunk.NEWLINE); para.add(new Chunk(team.getTeamName() + " / " + team.getOrganization(), TITLE_FONT)); para.add(Chunk.NEWLINE); para.add(new Chunk("Award Group: " + team.getAwardGroup(), TITLE_FONT)); para.add(Chunk.NEWLINE); para.add(new Chunk( "Each team is ranked in each category in the judging group and award group they were judged in. Performance scores are ranked by division only. Teams may have the same rank if they were tied.", RANK_VALUE_FONT)); para.add(Chunk.NEWLINE); para.add(Chunk.NEWLINE); final TeamRanking teamRanks = teamRankings.get(teamNum); final List<String> categories = teamRanks.getCategories(); Collections.sort(categories); // pull out performance next if (categories.contains(CategoryRank.PERFORMANCE_CATEGORY_NAME)) { final String category = CategoryRank.PERFORMANCE_CATEGORY_NAME; outputCategory(para, teamRanks, category, useQuartiles); } para.add(Chunk.NEWLINE); for (final String category : categories) { if (!CategoryRank.PERFORMANCE_CATEGORY_NAME.equals(category) && !CategoryRank.OVERALL_CATEGORY_NAME.equals(category)) { outputCategory(para, teamRanks, category, useQuartiles); } } document.add(para); final Paragraph definitionPara = new Paragraph(); definitionPara.add(Chunk.NEWLINE); definitionPara.add(new Chunk( "The 1st quartile is the top 25% of teams, 2nd quartile is the next 25%, quartiles 3 and 4 are the following 25% groupings of teams.")); document.add(definitionPara); document.add(Chunk.NEXTPAGE); } document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "filename=rankingReport.pdf"); // the content length is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream final ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (final SQLException e) { LOG.error(e, e); throw new RuntimeException(e); } catch (final DocumentException e) { LOG.error(e, e); throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }