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: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 w  w  w  .  j  av a2  s.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;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.coordinator.ManageFinalDegreeWorkDispatchAction.java

public ActionForward proposalsXLS(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException, FenixServiceException {

    final ExecutionDegree executionDegree = getExecutionDegree(request);
    final ExecutionYear executionYear = executionDegree.getExecutionYear();
    final String yearString = executionYear.getNextYearsYearString().replace('/', '_');

    try {//from w  w  w .  j  a  va2s  .c om
        response.setContentType("text/plain");
        response.setHeader("Content-disposition", "attachment; filename=proposals_" + yearString + ".xls");

        final HSSFWorkbook workbook = new HSSFWorkbook();
        final ExcelStyle excelStyle = new ExcelStyle(workbook);
        final ServletOutputStream writer = response.getOutputStream();

        final Spreadsheet proposalsSpreadsheet = new Spreadsheet("Proposals " + yearString);
        setProposalsHeaders(proposalsSpreadsheet);
        fillProposalsSpreadSheet(executionDegree, proposalsSpreadsheet);
        proposalsSpreadsheet.exportToXLSSheet(workbook, excelStyle.getHeaderStyle(),
                excelStyle.getStringStyle());

        final Spreadsheet groupsSpreadsheet = new Spreadsheet("Groups " + yearString);
        fillGroupsSpreadSheet(executionDegree, groupsSpreadsheet);
        groupsSpreadsheet.exportToXLSSheet(workbook, excelStyle.getHeaderStyle(), excelStyle.getStringStyle());

        final Scheduleing scheduleing = executionDegree.getScheduling();

        final Set<ExecutionDegree> allExecutionDegrees = new HashSet<ExecutionDegree>();
        for (final ExecutionDegree otherExecutionDegree : scheduleing.getExecutionDegreesSet()) {
            for (final FinalDegreeWorkGroup group : otherExecutionDegree
                    .getAssociatedFinalDegreeWorkGroupsSet()) {
                if (!group.getGroupProposalsSet().isEmpty()) {
                    for (final GroupStudent groupStudent : group.getGroupStudentsSet()) {
                        final Registration registration = groupStudent.getRegistration();
                        final StudentCurricularPlan studentCurricularPlan = registration
                                .getLastStudentCurricularPlan();
                        final DegreeCurricularPlan degreeCurricularPlan = studentCurricularPlan
                                .getDegreeCurricularPlan();
                        final ExecutionDegree executionDegreeByYear = degreeCurricularPlan
                                .getExecutionDegreeByYear(otherExecutionDegree.getExecutionYear());
                        if (executionDegreeByYear != null) {
                            allExecutionDegrees.add(executionDegreeByYear);
                        }
                    }
                }
            }
        }

        // for (final ExecutionDegree otherExecutionDegree :
        // scheduleing.getExecutionDegreesSet()) {
        for (final ExecutionDegree otherExecutionDegree : allExecutionDegrees) {
            final DegreeCurricularPlan degreeCurricularPlan = otherExecutionDegree.getDegreeCurricularPlan();
            final Spreadsheet studentsSpreadsheet = new Spreadsheet(
                    "Alunos " + degreeCurricularPlan.getName() + " " + yearString);
            fillStudentsSpreadSheet(otherExecutionDegree, scheduleing, studentsSpreadsheet);
            studentsSpreadsheet.exportToXLSSheet(workbook, excelStyle.getHeaderStyle(),
                    excelStyle.getStringStyle());
        }

        workbook.write(writer);

        writer.flush();
        response.flushBuffer();
    } catch (IOException e) {
        throw new FenixServiceException();
    }
    return null;
}

From source file:org.motechproject.mobile.web.OXDFormUploadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  ww.  jav  a  2 s  . c o  m*/
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@RequestMapping(method = RequestMethod.POST)
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    long startTime = System.currentTimeMillis();

    IMPService impService = (IMPService) appCtx.getBean("impService");
    StudyProcessor studyProcessor = (StudyProcessor) appCtx.getBean("studyProcessor");

    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    ZOutputStream zOutput = null; // Wrap the streams for compression

    // Wrap the streams so for logical types
    DataInputStream dataInput = null;
    DataOutputStream dataOutput = null;

    // Set the MIME type so clients don't misinterpret
    response.setContentType("application/octet-stream");

    try {
        zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);
        dataInput = new DataInputStream(input);
        dataOutput = new DataOutputStream(zOutput);

        if (rawUploadLog.isInfoEnabled()) {
            byte[] rawPayload = IOUtils.toByteArray(dataInput);
            String hexEncodedPayload = Hex.encodeHexString(rawPayload);
            rawUploadLog.info(hexEncodedPayload);
            // Replace the original input stream with one using read payload
            dataInput.close();
            dataInput = new DataInputStream(new ByteArrayInputStream(rawPayload));
        }

        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO Authentication of usename and password. Possible M6
        // enhancement
        log.info("uploading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        serObj.addDeserializationListener(studyProcessor);

        try {
            Map<Integer, String> formVersionMap = formService.getXForms();
            serObj.deserializeStudiesWithEvents(dataInput, formVersionMap);
        } catch (FormNotFoundException fne) {
            String msg = "failed to deserialize forms: ";
            log.error(msg + fne.getMessage());
            dataOutput.writeByte(ResponseHeader.STATUS_FORMS_STALE);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } catch (Exception e) {
            String msg = "failed to deserialize forms";
            log.error(msg, e);
            dataOutput.writeByte(ResponseHeader.STATUS_ERROR);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        String[][] studyForms = studyProcessor.getConvertedStudies();
        int numForms = studyProcessor.getNumForms();

        log.debug("upload contains: studies=" + studyForms.length + ", forms=" + numForms);

        // Starting processing here, only process until we run out of time
        int processedForms = 0;
        int faultyForms = 0;
        if (studyForms != null && numForms > 0) {
            formprocessing: for (int i = 0; i < studyForms.length; i++) {
                for (int j = 0; j < studyForms[i].length; j++, processedForms++) {

                    if (maxProcessingTime > 0 && System.currentTimeMillis() - startTime > maxProcessingTime)
                        break formprocessing;

                    try {
                        studyForms[i][j] = impService.processXForm(studyForms[i][j]);
                    } catch (Exception ex) {
                        log.error("processing form failed", ex);
                        studyForms[i][j] = ex.getMessage();
                    }
                    if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[i][j])) {
                        faultyForms++;
                    }
                }
            }
        }

        // Write out usual upload response
        dataOutput.writeByte(ResponseHeader.STATUS_SUCCESS);

        dataOutput.writeInt(processedForms);
        dataOutput.writeInt(faultyForms);

        for (int s = 0; s < studyForms.length; s++) {
            for (int f = 0; f < studyForms[s].length; f++) {
                if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[s][f])) {
                    dataOutput.writeByte((byte) s);
                    dataOutput.writeShort((short) f);
                    dataOutput.writeUTF(studyForms[s][f]);
                }
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        log.error("failure during upload", e);
    } finally {
        if (dataOutput != null)
            dataOutput.flush();
        if (zOutput != null)
            zOutput.finish();
        response.flushBuffer();
    }
}

