Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:org.kuali.ext.mm.document.web.struts.CountWorksheetPrintAction.java

private void combineAndFlushReportPDFFiles(List<File> fileList, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;//from   w ww.  j a va2  s . c om
    PdfCopy writer = null;
    com.lowagie.text.Document document = null;
    for (File file : fileList) {
        // we create a reader for a certain document
        String reportName = file.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0) {
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            }
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, baos);
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        f++;
    }

    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    document.close();

    StringBuffer sbContentDispValue = new StringBuffer();
    String useJavascript = request.getParameter("useJavascript");
    if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
        sbContentDispValue.append("attachment");
    } else {
        sbContentDispValue.append("inline");
    }
    sbContentDispValue.append("; filename=");
    sbContentDispValue.append(MMUtil.getFileName());

    String contentDisposition = sbContentDispValue.toString();

    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", contentDisposition);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(baos.size());

    // write to output
    ServletOutputStream sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    baos.close();
    sos.close();
    long endTime = System.currentTimeMillis();
    loggerAc.debug("Time taken for report Parameter settings in action " + (endTime - startTime));
}

From source file:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView ics(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {//from w  w  w  .  ja  v a  2s  . c om
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);

        Calendar calendar = feedsBo.buildCalendar(events, Utilities.getBaseUrl(req));

        // flush it in the res
        res.setContentType("text/calendar");
        res.setHeader("Content-Disposition", " attachment; filename=\"JUGEventsCalendar.ics\"");
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0, no-store");
        res.setHeader("Pragma", "public, no-cache");
        res.setCharacterEncoding("UTF-8");

        CalendarOutputter outputter = new CalendarOutputter(true);
        ServletOutputStream resOutputStream = res.getOutputStream();
        if (calendar.getComponents().isEmpty()) {
            outputter.setValidating(false);
        }
        outputter.output(calendar, resOutputStream);
        resOutputStream.flush();
        resOutputStream.close();
    } catch (Exception exception) {
        logger.error("Error producing ICS", exception);
        throw exception;
    }
    return null;
}

From source file:gxu.software_engineering.shen10.market.core.MappingJacksonJsonpView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    //      utf8/*from   w  w w  .j a v a  2 s. co  m*/
    // String charset = response.getCharacterEncoding();
    // if (charset == null || charset.length() == 0) {
    //    response.setCharacterEncoding(DEFAULT_CHARSET);
    // }

    if (request.getMethod().toUpperCase().equals("GET")) {
        if (request.getParameterMap().containsKey("callback")) {
            ServletOutputStream ostream = response.getOutputStream();
            //            try
            ostream.write(new String("try{" + request.getParameter("callback") + "(").getBytes());
            super.render(model, request, response);
            ostream.write(new String(");}catch(e){}").getBytes());
            //            ????closeflushspring?
            //            ?
            ostream.flush();
            ostream.close();
        } else {
            super.render(model, request, response);
        }
    } else {
        super.render(model, request, response);
    }
}

From source file:org.extensiblecatalog.ncip.v2.responder.implprof1.NCIPServlet.java

