Example usage for javax.servlet.http HttpServletResponse flushBuffer

List of usage examples for javax.servlet.http HttpServletResponse flushBuffer

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse flushBuffer.

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

From source file:org.wrml.server.WrmlServlet.java

void writeModelAsResponseEntity(final HttpServletResponse response, final Model responseModel,
        final List<MediaType> acceptableMediaTypes, final Method method)
        throws MediaTypeException, ServletException, IOException {

    // Set the content type
    MediaType responseEntityMediaType = getMostAcceptableMediaType(responseModel.getSchemaUri(),
            acceptableMediaTypes);/*from   ww w.  j  a v  a2s  .c  o  m*/
    if (responseEntityMediaType == null) {
        responseEntityMediaType = getDefaultMediaType();
    }
    final String contentTypeHeaderValue = responseEntityMediaType.toContentType();
    response.setContentType(contentTypeHeaderValue);

    LOGGER.debug("Responding with Content-Type: " + contentTypeHeaderValue);

    // Set the locale
    final Dimensions responseDimensions = responseModel.getDimensions();
    final Locale responseLocale = responseDimensions.getLocale();
    if (responseLocale != null) {
        response.setLocale(responseLocale);
    }

    // Set the status
    response.setStatus(HttpServletResponse.SC_OK);

    final boolean noBody = !method.isEntityAllowedInResponseMessage();
    if (noBody) {
        response.setContentLength(0);
    } else {
        final Context context = getContext();
        // TODO This isn't great
        final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();

        // Set the format for output
        URI formatUri = null;
        if (responseEntityMediaType.getFullType().equals(SystemMediaType.MEDIA_TYPE_STRING_WRML)) {
            final String format = responseEntityMediaType.getParameter(SystemMediaType.PARAMETER_NAME_FORMAT);
            if (format != null) {
                formatUri = URI.create(format);
            }
        } else {
            formatUri = getLoadedFormatUri(responseEntityMediaType);
        }

        // TODO Unfunkify this
        context.writeModel(byteOut, responseModel, formatUri);

        final byte[] modelBytes = byteOut.toByteArray();
        final int contentLength = modelBytes.length;
        response.setContentLength(contentLength);

        final OutputStream responseOut = response.getOutputStream();
        IOUtils.write(modelBytes, responseOut);
        // Make sure it's on the wire
        responseOut.flush();
        // Close our stream
        responseOut.close();
    }

    response.flushBuffer();
    // TODO: response.setBufferSize(?); - Is this needed?
    // TODO: response.setCharacterEncoding(?); - Is this needed?
    // TODO: Set other headers as needed.
}

From source file:org.kuali.coeus.propdev.impl.s2s.ProposalDevelopmentS2SController.java