From source file:org.apache.ambari.server.security.authorization.AmbariAuthorizationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String requestURI = httpRequest.getRequestURI();

    SecurityContext context = getSecurityContext();

    Authentication authentication = context.getAuthentication();

    //  If no explicit authenticated user is set, set it to the default user (if one is specified)
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        Authentication defaultAuthentication = getDefaultAuthentication();
        if (defaultAuthentication != null) {
            context.setAuthentication(defaultAuthentication);
            authentication = defaultAuthentication;
        }// w w  w .  j a  v  a2 s  . com
    }

    if (authentication == null || !authentication.isAuthenticated()) {
        String token = httpRequest.getHeader(INTERNAL_TOKEN_HEADER);
        if (token != null) {
            context.setAuthentication(new InternalAuthenticationToken(token));
        } else {
            // for view access, we should redirect to the Ambari login
            if (requestURI.matches(VIEWS_CONTEXT_ALL_PATTERN)) {
                String queryString = httpRequest.getQueryString();
                String requestedURL = queryString == null ? requestURI : (requestURI + '?' + queryString);
                String redirectURL = httpResponse.encodeRedirectURL(LOGIN_REDIRECT_BASE + requestedURL);

                httpResponse.sendRedirect(redirectURL);
                return;
            } else {
                httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Authentication required");
            }
        }
    } else if (!authorizationPerformedInternally(requestURI)) {
        boolean authorized = false;

        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (grantedAuthority instanceof AmbariGrantedAuthority) {

                AmbariGrantedAuthority ambariGrantedAuthority = (AmbariGrantedAuthority) grantedAuthority;

                PrivilegeEntity privilegeEntity = ambariGrantedAuthority.getPrivilegeEntity();
                Integer permissionId = privilegeEntity.getPermission().getId();

                // admin has full access
                if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
                    authorized = true;
                    break;
                }

                // clusters require permission
                if (!"GET".equalsIgnoreCase(httpRequest.getMethod())
                        && requestURI.matches(API_CREDENTIALS_AMBARI_PATTERN)) {
                    // Only the administrator can operate on credentials where the alias starts with "ambari."
                    if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_CLUSTERS_ALL_PATTERN)) {
                    if (permissionId.equals(PermissionEntity.CLUSTER_USER_PERMISSION)
                            || permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (STACK_ADVISOR_REGEX.matcher(requestURI).matches()) {
                    //TODO permissions model doesn't manage stacks api, but we need access to stack advisor to save configs
                    if (permissionId.equals(PermissionEntity.CLUSTER_USER_PERMISSION)
                            || permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_VIEWS_ALL_PATTERN)) {
                    // views require permission
                    if (permissionId.equals(PermissionEntity.VIEW_USER_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_PERSIST_ALL_PATTERN)) {
                    if (permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                }
            }
        }

        // allow GET for everything except /views, /api/v1/users, /api/v1/groups, /api/v1/ldap_sync_events
        if (!authorized && (!httpRequest.getMethod().equals("GET")
                || requestURI.matches(API_LDAP_SYNC_EVENTS_ALL_PATTERN))) {

            httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "You do not have permissions to access this resource.");
            httpResponse.flushBuffer();
            return;
        }
    }

    if (AuthorizationHelper.getAuthenticatedName() != null) {
        httpResponse.setHeader("User", AuthorizationHelper.getAuthenticatedName());
    }
    chain.doFilter(request, response);
}