protected void returnValidationProblem(HttpServletResponse response, ValidationException validationException)
        throws ServletException {

    StringBuffer sb = new StringBuffer();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            // TODO: The version, namespace, etc. ought to come from ServiceContext
            .append("<ns1:NCIPMessage ns1:version=\"http://www.niso.org/ncip/v2_0/imp1/xsd/ncip_v2_0.xsd\"")
            .append(" xmlns:ns1=\"http://www.niso.org/2008/ncip\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"")
            .append(" xsi:schemaLocation=\"http://www.niso.org/2008/ncip ncip_v2_0.xsd\">\n");

    // This hand-marshaling may seem like a bad idea, but we may've entered this method because the marshaling is failing
    List<Problem> problemsList = validationException.getProblems();
    for (Problem p : problemsList) {

        sb.append("  <ns1:Problem>\n");
        ProblemType pt = p.getProblemType();
        if (pt != null) {

            sb.append("    <ns1:ProblemType");
            String scheme = p.getProblemType().getScheme();
            if (scheme != null && !scheme.isEmpty()) {
                sb.append(" ns1:Scheme=\"").append(scheme).append("\"");
            }//from  w  w w  .  j a v a  2  s. c o m
            sb.append(">").append(p.getProblemType().getValue()).append("</ns1:ProblemType>\n");

        }

        String pd = p.getProblemDetail();
        if (pd != null && !pd.isEmpty()) {

            sb.append("    <ns1:ProblemDetail>").append(StringEscapeUtils.escapeXml(pd))
                    .append("</ns1:ProblemDetail>\\n");

        }

        sb.append("  </ns1:Problem>\n");

    }

    sb.append("</ns1:NCIPMessage>");

    byte[] problemMsgBytes = sb.toString().getBytes();

    response.setContentLength(problemMsgBytes.length);

    try {

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(problemMsgBytes);
        outputStream.flush();

    } catch (IOException e) {

        throw new ServletException("Exception writing Problem response.", e);

    }

}

From source file:com.sample.RSSAdapterResource.java

public void execute(HttpUriRequest req, HttpServletResponse resultResponse)
        throws ClientProtocolException, IOException, IllegalStateException, SAXException {
    HttpResponse RSSResponse = client.execute(host, req);
    ServletOutputStream os = resultResponse.getOutputStream();
    if (RSSResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        resultResponse.addHeader("Content-Type", "application/json");
        String json = XML.toJson(RSSResponse.getEntity().getContent());
        os.write(json.getBytes(Charset.forName("UTF-8")));

    } else {// w  ww . j  a v  a2s. com
        resultResponse.setStatus(RSSResponse.getStatusLine().getStatusCode());
        RSSResponse.getEntity().getContent().close();
        os.write(RSSResponse.getStatusLine().getReasonPhrase().getBytes());
    }
    os.flush();
    os.close();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.ViewAllRoomsSchedulesDA.java

public ActionForward downloadScheduleList(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    final ExecutionSemester executionSemester = getExecutionSemester(request);
    final Integer semester = executionSemester.getSemester();
    final String executionYear = executionSemester.getExecutionYear().getYear();

    final Spreadsheet spreadsheet = new Spreadsheet("ScheduleMap");
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionPeriod"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionYear"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionCourse"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionDegree"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.curricular.year"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift.schedule"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift.schedule.hasAllocatedRooms"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.teacher.emails"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.comments"));

    for (final ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) {
        final StringBuilder executionDegreeBuilder = new StringBuilder();
        for (final ExecutionDegree executionDegree : executionCourse.getExecutionDegrees()) {
            if (executionDegreeBuilder.length() > 0) {
                executionDegreeBuilder.append("\n");
            }/*from   w w  w. j  ava 2s  .c o m*/
            executionDegreeBuilder.append(executionDegree.getDegree().getSigla());
        }
        final StringBuilder emailBuilder = new StringBuilder();
        for (final Professorship professorship : executionCourse.getProfessorshipsSet()) {
            if (emailBuilder.length() > 0) {
                emailBuilder.append("\n");
            }
            emailBuilder.append(professorship.getPerson().getEmailForSendingEmails());
        }

        for (final CourseLoad courseLoad : executionCourse.getCourseLoadsSet()) {
            for (final Shift shift : courseLoad.getShiftsSet()) {
                final Set<Integer> curricularYears = new TreeSet<Integer>();
                for (final SchoolClass schoolClass : shift.getAssociatedClassesSet()) {
                    curricularYears.add(schoolClass.getAnoCurricular());
                }
                final StringBuilder curricularYearBuilder = new StringBuilder();
                for (final Integer curricularYear : curricularYears) {
                    if (curricularYearBuilder.length() > 0) {
                        curricularYearBuilder.append(", ");
                    }
                    curricularYearBuilder.append(curricularYear);
                }

                final Row row = spreadsheet.addRow();
                row.setCell(semester);
                row.setCell(executionYear);
                row.setCell(executionCourse.getName());
                row.setCell(executionDegreeBuilder.toString());
                row.setCell(curricularYearBuilder.toString());
                row.setCell(shift.getNome());
                row.setCell(shift.getLessonPresentationString().replace(';', '\n'));
                row.setCell(hasRoomsAttributed(shift));
                row.setCell(emailBuilder.toString());
                row.setCell(shift.getComment() == null ? "" : shift.getComment());
            }
        }
    }

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=scheduleMap"
            + executionYear.replace('/', '_') + "_" + executionSemester.getSemester() + ".xls");

    final ServletOutputStream writer = response.getOutputStream();
    spreadsheet.exportToXLSSheet(writer);
    writer.flush();
    response.flushBuffer();
    return null;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.ViewAllRoomsSchedulesDA.java

public ActionForward downloadShiftAttendence(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    final ExecutionSemester executionSemester = getExecutionSemester(request);
    final String executionYear = executionSemester.getExecutionYear().getYear();

    final Spreadsheet spreadsheet = new Spreadsheet("ShiftAttendenceMap");
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionCourse"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionDegree"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift.schedule"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.lesson.room"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.number.students.enrolled"));

    for (final ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) {
        final StringBuilder executionDegreeBuilder = new StringBuilder();
        for (final ExecutionDegree executionDegree : executionCourse.getExecutionDegrees()) {
            if (executionDegreeBuilder.length() > 0) {
                executionDegreeBuilder.append("\n");
            }/*from  w  w w.j a  va  2 s  . co m*/
            executionDegreeBuilder.append(executionDegree.getDegree().getSigla());
        }
        final StringBuilder emailBuilder = new StringBuilder();
        for (final Professorship professorship : executionCourse.getProfessorshipsSet()) {
            if (emailBuilder.length() > 0) {
                emailBuilder.append("\n");
            }
            emailBuilder.append(professorship.getPerson().getEmailForSendingEmails());
        }

        for (final CourseLoad courseLoad : executionCourse.getCourseLoadsSet()) {
            for (final Shift shift : courseLoad.getShiftsSet()) {
                final Row row = spreadsheet.addRow();
                final StringBuilder roomBuilder = new StringBuilder();
                final StringBuilder scheduleBuilder = new StringBuilder();
                if (!shift.getAssociatedLessonsSet().isEmpty()) {
                    for (Iterator<Lesson> iterator = shift.getAssociatedLessonsSet().iterator(); iterator
                            .hasNext();) {
                        Lesson lesson = iterator.next();
                        scheduleBuilder.append(WeekDay.getWeekDay(lesson.getDiaSemana()).getLabelShort());
                        scheduleBuilder.append(" ");
                        scheduleBuilder.append(lesson.getBeginHourMinuteSecond().toString("HH:mm"));
                        scheduleBuilder.append(" - ");
                        scheduleBuilder.append(lesson.getEndHourMinuteSecond().toString("HH:mm"));
                        if (lesson.hasSala()) {
                            roomBuilder.append(lesson.getSala().getName());
                        }
                        if (iterator.hasNext()) {
                            scheduleBuilder.append(" ; ");
                            roomBuilder.append(" ; ");
                        }
                    }
                }

                row.setCell(shift.getNome());
                row.setCell(executionCourse.getName());
                row.setCell(executionDegreeBuilder.toString());
                row.setCell(scheduleBuilder.toString().replace(';', '\n'));
                row.setCell(roomBuilder.toString().replace(';', '\n'));
                row.setCell(shift.getStudentsSet().size());
            }
        }
    }

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=shiftAttendenceMap"
            + executionYear.replace('/', '_') + "_" + executionSemester.getSemester() + ".xls");

    final ServletOutputStream writer = response.getOutputStream();
    spreadsheet.exportToXLSSheet(writer);
    writer.flush();
    response.flushBuffer();
    return null;
}

From source file:org.openmrs.module.hl7output.web.controller.RHEApatientController.java

@RequestMapping(value = "/{ecID}/encounters", method = RequestMethod.GET)
@ResponseBody//from   ww  w .  j av  a  2 s.c  o  m
public Object getEncounters(@PathVariable("ecID") String enterpriseId,
        @RequestParam(value = "encounterUniqueId", required = false) String encounterUniqueId,
        @RequestParam(value = "dateStart", required = false) String dateStart,
        @RequestParam(value = "dateEnd", required = false) String dateEnd, HttpServletRequest request,
        HttpServletResponse response) throws ResponseException {

    LogEncounterService service = Context.getService(LogEncounterService.class);

    Date fromDate = null;
    Date toDate = null;
    Patient p = null;
    ORU_R01 r01 = null;

    log.info("RHEA Controller call detected...");
    log.info("Enterprise Patient Id is :" + enterpriseId);
    log.info("encounterUniqueId is :" + encounterUniqueId);
    log.info("dateStart is :" + dateStart);

    GetEncounterLog getEncounterLog = new GetEncounterLog();
    getEncounterLog.setEncounterUniqueId(encounterUniqueId);

    // first, we create from and to data objects out of the String
    // parameters

    if (enterpriseId == null) {
        log.info("Error : missing enterpriseId");
        getEncounterLog.setResult("Error, missing enterpriseId");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    getEncounterLog.setEnterpriseId(enterpriseId);

    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    try {
        if (dateStart != null)
            fromDate = format.parse(dateStart);
    } catch (ParseException e) {
        log.info("Error : failed to parse specidied start date : " + dateStart);
        getEncounterLog.setResult("Error, incorrectly parsed start date");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    log.info("fromDate is :" + fromDate);

    try {
        if (dateEnd != null)
            toDate = format.parse(dateEnd);
    } catch (ParseException e) {
        log.info("Error : failed to parse specidied end date : " + dateEnd);
        getEncounterLog.setResult("Error, incorrectly parsed start date");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    log.info("toDate is :" + toDate);

    getEncounterLog.setDateEnd(toDate);
    getEncounterLog.setDateStart(fromDate);

    // Next, we try to retrieve the matching patient object
    if (enterpriseId != null) {
        PatientIdentifierType patientIdentifierType = Context.getPatientService()
                .getPatientIdentifierTypeByName("ECID");
        List<PatientIdentifierType> identifierTypeList = new ArrayList<PatientIdentifierType>();
        identifierTypeList.add(patientIdentifierType);

        List<Patient> patients = Context.getPatientService().getPatients(null, enterpriseId, identifierTypeList,
                false);
        //I am not checking the identifier type here. Need to come back and add a check for this
        if (patients.size() == 1) {
            p = patients.get(0);
        }
    }

    // if the patient doesn't exist, we need to return 400-BAD REQUEST
    // because the parameters are malformed
    if (p == null) {
        log.info("Error : failed to retreive patient for the given uuid : " + enterpriseId);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    } else {
        log.info("Patient id : " + p.getPatientId() + "was retreived...");

        if (p != null) {
            //get all the encounters for this patient
            List<Encounter> encounterList = Context.getEncounterService().getEncountersByPatient(p);
            //if the enconteruniqueId is not null, we can isolate the given encounter

            if (encounterUniqueId != null) {
                Iterator<Encounter> i = encounterList.iterator();
                while (i.hasNext()) {
                    if (!i.next().getUuid().equals(encounterUniqueId))
                        i.remove();
                }
            }

            //If the encounterUniqueId was not given, we will try to filter encounters based on from and to dates
            List<Encounter> filteredEncounterList = new ArrayList<Encounter>();

            if (fromDate != null || toDate != null) {
                for (Encounter encounter : encounterList) {
                    if (fromDate != null && toDate != null) {
                        if ((encounter.getEncounterDatetime().after(fromDate))
                                && (encounter.getEncounterDatetime().before(toDate))) {
                            filteredEncounterList.add(encounter);
                        }

                    } else if (fromDate == null) {
                        if (encounter.getEncounterDatetime().before(toDate)) {
                            filteredEncounterList.add(encounter);
                        }

                    } else {
                        if (encounter.getEncounterDatetime().after(fromDate)) {
                            filteredEncounterList.add(encounter);
                        }

                    }
                }

                log.info("The number of matching encounters are :" + filteredEncounterList.size());
                encounterList = filteredEncounterList;
            }
            log.info("Calling the ORU_R01 parser...");

            SortedSet<MatchingEncounters> encounterSet = new TreeSet<MatchingEncounters>();

            for (Encounter e : encounterList) {
                MatchingEncounters matchingEncounters = new MatchingEncounters();
                matchingEncounters.setGetEncounterLog(getEncounterLog);
                matchingEncounters.setEncounterId(e.getEncounterId());

                encounterSet.add(matchingEncounters);
            }

            getEncounterLog.setLogTime(new Date());
            if (encounterList.size() > 0)
                getEncounterLog.setResult("Results Retrived");
            if (encounterList.size() == 0)
                getEncounterLog.setResult("No Results Retrived");

            //Now we will generate the HL7 message

            GenerateORU_R01 R01Util = new GenerateORU_R01();
            try {
                r01 = R01Util.generateORU_R01Message(p, encounterList);
            } catch (Exception e) {
                getEncounterLog.setResult("Error : Processing hl7 message failed");
                service.saveGetEncounterLog(getEncounterLog);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }

            getEncounterLog.getMatchingEncounters().clear();
            getEncounterLog.setMatchingEncounters(encounterSet);

            service.saveGetEncounterLog(getEncounterLog);

        }

        try {
            // Convert the ORU_R01 object into a byte stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(r01);
            oos.flush();
            oos.close();
            bos.close();
            byte[] data = bos.toByteArray();

            // Write the bytestream into the HttpServletResponse
            ServletOutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();

            response.getWriter().flush();
            response.getWriter().close();

            //NOTE : Im returning the ORU_R01 object as a bytestream AND a session object. Why both ? remove one later !
            request.getSession().setAttribute("oru_r01", r01);

            response.setStatus(HttpServletResponse.SC_OK);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Return null for now
    return null;
}

From source file:module.workingCapital.presentationTier.action.WorkingCapitalAction.java

private ActionForward streamSpreadsheet(final HttpServletResponse response, final String fileName,
        final SpreadsheetBuilder spreadSheetBuilder) throws IOException {
    response.setContentType("application/xls ");
    response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

    ServletOutputStream outputStream = response.getOutputStream();

    spreadSheetBuilder.build(WorkbookExportFormat.EXCEL, outputStream);
    outputStream.flush();
    outputStream.close();/*from w w  w .  ja v a  2  s. c o  m*/

    return null;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.ViewAllRoomsSchedulesDA.java

public ActionForward downloadRoomLessonOccupationInfo(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
    final ExecutionSemester executionSemester = getExecutionSemester(request);

    final ExecutionYear executionYear = executionSemester.getExecutionYear();

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=occupationMap"
            + executionYear.getYear().replace('/', '_') + "_" + executionSemester.getSemester() + ".xls");

    final RoomMap occupationMap = new RoomMap();

    Space.getSpaces().forEach(s -> occupationMap.register(s));

    for (final ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) {
        for (final CourseLoad courseLoad : executionCourse.getCourseLoadsSet()) {
            for (final Shift shift : courseLoad.getShiftsSet()) {
                for (final Lesson lesson : shift.getAssociatedLessonsSet()) {
                    occupationMap.register(lesson);
                }//from   ww w.  j a va  2s.c o m
            }
        }
    }

    final Spreadsheet spreadsheet = new Spreadsheet("OccupationMap");
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.building"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.identification"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.blueprintNumber"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.doorNumber"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.description"));
    spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.classification"));
    final DateTime now = new DateTime();
    for (int weekDay = 0; weekDay < 6; weekDay++) {
        final DateTime dateTime = now.withDayOfWeek(weekDay + 1);
        final String weekDayString = dateTime.dayOfWeek().getAsText(I18N.getLocale());
        for (int hour = 0; hour < 16; hour++) {
            spreadsheet.setHeader(weekDayString + " " + (hour + 8) + ":00");
            spreadsheet.setHeader(weekDayString + " " + (hour + 8) + ":30");
        }
    }
    for (final Entry<Space, boolean[][]> entry : occupationMap.entrySet()) {
        final Space space = entry.getKey();
        final String identification = space.getName();
        final Space building = SpaceUtils.getSpaceBuilding(space);
        final String buildingName = building == null ? "" : building.getPresentationName();
        final boolean[][] slots = entry.getValue();

        final Row row = spreadsheet.addRow();
        row.setCell(buildingName);
        row.setCell(identification == null ? " " : identification);
        final String blueprintNumber = findClosestBlueprintNumber(space);
        row.setCell(blueprintNumber);
        if (SpaceUtils.isRoom(space)) {
            Optional<String> doorNumber = space.getMetadata("doorNumber");
            Optional<String> description = space.getMetadata("description");
            row.setCell(doorNumber.isPresent() ? doorNumber.get() : " ");
            row.setCell(description.isPresent() ? description.get() : " ");
        } else if (SpaceUtils.isRoomSubdivision(space)) {
            final Space room = findSurroundingRoom(space);
            if (room == null) {
                row.setCell(" ");
                row.setCell(" ");
            } else {
                Optional<String> doorNumber = space.getMetadata("doorNumber");
                Optional<String> description = space.getMetadata("description");
                row.setCell(doorNumber.isPresent() ? doorNumber.get() : " ");
                row.setCell(description.isPresent() ? description.get() : " ");
            }
        } else {
            row.setCell(" ");
            row.setCell(" ");
        }
        SpaceClassification classification = space.getClassification();
        if (classification == null) {
            row.setCell(" ");
        } else {
            row.setCell(classification.getAbsoluteCode() + " " + classification.getName().getContent());
        }

        for (int i = 0; i < WEEKDAY_COUNT; i++) {
            for (int j = 0; j < HOUR_COUNT; j++) {
                row.setCell(Boolean.toString(slots[i][j]));
            }
        }
    }

    final ServletOutputStream writer = response.getOutputStream();
    spreadsheet.exportToXLSSheet(writer);
    writer.flush();
    response.flushBuffer();
    return null;
}