@Transactional
@RequestMapping(value = "/proposalDevelopment", params = { "methodToCall=printForms" })
public ModelAndView printForms(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form,
        HttpServletResponse response) throws Exception {
    ProposalDevelopmentDocument proposalDevelopmentDocument = form.getProposalDevelopmentDocument();

    proposalDevelopmentDocumentViewAuthorizer
            .initializeDocumentAuthorizerIfNecessary(form.getProposalDevelopmentDocument());

    if (!((ProposalDevelopmentDocumentAuthorizer) proposalDevelopmentDocumentViewAuthorizer
            .getDocumentAuthorizer()).isAuthorizedToPrint(proposalDevelopmentDocument,
                    globalVariableService.getUserSession().getPerson())) {
        throw new AuthorizationException(globalVariableService.getUserSession().getPrincipalName(),
                "printForms", "Proposal");
    }/* ww  w.  ja v a2  s  .  c  om*/

    if (proposalDevelopmentDocument.getDevelopmentProposal().getSelectedS2sOppForms().isEmpty()) {
        getGlobalVariableService().getMessageMap().putError("noKey", ERROR_NO_GRANTS_GOV_FORM_SELECTED);
        return getModelAndViewService().getModelAndView(form);
    }
    FormPrintResult formPrintResult = getFormPrintService().printForm(proposalDevelopmentDocument);

    setValidationErrorMessage(formPrintResult.getErrors());
    KcFile attachmentDataSource = formPrintResult.getFile();
    if (((attachmentDataSource == null || attachmentDataSource.getData() == null
            || attachmentDataSource.getData().length == 0)
            && !proposalDevelopmentDocument.getDevelopmentProposal().getGrantsGovSelectFlag())
            || CollectionUtils.isNotEmpty(formPrintResult.getErrors())) {
        boolean grantsGovErrorExists = copyAuditErrorsToPage(Constants.GRANTSGOV_ERRORS,
                "grantsGovFormValidationErrors");
        if (grantsGovErrorExists) {
            getGlobalVariableService().getMessageMap().putError("grantsGovFormValidationErrors",
                    KeyConstants.VALIDATTION_ERRORS_BEFORE_GRANTS_GOV_SUBMISSION);
        }
        proposalDevelopmentDocument.getDevelopmentProposal().setGrantsGovSelectFlag(false);
        return getModelAndViewService().getModelAndView(form);
    }
    if (proposalDevelopmentDocument.getDevelopmentProposal().getGrantsGovSelectFlag()) {
        File grantsGovXmlDirectoryFile = getS2sSubmissionService()
                .getGrantsGovSavedFile(proposalDevelopmentDocument);
        byte[] bytes = new byte[(int) grantsGovXmlDirectoryFile.length()];
        FileInputStream fileInputStream = new FileInputStream(grantsGovXmlDirectoryFile);
        fileInputStream.read(bytes);
        int size = bytes.length;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(size)) {
            outputStream.write(bytes);
            ControllerFileUtils.streamOutputToResponse(response, outputStream, "binary/octet-stream",
                    grantsGovXmlDirectoryFile.getName(), size);
            response.flushBuffer();
        }
        proposalDevelopmentDocument.getDevelopmentProposal().setGrantsGovSelectFlag(false);
        return getModelAndViewService().getModelAndView(form);
    }

    ControllerFileUtils.streamToResponse(attachmentDataSource, response);
    return getModelAndViewService().getModelAndView(form);
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