From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Get request/*from   w  ww . j  a v  a  2s .  c  o  m*/
 ***************************************************************************/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String serverUrl = request.getParameter("url");
    // manages a get request if it's the geoprint or getcapabilities operation
    boolean isGeoprint = serverUrl.toLowerCase().contains("mapeaop=geoprint");
    boolean isGetCapabilities = serverUrl.toLowerCase().contains("getcapabilities");
    boolean isGetFeatureInfo = serverUrl.toLowerCase().contains("wmsinfo");
    if (isGeoprint || isGetCapabilities || isGetFeatureInfo) {
        String strErrorMessage = "";
        serverUrl = checkTypeRequest(serverUrl);
        if (!serverUrl.equals("ERROR")) {
            // removes mapeaop parameter
            String url = serverUrl.replaceAll("\\&?\\??mapeaop=geoprint", "");
            url = serverUrl.replaceAll("\\&?\\??mapeaop=getcapabilities", "");
            url = serverUrl.replaceAll("\\&?\\??mapeaop=wmsinfo", "");
            HttpClient client = new HttpClient();
            GetMethod httpget = null;
            try {
                httpget = new GetMethod(url);
                HttpClientParams params = client.getParams();
                params.setIntParameter(HttpClientParams.MAX_REDIRECTS, numMaxRedirects);
                client.executeMethod(httpget);
                // REDIRECTS MANAGEMENT
                if (httpget.getStatusCode() == HttpStatus.SC_OK) {
                    // PATH_SECURITY_PROXY - AG
                    Header[] respHeaders = httpget.getResponseHeaders();
                    int compSize = httpget.getResponseBody().length;
                    ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders));
                    String headersString = headerList.toString();
                    boolean checkedContent = checkContent(headersString, compSize, serverUrl);
                    // FIN_PATH_SECURITY_PROXY
                    if (checkedContent) {
                        if (request.getProtocol().compareTo("HTTP/1.0") == 0) {
                            response.setHeader("Pragma", "no-cache");
                        } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) {
                            response.setHeader("Cache-Control", "no-cache");
                        }
                        response.setDateHeader("Expires", -1);
                        // set content-type headers
                        if (isGeoprint) {
                            response.setContentType("application/json");
                        } else if (isGetCapabilities) {
                            response.setContentType("text/xml");
                        }
                        /*
                         * checks if it has requested an getfeatureinfo to modify the response content
                         * type.
                         */
                        String requesteredUrl = request.getParameter("url");
                        if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/plain");
                        } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("application/gml+xml");
                        } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/html");
                        }
                        InputStream st = httpget.getResponseBodyAsStream();
                        ServletOutputStream sos = response.getOutputStream();
                        IOUtils.copy(st, sos);
                    } else {
                        strErrorMessage += errorType;
                        log.error(strErrorMessage);
                    }
                } else {
                    strErrorMessage = "Unexpected failure: " + httpget.getStatusLine().toString();
                    log.error(strErrorMessage);
                }
                httpget.releaseConnection();
            } catch (Exception e) {
                log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e);
            } finally {
                if (httpget != null) {
                    httpget.releaseConnection();
                }
            }
        } else {
            // String errorXML = strErrorMessage;
            String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>Error en el parametro url de entrada</descripcion></error>";
            response.setContentType("text/xml");
            try {
                PrintWriter out = response.getWriter();
                out.print(errorXML);
                response.flushBuffer();
            } catch (Exception e) {
                log.error(e);
            }
        }
    } else {
        doPost(request, response);
    }
}

From source file:org.apache.nutch.searcher.response.xml.XMLResponseWriter.java

public void writeResponse(SearchResults results, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    try {/*from  w ww. ja v a  2s.  c om*/

        // create the xml document and add the results and search nodes
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document xmldoc = factory.newDocumentBuilder().newDocument();
        Element resEl = addNode(xmldoc, xmldoc, "results");
        Element searchEl = addNode(xmldoc, resEl, "search");

        // add common nodes
        String query = results.getQuery();
        addNode(xmldoc, searchEl, "query", query);
        addNode(xmldoc, searchEl, "totalhits", String.valueOf(results.getTotalHits()));
        String lang = results.getLang();
        if (lang != null) {
            addNode(xmldoc, searchEl, "lang", lang);
        }
        String sort = results.getSort();
        if (sort != null) {
            addNode(xmldoc, searchEl, "sort", sort);
        }
        addNode(xmldoc, searchEl, "reverse", results.isReverse() ? "true" : "false");
        addNode(xmldoc, searchEl, "start", String.valueOf(results.getStart()));
        addNode(xmldoc, searchEl, "end", String.valueOf(results.getEnd()));
        addNode(xmldoc, searchEl, "rows", String.valueOf(results.getRows()));
        addNode(xmldoc, searchEl, "totalhits", String.valueOf(results.getTotalHits()));
        addNode(xmldoc, searchEl, "withSummary", String.valueOf(results.isWithSummary()));

        String[] searchFields = results.getFields();
        Set<String> fieldSet = new HashSet<String>();
        if (searchFields != null && searchFields.length > 0) {
            addNode(xmldoc, searchEl, "fields", StringUtils.join(searchFields, ","));
            for (int i = 0; i < searchFields.length; i++) {
                fieldSet.add(searchFields[i]);
            }
        }

        // add documents
        Element documents = addNode(xmldoc, resEl, "documents");
        HitDetails[] details = results.getDetails();
        Hit[] hits = results.getHits();
        Summary[] summaries = results.getSummaries();
        for (int i = 0; i < details.length; i++) {

            // every document has an indexno and an indexdocno
            Element document = addNode(xmldoc, documents, "document");
            addAttribute(xmldoc, document, "indexno", String.valueOf(hits[i].getIndexNo()));
            addAttribute(xmldoc, document, "indexkey", String.valueOf(hits[i].getUniqueKey()));

            // don't add summaries not including summaries
            if (summaries != null && results.isWithSummary()) {
                String encSumm = Entities.encode(summaries[i].toString());
                addNode(xmldoc, document, "summary", encSumm);
            }

            // add the fields from hit details
            Element fields = addNode(xmldoc, document, "fields");
            HitDetails detail = details[i];
            for (int j = 0; j < detail.getLength(); j++) {
                String fieldName = detail.getField(j);
                String[] fieldValues = detail.getValues(fieldName);

                // if we specified fields to return, only return those fields
                if (fieldSet.size() == 0 || fieldSet.contains(fieldName)) {
                    Element field = addNode(xmldoc, fields, "field");
                    addAttribute(xmldoc, field, "name", fieldName);
                    for (int k = 0; k < fieldValues.length; k++) {
                        String encFieldVal = Entities.encode(fieldValues[k]);
                        addNode(xmldoc, field, "value", encFieldVal);
                    }
                }
            }
        }

        // get the xml source and a transformer to print it out
        DOMSource source = new DOMSource(xmldoc);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();

        // pretty printing can be set through configuration
        if (prettyPrint) {
            transformer.setOutputProperty("indent", "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }

        // write out the content to a byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(baos);
        transformer.transform(source, result);
        baos.flush();
        baos.close();

        // cache control headers
        SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'");
        long relExpiresInMillis = System.currentTimeMillis() + (1000 * maxAgeInSeconds);
        response.setContentType(contentType);
        response.setHeader("Cache-Control", "max-age=" + maxAgeInSeconds);
        response.setHeader("Expires", sdf.format(relExpiresInMillis));

        // write out the content to the response
        response.getOutputStream().write(baos.toByteArray());
        response.flushBuffer();
    } catch (Exception e) {
        throw new IOException(e);
    }

}

From source file:org.alfresco.repo.webdav.auth.AuthenticationFilter.java

/**
 * Run the authentication filter//from  w w w . j  a v a2 s .co m
 * 
 * @param context ServletContext
 * @param req ServletRequest
 * @param resp ServletResponse
 * @param chain FilterChain
 * @exception ServletException
 * @exception IOException
 */
public void doFilter(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (logger.isDebugEnabled())
        logger.debug("Entering AuthenticationFilter.");

    // Assume it's an HTTP request

    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;

    // Get the user details object from the session
    SessionUser user = getSessionUser(context, httpReq, httpResp, false);

    if (user == null) {
        if (logger.isDebugEnabled())
            logger.debug("There is no user in the session.");
        // Get the authorization header

        String authHdr = httpReq.getHeader("Authorization");

        if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) {
            if (logger.isDebugEnabled())
                logger.debug("Basic authentication details present in the header.");
            byte[] encodedString = Base64.decodeBase64(authHdr.substring(5).getBytes());

            // ALF-13621: Due to browser inconsistencies we have to try a fallback path of encodings
            Set<String> attemptedAuths = new HashSet<String>(ENCODINGS.length * 2);
            for (String encoding : ENCODINGS) {
                CharsetDecoder decoder = Charset.forName(encoding).newDecoder()
                        .onMalformedInput(CodingErrorAction.REPORT);
                try {
                    // Attempt to decode using this charset 
                    String basicAuth = decoder.decode(ByteBuffer.wrap(encodedString)).toString();

                    // It decoded OK but we may already have tried this string.
                    if (!attemptedAuths.add(basicAuth)) {
                        // Already tried - no need to try again
                        continue;
                    }

                    String username = null;
                    String password = null;

                    // Split the username and password
                    int pos = basicAuth.indexOf(":");
                    if (pos != -1) {
                        username = basicAuth.substring(0, pos);
                        password = basicAuth.substring(pos + 1);
                    } else {
                        username = basicAuth;
                        password = "";
                    }

                    // Go to the repo and authenticate
                    Authorization auth = new Authorization(username, password);
                    if (auth.isTicket()) {
                        authenticationService.validate(auth.getTicket());
                    } else {
                        authenticationService.authenticate(username, password.toCharArray());
                        authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password));
                    }

                    user = createUserEnvironment(httpReq.getSession(),
                            authenticationService.getCurrentUserName(),
                            authenticationService.getCurrentTicket(), false);

                    // Success so break out
                    break;
                } catch (CharacterCodingException e) {
                    if (logger.isDebugEnabled())
                        logger.debug("Didn't decode using " + decoder.getClass().getName(), e);
                } catch (AuthenticationException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Authentication error ", ex);
                } catch (NoSuchPersonException e) {
                    if (logger.isDebugEnabled())
                        logger.debug("There is no such person error ", e);
                }
            }
        } else {
            // Check if the request includes an authentication ticket

            String ticket = req.getParameter(ARG_TICKET);

            if (ticket != null && ticket.length() > 0) {
                // PowerPoint bug fix
                if (ticket.endsWith(PPT_EXTN)) {
                    ticket = ticket.substring(0, ticket.length() - PPT_EXTN.length());
                }

                // Debug

                if (logger.isDebugEnabled())
                    logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr()
                            + ":" + req.getRemotePort() + ")" + " ticket=" + ticket);

                // Validate the ticket

                authenticationService.validate(ticket);
                authenticationListener.userAuthenticated(new TicketCredentials(ticket));

                // Need to create the User instance if not already available

                String currentUsername = authenticationService.getCurrentUserName();

                user = createUserEnvironment(httpReq.getSession(), currentUsername, ticket, false);
            }
        }

        // Check if the user is authenticated, if not then prompt again

        if (user == null) {
            if (logger.isDebugEnabled())
                logger.debug("No user/ticket, force the client to prompt for logon details.");

            httpResp.setHeader("WWW-Authenticate", "BASIC realm=\"Alfresco DAV Server\"");
            httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            httpResp.flushBuffer();
            return;
        }
    } else {
        authenticationListener.userAuthenticated(new TicketCredentials(user.getTicket()));
    }

    // Chain other filters

    chain.doFilter(req, resp);
}