private synchronized void initializeServer(final ProcessContext context) throws Exception {
    if (initialized.get()) {
        return;/*from   w w  w . j a va2s .  c o m*/
    }
    this.containerQueue = new LinkedBlockingQueue<>(context.getProperty(CONTAINER_QUEUE_SIZE).asInteger());
    final String host = context.getProperty(HOSTNAME).getValue();
    final int port = context.getProperty(PORT).asInteger();
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT)
            .asControllerService(SSLContextService.class);

    final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
    final boolean need;
    final boolean want;
    if (CLIENT_NEED.equals(clientAuthValue)) {
        need = true;
        want = false;
    } else if (CLIENT_WANT.equals(clientAuthValue)) {
        need = false;
        want = true;
    } else {
        need = false;
        want = false;
    }

    final SslContextFactory sslFactory = (sslService == null) ? null : createSslFactory(sslService, need, want);
    final Server server = new Server(port);

    // create the http configuration
    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    if (sslFactory == null) {
        // create the connector
        final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));

        // set host and port
        if (StringUtils.isNotBlank(host)) {
            http.setHost(host);
        }
        http.setPort(port);

        // add this connector
        server.setConnectors(new Connector[] { http });
    } else {
        // add some secure config
        final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
        httpsConfiguration.setSecureScheme("https");
        httpsConfiguration.setSecurePort(port);
        httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

        // build the connector
        final ServerConnector https = new ServerConnector(server,
                new SslConnectionFactory(sslFactory, "http/1.1"),
                new HttpConnectionFactory(httpsConfiguration));

        // set host and port
        if (StringUtils.isNotBlank(host)) {
            https.setHost(host);
        }
        https.setPort(port);

        // add this connector
        server.setConnectors(new Connector[] { https });
    }

    final Set<String> allowedMethods = new HashSet<>();
    if (context.getProperty(ALLOW_GET).asBoolean()) {
        allowedMethods.add("GET");
    }
    if (context.getProperty(ALLOW_POST).asBoolean()) {
        allowedMethods.add("POST");
    }
    if (context.getProperty(ALLOW_PUT).asBoolean()) {
        allowedMethods.add("PUT");
    }
    if (context.getProperty(ALLOW_DELETE).asBoolean()) {
        allowedMethods.add("DELETE");
    }
    if (context.getProperty(ALLOW_HEAD).asBoolean()) {
        allowedMethods.add("HEAD");
    }
    if (context.getProperty(ALLOW_OPTIONS).asBoolean()) {
        allowedMethods.add("OPTIONS");
    }

    final String additionalMethods = context.getProperty(ADDITIONAL_METHODS).getValue();
    if (additionalMethods != null) {
        for (final String additionalMethod : additionalMethods.split(",")) {
            final String trimmed = additionalMethod.trim();
            if (!trimmed.isEmpty()) {
                allowedMethods.add(trimmed.toUpperCase());
            }
        }
    }

    final String pathRegex = context.getProperty(PATH_REGEX).getValue();
    final Pattern pathPattern = (pathRegex == null) ? null : Pattern.compile(pathRegex);

    server.setHandler(new AbstractHandler() {
        @Override
        public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
                final HttpServletResponse response) throws IOException, ServletException {

            final String requestUri = request.getRequestURI();
            if (!allowedMethods.contains(request.getMethod().toUpperCase())) {
                getLogger().info(
                        "Sending back METHOD_NOT_ALLOWED response to {}; method was {}; request URI was {}",
                        new Object[] { request.getRemoteAddr(), request.getMethod(), requestUri });
                response.sendError(Status.METHOD_NOT_ALLOWED.getStatusCode());
                return;
            }

            if (pathPattern != null) {
                final URI uri;
                try {
                    uri = new URI(requestUri);
                } catch (final URISyntaxException e) {
                    throw new ServletException(e);
                }

                if (!pathPattern.matcher(uri.getPath()).matches()) {
                    response.sendError(Status.NOT_FOUND.getStatusCode());
                    getLogger().info("Sending back NOT_FOUND response to {}; request was {} {}",
                            new Object[] { request.getRemoteAddr(), request.getMethod(), requestUri });
                    return;
                }
            }

            // If destination queues full, send back a 503: Service Unavailable.
            if (context.getAvailableRelationships().isEmpty()) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            }

            // Right now, that information, though, is only in the ProcessSession, not the ProcessContext,
            // so it is not known to us. Should see if it can be added to the ProcessContext.
            final AsyncContext async = baseRequest.startAsync();
            async.setTimeout(Long.MAX_VALUE); // timeout is handled by HttpContextMap
            final boolean added = containerQueue.offer(new HttpRequestContainer(request, response, async));

            if (added) {
                getLogger().debug("Added Http Request to queue for {} {} from {}",
                        new Object[] { request.getMethod(), requestUri, request.getRemoteAddr() });
            } else {
                getLogger().info("Sending back a SERVICE_UNAVAILABLE response to {}; request was {} {}",
                        new Object[] { request.getRemoteAddr(), request.getMethod(), request.getRemoteAddr() });

                response.sendError(Status.SERVICE_UNAVAILABLE.getStatusCode());
                response.flushBuffer();
                async.complete();
            }
        }
    });

    this.server = server;
    server.start();

    getLogger().info("Server started and listening on port " + getPort());

    initialized.set(true);
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void commitResponse(javax.servlet.http.HttpServletResponse response) {
    if (!response.isCommitted()) {
        try {/*from   ww  w  .j a  va 2s .co  m*/
            response.flushBuffer();
        } catch (IOException e) {
        }
    }
}