From source file:org.ejbca.ui.web.admin.certprof.ProfilesExportServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {
    log.trace(">doGet()");
    final String type = request.getParameter("profileType");

    String zipfilename = null;/*w ww.  ja va  2 s  . c  om*/
    int exportedprofiles = 0;
    int totalprofiles = 0;
    int missingprofiles = 0;
    ByteArrayOutputStream zbaos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(zbaos);

    if (StringUtils.equalsIgnoreCase(type, "cp")) {
        zipfilename = "certprofiles.zip";

        Collection<Integer> certprofids = certificateProfileSession
                .getAuthorizedCertificateProfileIds(alwaysAllowAuthenticationToken, 0);
        totalprofiles = certprofids.size();
        log.info("Exporting non-fixed certificate profiles");
        for (int profileid : certprofids) {
            if (profileid == CertificateProfileConstants.CERTPROFILE_NO_PROFILE) { // Certificate profile not found i database.
                log.error("Couldn't find certificate profile '" + profileid + "' in database.");
            } else if (CertificateProfileConstants.isFixedCertificateProfile(profileid)) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping export fixed certificate profile with id '" + profileid + "'.");
                }
            } else {
                String profilename = certificateProfileSession.getCertificateProfileName(profileid);
                CertificateProfile profile = certificateProfileSession.getCertificateProfile(profileid);
                if (profile == null) {
                    missingprofiles++;
                    log.error("Couldn't find certificate profile '" + profilename + "'-" + profileid
                            + " in database.");
                } else {
                    String profilenameEncoded;
                    try {
                        profilenameEncoded = URLEncoder.encode(profilename, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        throw new IllegalStateException("UTF-8 was not a known encoding", e);
                    }

                    byte[] ba = getProfileBytes(profile);
                    String filename = "certprofile_" + profilenameEncoded + "-" + profileid + ".xml";
                    ZipEntry ze = new ZipEntry(filename);
                    zos.putNextEntry(ze);
                    zos.write(ba);
                    zos.closeEntry();
                    exportedprofiles++;
                }
            }
        }

    } else if (StringUtils.equalsIgnoreCase(type, "eep")) {

        zipfilename = "entityprofiles.zip";

        Collection<Integer> endentityprofids = endEntityProfileSession
                .getAuthorizedEndEntityProfileIds(alwaysAllowAuthenticationToken);
        totalprofiles = endentityprofids.size();
        log.info("Exporting non-fixed end entity profiles");
        for (int profileid : endentityprofids) {
            if (profileid == SecConst.PROFILE_NO_PROFILE) { // Entity profile not found i database.
                missingprofiles++;
                log.error("Error : Couldn't find entity profile '" + profileid + "' in database.");
            } else if (profileid == SecConst.EMPTY_ENDENTITYPROFILE) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping export fixed end entity profile with id '" + profileid + "'.");
                }
            } else {
                String profilename = endEntityProfileSession.getEndEntityProfileName(profileid);
                EndEntityProfile profile = endEntityProfileSession.getEndEntityProfile(profileid);
                if (profile == null) {
                    log.error("Error : Couldn't find entity profile '" + profilename + "'-" + profileid
                            + " in database.");
                } else {
                    String profilenameEncoded;
                    try {
                        profilenameEncoded = URLEncoder.encode(profilename, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        throw new IllegalStateException("UTF-8 was not a known encoding", e);
                    }

                    byte[] ba = getProfileBytes(profile);
                    String filename = "entityprofile_" + profilenameEncoded + "-" + profileid + ".xml";
                    ZipEntry ze = new ZipEntry(filename);
                    zos.putNextEntry(ze);
                    zos.write(ba);
                    zos.closeEntry();

                    exportedprofiles++;
                }
            }
        }
    }
    zos.close();

    byte[] zipfile = zbaos.toByteArray();
    zbaos.close();

    log.info("Found " + totalprofiles + " profiles. " + exportedprofiles + " profiles were exported to "
            + zipfilename + " and " + missingprofiles + " were not found in the database.");

    response.setContentType("application/octet-stream");
    response.setHeader("Content-disposition",
            " attachment; filename=\"" + StringTools.stripFilename(zipfilename) + "\"");
    response.getOutputStream().write(zipfile);
    response.flushBuffer();

    log.trace("<doGet()");
}

From source file:com.rr.familyPlanning.ui.aggregate.aggregateController.java

@RequestMapping(value = "/DLReport", method = { RequestMethod.GET })
public void DLReport(@RequestParam String i, @RequestParam String v, HttpSession session,
        HttpServletResponse response) throws Exception {

    Integer reportRequestId = 0;/*from  ww w. java  2  s . c om*/
    aggregateView view = new aggregateView();
    boolean canViewReport = false;

    userActivityLog ual = new userActivityLog();
    ual.setMapping("/DLReport");
    ual.setRequestMethod("GET");
    ual.setMethodAccessed("/DLReport");
    ual.setModuleId(moduleId);
    ual.setProgramId(programId);

    if (session.getAttribute("userDetails") != null) {

        User userDetails = (User) session.getAttribute("userDetails");
        //1 decrpt and get the reportId
        decryptObject decrypt = new decryptObject();
        Object obj = decrypt.decryptObject(i, v);
        String[] result = obj.toString().split((","));
        reportRequestId = Integer.parseInt(result[0].substring(4));
        view.setAggregateRequestId(reportRequestId);
        view.setAggregateAction("/DLReport| Accessed Aggregate Report DL link");
        view.setSystemUserId(userDetails.getId());
        aggregatemanager.saveAggregateView(view);
        //now we get the report details
        aggregateRequests request = aggregatemanager.getAggregateRequestById(reportRequestId);

        if (request != null) {
            if (userDetails.getRoleId() == 2) {
                canViewReport = true;
            } else {
                //check permission
                List<programOrgHierarchy> orgHierarchyList = hierarchymanager.getProgramOrgHierarchy(programId);
                List<aggregateRequests> requests = aggregatemanager.getAggregateRequests(programId,
                        userDetails.getId(), 2, orgHierarchyList.get(1).getId(), request.getId());
                if (requests.size() > 0) {
                    canViewReport = true;
                }
            }
            //we log them, grab report for them to download
            //if report doesn't exist we send them back to list with a message
            if (!canViewReport) {
                view = new aggregateView();
                view.setAggregateRequestId(reportRequestId);
                view.setSystemUserId(userDetails.getId());
                view.setAggregateAction("/DLReport| User does not have permission to view aggregate report");
                aggregatemanager.saveAggregateView(view);

                ual.setRelatedId(reportRequestId);
                ual.setRelatedIdCol("reportRequestId");
                ual.setSystemUserId(userDetails.getId());
                ual.setMiscNotes("User does not have permission to view aggregate report");
                usermanager.saveUserActivityLog(ual);

            } else {
                //generate the report for user to download
                //need to get report path
                String filePath = aggregatemanager.getReportPath(programId);
                String fileName = request.getReportFileName();
                try {
                    File f = new File(filePath + fileName);
                    if (!f.exists()) {
                        ual.setRelatedId(reportRequestId);
                        ual.setRelatedIdCol("reportRequestId");
                        ual.setSystemUserId(userDetails.getId());
                        ual.setMiscNotes("Error with File " + filePath + fileName);
                        usermanager.saveUserActivityLog(ual);
                        throw new Exception("Error with File " + filePath + fileName);
                    }
                } catch (Exception e) {
                    ual.setRelatedId(reportRequestId);
                    ual.setRelatedIdCol("reportRequestId");
                    ual.setSystemUserId(userDetails.getId());
                    ual.setMiscNotes("File does not exists " + filePath + fileName);
                    usermanager.saveUserActivityLog(ual);
                    throw new Exception("File does not exists " + filePath + fileName);
                }

                try {
                    // get your file as InputStream
                    InputStream is = new FileInputStream(filePath + fileName);
                    // copy it to response's OutputStream

                    String mimeType = "application/octet-stream";
                    response.setContentType(mimeType);
                    response.setHeader("Content-Transfer-Encoding", "binary");
                    response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                    org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
                    response.flushBuffer();
                    is.close();

                    view = new aggregateView();
                    view.setSystemUserId(userDetails.getId());
                    view.setAggregateRequestId(reportRequestId);
                    view.setAggregateAction("/DLReport| Download Report Set");
                    aggregatemanager.saveAggregateView(view);
                    //update status
                    request.setStatusId(4);
                    aggregatemanager.updateAggregateRequest(request);

                    ual.setRelatedId(reportRequestId);
                    ual.setRelatedIdCol("reportRequestId");
                    ual.setSystemUserId(userDetails.getId());
                    ual.setMiscNotes("Downloaded Report Set");
                    usermanager.saveUserActivityLog(ual);

                } catch (IOException ex) {
                    ual.setRelatedId(reportRequestId);
                    ual.setRelatedIdCol("reportRequestId");
                    ual.setSystemUserId(userDetails.getId());
                    ual.setMiscNotes("Error with File " + filePath + fileName);
                    usermanager.saveUserActivityLog(ual);
                    ex.printStackTrace();
                    throw new Exception("Error with File " + filePath + fileName + ex);
                }
            }

        } else {
            //someone somehow got to this link, we just log
            //we log who is accessing 
            //now we have report id, we check to see which program it belongs to and if the user has permission
            view.setAggregateRequestId(reportRequestId);
            view.setAggregateAction("/DLReport| Accessed aggregate report link - no user session found");
            aggregatemanager.saveAggregateView(view);

            ual.setRelatedId(reportRequestId);
            ual.setRelatedIdCol("reportRequestId");
            ual.setMiscNotes("Accessed aggregate report link - no user session found");
            usermanager.saveUserActivityLog(ual);

            throw new Exception("invalid aggregate report download - " + reportRequestId);

        }

    }

}