From source file:org.openqa.grid.internal.TestSession.java

/**
 * forwards the request to the node.//  ww  w .  jav a2s  .com
 */
public String forward(SeleniumBasedRequest request, HttpServletResponse response, boolean newSessionRequest)
        throws IOException {
    String res = null;

    String currentThreadName = Thread.currentThread().getName();
    setThreadDisplayName();
    forwardingRequest = true;

    try {
        if (slot.getProxy() instanceof CommandListener) {
            ((CommandListener) slot.getProxy()).beforeCommand(this, request, response);
        }

        lastActivity = timeSource.currentTimeInMillis();

        HttpRequest proxyRequest = prepareProxyRequest(request/*, config*/);

        HttpResponse proxyResponse = sendRequestToNode(proxyRequest);
        lastActivity = timeSource.currentTimeInMillis();

        final int statusCode = proxyResponse.getStatusLine().getStatusCode();
        response.setStatus(statusCode);
        processResponseHeaders(request, response, slot.getRemoteURL(), proxyResponse);

        byte[] consumedNewWebDriverSessionBody = null;
        if (statusCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                && statusCode != HttpServletResponse.SC_NOT_FOUND) {
            consumedNewWebDriverSessionBody = updateHubIfNewWebDriverSession(request, proxyResponse);
        }
        if (newSessionRequest && statusCode == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            removeIncompleteNewSessionRequest();
        }
        if (statusCode == HttpServletResponse.SC_NOT_FOUND) {
            removeSessionBrowserTimeout();
        }

        HttpEntity responseBody = proxyResponse.getEntity();
        byte[] contentBeingForwarded = null;
        if (responseBody != null) {
            try {
                InputStream in;
                if (consumedNewWebDriverSessionBody == null) {
                    in = responseBody.getContent();
                    if (request.getRequestType() == RequestType.START_SESSION
                            && request instanceof LegacySeleniumRequest) {
                        res = getResponseUtf8Content(in);

                        updateHubNewSeleniumSession(res);

                        in = new ByteArrayInputStream(res.getBytes("UTF-8"));
                    }
                } else {
                    in = new ByteArrayInputStream(consumedNewWebDriverSessionBody);
                }

                final byte[] bytes = drainInputStream(in);
                writeRawBody(response, bytes);

            } finally {
                EntityUtils.consume(responseBody);
            }

        }

        if (slot.getProxy() instanceof CommandListener) {
            SeleniumBasedResponse wrappedResponse = new SeleniumBasedResponse(response);
            wrappedResponse.setForwardedContent(contentBeingForwarded);
            ((CommandListener) slot.getProxy()).afterCommand(this, request, wrappedResponse);
        }
        response.flushBuffer();
        return res;
    } finally {
        forwardingRequest = false;
        Thread.currentThread().setName(currentThreadName);
    }
}

From source file:org.openmrs.module.pharmacy.web.controller.DrugDispense.java

@RequestMapping(method = RequestMethod.GET, value = "module/pharmacy/drugDispense")
public synchronized void pageLoad(HttpServletRequest request, HttpServletResponse response) {
    String locationVal = null;/*www  .  j  av  a  2s .co  m*/
    service = Context.getService(PharmacyService.class);
    pharmacyLocationUserses = service
            .getPharmacyLocationUsersByUserName(Context.getAuthenticatedUser().getUsername());
    sizeUsers = pharmacyLocationUserses.size();

    if (sizeUsers > 1) {
        locationVal = request.getSession().getAttribute("location").toString();

    } else if (sizeUsers == 1) {
        locationVal = pharmacyLocationUserses.get(0).getLocation();

    }
    userService = Context.getUserContext();

    service = Context.getService(PharmacyService.class);
    serviceLocation = Context.getLocationService();
    datadFrm = new JSONArray();

    drugDispenseSettings = service.getDrugDispenseSettings();

    size = drugDispenseSettings.size();
    currentDate = Calendar.getInstance();
    readDate = Calendar.getInstance();

    dateC = new Date();

    currentDate.setTime(dateC);

    gregorianCalendar = new GregorianCalendar();
    calendar = new GregorianCalendar();

    gregorianCalendar.set(currentDate.get(currentDate.YEAR), currentDate.get(currentDate.MONTH),
            currentDate.get(currentDate.DAY_OF_MONTH));

    try {

        json = new JSONObject();
        if (dialogShow != null && dialog == null) {
            if (size != 0) {

                for (int i = 0; i < size; i++) {

                    if (service.getPharmacyLocationsByUuid(drugDispenseSettings.get(i).getLocation().getUuid())

                            .getName().equalsIgnoreCase(locationVal)) {
                        datadFrm = new JSONArray();

                        datadFrm = getArrayDialog(drugDispenseSettings, i, dialogShow, locationVal);

                        if (datadFrm != null)
                            json.accumulate("aaData", datadFrm);
                    }

                }

            }
            if (!json.has("aaData")) {

                datad2 = new JSONArray();
                datad2.put("None");
                datad2.put("None");
                datad2.put("None");
                datad2.put("None");
                datad2.put("None");
                datad2.put("None");
                datad2.put("None");
                datad2.put("None");
                datad2.put("None");
                datad2.put("None");
                datad2.put("");

                json.accumulate("aaData", datad2);

            }
            dialogShow = null;

            json.accumulate("iTotalRecords", json.getJSONArray("aaData").length());
            json.accumulate("iTotalDisplayRecords", json.getJSONArray("aaData").length());
            json.accumulate("iDisplayStart", 0);
            json.accumulate("iDisplayLength", 10);

            response.getWriter().print(json);

            response.flushBuffer();
        } else if (dialog != null && dialogShow == null) {

            List<PharmacyStore> listStore = service.getPharmacyInventory();
            int sizeStore = listStore.size();

            for (int i = 0; i < sizeStore; i++) {

                if (service.getPharmacyLocationsByUuid(listStore.get(i).getLocation()).getName()
                        .equalsIgnoreCase(locationVal)) {

                    datadFrm = new JSONArray();

                    datadFrm = getArray(listStore, i, dialog, locationVal);
                    if (datadFrm != null)
                        json.accumulate("aaData", datadFrm);
                }

                datad2 = new JSONArray();
            }

            if (!json.has("aaData")) {
                datad2 = new JSONArray();

                datad2.put("None");
                datad2.put("None");
                datad2.put("None");

                datad2.put("None");
                datad2.put("None");
                datad2.put("None");

                json.accumulate("aaData", datad2);
            }
            dialog = null;
            json.accumulate("iTotalRecords", json.getJSONArray("aaData").length());
            json.accumulate("iTotalDisplayRecords", json.getJSONArray("aaData").length());
            json.accumulate("iDisplayStart", 0);
            json.accumulate("iDisplayLength", 10);

            response.getWriter().print(json);

            response.flushBuffer();
        } else if (dose != null) {

            DrugDispenseSettings drugDispense = new DrugDispenseSettings();
            //change calendar
            datad2 = new JSONArray();
            if (Context.getConceptService().getDrugByNameOrId(dose) != null
                    && service.getDrugDispenseSettingsByDrugId(
                            Context.getConceptService().getDrugByNameOrId(dose)) != null) {

                drugDispense = service
                        .getDrugDispenseSettingsByDrugId(Context.getConceptService().getDrugByNameOrId(dose));
                datad2.put(drugDispense.getOption().getName());
                datad2.put(drugDispense.getValue());

                datad2.put(drugDispense.getAmount());
            } else {
                datad2.put(0);
                datad2.put(0);

                datad2.put(0);
            }

            //json.accumulate("aaData", datad2);

            response.getWriter().print(datad2);

            response.flushBuffer();

        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error("Error generated", e);
    }

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.teacher.onlineTests.TestsManagementAction.java

public ActionForward showImage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {
    final String exerciseCode = getStringFromRequest(request, "exerciseCode");
    final Integer imgCode = getCodeFromRequest(request, "imgCode");
    final String imgTypeString = request.getParameter("imgType");
    final String studentCode = getStringFromRequest(request, "studentCode");
    final String optionShuffle = request.getParameter("optionShuffle");
    final String testCode = getStringFromRequest(request, "testCode");
    final Integer itemIndex = getCodeFromRequest(request, "item");
    final Integer feedbackCode = getCodeFromRequest(request, "feedbackCode");
    String img = null;/*w ww  .j a  v  a 2 s.com*/
    if (studentCode != null && testCode != null) {
        try {
            img = ReadStudentTestQuestionImage.run(studentCode, testCode, exerciseCode, imgCode, feedbackCode,
                    itemIndex);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    } else if (optionShuffle != null && !Strings.isNullOrEmpty(testCode)) {
        try {
            img = ReadQuestionImage.run(testCode, exerciseCode, optionShuffle, imgCode, feedbackCode);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    } else {

        try {
            img = ReadQuestionImage.run(exerciseCode, imgCode, feedbackCode, itemIndex);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    }
    byte[] imageData = BaseEncoding.base64().decode(img);
    try {
        response.reset();
        response.setContentType(imgTypeString);
        response.setContentLength(imageData.length);
        response.setBufferSize(imageData.length);
        String imageName = "image" + exerciseCode + imgCode + "."
                + imgTypeString.substring(imgTypeString.lastIndexOf("/") + 1, imgTypeString.length());
        response.setHeader("Content-disposition", "attachment; filename=" + imageName);
        DataOutputStream dataOut = new DataOutputStream(response.getOutputStream());
        dataOut.write(imageData);
        response.flushBuffer();
    } catch (java.io.IOException e) {
        throw new FenixActionException(e);
    }
    return null;
}

From source file:org.dataone.proto.trove.mn.rest.v1.ObjectController.java

/**
 * Describe the object requested, this is no body returned, only HTTP header info
 *
 * @param request/*  w w  w  .  j  a  va  2s  . com*/
 * @param response
 * @param pid
 * @throws InvalidToken
 * @throws ServiceFailure
 * @throws IOException
 * @throws NotAuthorized
 * @throws NotFound
 * @throws NotImplemented
 */
@RequestMapping(value = "/v1/object/{pid}", method = RequestMethod.HEAD)
public void describe(HttpServletRequest request, HttpServletResponse response, @PathVariable String pid)
        throws InvalidToken, ServiceFailure, IOException, NotAuthorized, NotFound, NotImplemented,
        InvalidRequest {

    debugRequest(request);
    Identifier id = new Identifier();
    try {
        id.setValue(urlCodec.decode(pid, "UTF-8"));
    } catch (DecoderException ex) {
        throw new ServiceFailure("20000", ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        throw new ServiceFailure("20001", ex.getMessage());
    }
    Session session = new Session();
    DescribeResponse describe = mnRead.describe(session, id);
    response.addHeader("Content-Length", describe.getContent_Length().toString());

    /* FROM http://www.ietf.org/rfc/rfc2822.txt
     * Internet Message Format
     * 3.3. Date and Time Specification ..............................14
     *
     *  Date and time occur in several header fields.  This section specifies
     *  the syntax for a full date and time specification.  Though folding
     *  white space is permitted throughout the date-time specification, it
     *  is RECOMMENDED that a single space be used in each place that FWS
     *  appears (whether it is required or optional); some older
     *  implementations may not interpret other occurrences of folding white
     *  space correctly.
     *
     *  date-time       =       [ day-of-week "," ] date FWS time [CFWS]
     *
     *  day-of-week     Logger d1Log = DataONELog.getLogger(MNReadImpl.class.getName());    =       ([FWS] day-name) / obs-day-of-week
     *
     *  day-name        =       "Mon" / "Tue" / "Wed" / "Thu" /
     *                          "Fri" / "Sat" / "Sun"
     *
     *  date            =       day month year
     *
     *  year            =       4*DIGIT / obs-year
     *
     *  month           =       (FWS month-name FWS) / obs-month
     *
     *  month-name      =       "Jan" / "Feb" / "Mar" / "Apr" /
     *                          "May" / "Jun" / "Jul" / "Aug" /
     *                          "Sep" / "Oct" / "Nov" / "Dec"
     *
     *  day             =       ([FWS] 1*2DIGIT) / obs-day
     *
     *  time            =       time-of-day FWS zone
     *
     *  time-of-day     =       hour ":" minute [ ":" second ]
     *
     *  hour            =       2DIGIT / obs-hour
     *
     *  minute          =       2DIGIT / obs-minute
     *
     *  second          =       2DIGIT / obs-second
     *
     *  zone            =       (( "+" / "-" ) 4DIGIT) / obs-zone
     *
     */
    DateTime lastModifiedDate = new DateTime(describe.getLast_Modified(), DateTimeZone.UTC);
    response.addHeader("Last-Modified", lastModifiedDate.toString());
    response.addHeader("DataONE-ObjectFormat", describe.getDataONE_ObjectFormatIdentifier().getValue());
    response.addHeader("DataONE-Checksum",
            describe.getDataONE_Checksum().getAlgorithm() + "," + describe.getDataONE_Checksum().getValue());
    OutputStream out = response.getOutputStream();
    response.flushBuffer();
    out.close();
}

From source file:org.fenixedu.parking.ui.Action.ParkingManagerDispatchAction.java

public ActionForward exportToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    ParkingRequestSearch parkingRequestSearch = new ParkingRequestSearch();
    setSearchCriteria(request, parkingRequestSearch);
    parkingRequestSearch.doSearch();/*  w  w w  .  ja va 2 s  . c o m*/
    List<ParkingRequest> parkingRequestList = parkingRequestSearch.getSearchResult();
    StyledExcelSpreadsheet spreadsheet = new StyledExcelSpreadsheet("Pedidos_Parque", 15);
    spreadsheet.newHeaderRow();
    spreadsheet.addHeader("Categoria");
    spreadsheet.addHeader("Nmero");
    spreadsheet.addHeader("Nome", 9000);
    spreadsheet.addHeader("Estado");
    spreadsheet.addHeader("Data Pedido");
    spreadsheet.addHeader("Outras Informaes", 6000);

    final ResourceBundle enumerationBundle = ResourceBundle.getBundle("resources.EnumerationResources",
            I18N.getLocale());
    for (ParkingRequest parkingRequest : parkingRequestList) {
        if (parkingRequest.getParkingParty().getParty().isPerson()) {
            Person person = (Person) parkingRequest.getParkingParty().getParty();
            spreadsheet.newRow();
            int firstRow = spreadsheet.getRow().getRowNum();
            spreadsheet
                    .addCell(enumerationBundle.getString(parkingRequestSearch.getPartyClassification().name()));
            spreadsheet.addCell(parkingRequest.getParkingParty().getMostSignificantNumber());
            spreadsheet.addCell(person.getName());
            spreadsheet.addCell(enumerationBundle.getString(parkingRequest.getParkingRequestState().name()));
            spreadsheet.addDateTimeCell(parkingRequest.getCreationDate());
            if (!parkingRequest.getParkingParty().getDegreesInformation().isEmpty()) {
                Iterator<String> iterator = parkingRequest.getParkingParty().getDegreesInformation().iterator();
                String degreeInfo = iterator.next();
                spreadsheet.addCell(degreeInfo);
                while (iterator.hasNext()) {
                    spreadsheet.newRow();
                    degreeInfo = iterator.next();
                    spreadsheet.addCell(degreeInfo, 5);
                }
                int lastRow = firstRow + parkingRequest.getParkingParty().getDegreesInformation().size() - 1;
                if (firstRow != lastRow) {
                    for (int iter = 0; iter < 5; iter++) {
                        spreadsheet.getSheet()
                                .addMergedRegion(new Region(firstRow, (short) iter, lastRow, (short) iter));
                    }
                }
            }
        }
    }
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=pedidos_parque.xls");
    final ServletOutputStream writer = response.getOutputStream();
    spreadsheet.getWorkbook().write(writer);
    writer.flush();
    response.flushBuffer();
    return null;
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

private boolean doKerberosDelegateLogin(HttpServletRequest req, HttpServletResponse res, HttpSession session,
        String userName, String tokenForEndpoint) throws IOException {

    try {//from w w w  . j a v a 2s . c  o  m
        Connector conn = connectorService.getConnector(this.endpoint, session);
        ConnectorContext ctx;

        // ALF-10785: We must pass through the language header to set up the session in the correct locale            
        if (req.getHeader(HEADER_ACCEPT_LANGUAGE) != null) {
            if (logger.isDebugEnabled())
                logger.debug("Accept-Language header present: " + req.getHeader(HEADER_ACCEPT_LANGUAGE));
            Map<String, String> headers = new HashMap(7);
            headers.put(HEADER_ACCEPT_LANGUAGE, req.getHeader(HEADER_ACCEPT_LANGUAGE));

            ctx = new ConnectorContext(null, headers);
        } else {
            ctx = new ConnectorContext();
        }

        Response remoteRes = conn.call("/touch", ctx);
        if (Status.STATUS_UNAUTHORIZED == remoteRes.getStatus().getCode()) {
            String authHdr = remoteRes.getStatus().getHeaders().get(HEADER_WWWAUTHENTICATE);
            if (authHdr.equals(AUTH_SPNEGO)) {
                Map<String, String> headers = new HashMap(7);
                headers.put(HEADER_AUTHORIZATION, AUTH_SPNEGO + ' ' + tokenForEndpoint);

                if (req.getHeader(HEADER_ACCEPT_LANGUAGE) != null) {
                    headers.put(HEADER_ACCEPT_LANGUAGE, req.getHeader(HEADER_ACCEPT_LANGUAGE));
                }

                ctx = new ConnectorContext(null, headers);
                remoteRes = conn.call("/touch", ctx);

                if (Status.STATUS_OK == remoteRes.getStatus().getCode()
                        || Status.STATUS_TEMPORARY_REDIRECT == remoteRes.getStatus().getCode()) {
                    if (logger.isDebugEnabled())
                        logger.debug("Authentication succeeded on the repo side.");

                    setExternalAuthSession(session);
                    onSuccess(req, res, session, userName);
                } else if (Status.STATUS_UNAUTHORIZED == remoteRes.getStatus().getCode()) {
                    if (logger.isDebugEnabled())
                        logger.debug("Authentication failed on repo side - beging login process again.");
                    res.setHeader(HEADER_WWWAUTHENTICATE, authHdr);
                    res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

                    res.flushBuffer();
                }
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("Unexpected response from repository: WWW-Authenticate:" + authHdr);
                return false;
            }
        } else if (Status.STATUS_OK == remoteRes.getStatus().getCode()
                || Status.STATUS_TEMPORARY_REDIRECT == remoteRes.getStatus().getCode()) {
            if (logger.isDebugEnabled())
                logger.debug("Authentication succeeded on the repo side.");

            setExternalAuthSession(session);
            onSuccess(req, res, session, userName);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Unexpected response from repository: " + remoteRes.getStatus().getMessage());
            return false;
        }
    } catch (ConnectorServiceException cse) {
        throw new AlfrescoRuntimeException("Incorrectly configured endpoint: " + this.endpoint);
    }

    return true;
}