From source file:org.codice.ddf.security.filter.websso.WebSSOFilter.java

private void handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        FilterChain filterChain, List<AuthenticationHandler> handlers) throws IOException, ServletException {

    if (handlers.size() == 0) {
        LOGGER.warn("Handlers not ready. Returning status code 503, Service Unavailable.");
        returnSimpleResponse(HttpServletResponse.SC_SERVICE_UNAVAILABLE, httpResponse);
        return;//from  w  w  w.j  a  v a 2  s.co m
    }

    // First pass, see if anyone can come up with proper security token from the get-go
    HandlerResult result = null;
    LOGGER.debug("Checking for existing tokens in request.");

    for (AuthenticationHandler auth : handlers) {
        result = auth.getNormalizedToken(httpRequest, httpResponse, filterChain, false);
        if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
            LOGGER.debug("Handler {} set the result status to {}", auth.getAuthenticationType(),
                    result.getStatus());
            break;
        }
    }

    // If we haven't received usable credentials yet, go get some
    if (result == null || result.getStatus() == HandlerResult.Status.NO_ACTION) {
        LOGGER.debug("First pass with no tokens found - requesting tokens");
        // This pass, tell each handler to do whatever it takes to get a SecurityToken
        for (AuthenticationHandler auth : handlers) {
            result = auth.getNormalizedToken(httpRequest, httpResponse, filterChain, true);
            if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
                LOGGER.debug("Handler {} set the result status to {}", auth.getAuthenticationType(),
                        result.getStatus());
                break;
            }
        }
    }

    String path = StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
            : httpRequest.getServletPath() + StringUtils.defaultString(httpRequest.getPathInfo());
    String ipAddress = httpRequest.getHeader("X-FORWARDED-FOR");

    if (ipAddress == null) {
        ipAddress = httpRequest.getRemoteAddr();
    }

    if (result != null) {
        switch (result.getStatus()) {
        case REDIRECTED:
            // handler handled the response - it is redirecting or whatever
            // necessary to get their tokens
            LOGGER.debug("Stopping filter chain - handled by plugins");
            return;
        case NO_ACTION:
            // should never occur - one of the handlers should have returned a token
            LOGGER.warn(
                    "No handlers were able to determine required credentials, returning bad request to {}. Check policy configuration for path: {}",
                    ipAddress, path);
            returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
            return;
        case COMPLETED:
            if (result.getToken() == null) {
                LOGGER.warn(
                        "Completed without credentials for {} - check context policy configuration for path: {}",
                        ipAddress, path);
                returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
                return;
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "Attaching result handler to the http request - token is instance of {} from classloader {}",
                        result.getToken().getClass().getName(), result.getToken().getClass().getClassLoader());
            }
            httpRequest.setAttribute(DDF_AUTHENTICATION_TOKEN, result);
            break;
        default:
            LOGGER.warn("Unexpected response from handler - ignoring. Remote IP: {}, Path: {}", ipAddress,
                    path);
            return;
        }
    } else {
        LOGGER.warn(
                "Expected login credentials from {} - didn't find any. Returning a bad request for path: {}",
                ipAddress, path);
        returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
        return;
    }

    // If we got here, we've received our tokens to continue
    LOGGER.debug("Invoking the rest of the filter chain");
    try {
        filterChain.doFilter(httpRequest, httpResponse);
    } catch (InvalidSAMLReceivedException e) {
        // we tried to process an invalid or missing SAML assertion
        returnSimpleResponse(HttpServletResponse.SC_UNAUTHORIZED, httpResponse);
    } catch (Exception e) {
        LOGGER.debug("Exception in filter chain - passing off to handlers. Msg: {}", e.getMessage(), e);

        // First pass, see if anyone can come up with proper security token
        // from the git-go
        result = null;
        for (AuthenticationHandler auth : handlers) {
            result = auth.handleError(httpRequest, httpResponse, filterChain);
            if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
                LOGGER.debug("Handler {} set the status to {}", auth.getAuthenticationType(),
                        result.getStatus());
                break;
            }
        }
        if (result == null || result.getStatus() == HandlerResult.Status.NO_ACTION) {
            LOGGER.debug("Error during authentication - no error recovery attempted - returning bad request.");
            httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.flushBuffer();
        }
    }
}