Example usage for javax.servlet.http HttpServletResponse resetBuffer

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

Introduction

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

Prototype


public void resetBuffer();

Source Link

Document

Clears the content of the underlying buffer in the response without clearing headers or status code.

Usage

From source file:org.openmeetings.servlet.outputhandler.LangExport.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {//  w ww  .  j  av  a  2s .c o  m

        if (getUserManagement() == null || getFieldLanguageDaoImpl() == null || getFieldmanagment() == null
                || getSessionManagement() == null) {
            return;
        }

        String sid = httpServletRequest.getParameter("sid");
        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        String language = httpServletRequest.getParameter("language");
        if (language == null) {
            language = "0";
        }
        Long language_id = Long.valueOf(language).longValue();
        log.debug("language_id: " + language_id);

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        log.debug("users_id: " + users_id);
        log.debug("user_level: " + user_level);

        if (user_level != null && user_level > 0) {
            FieldLanguage fl = getFieldLanguageDaoImpl().getFieldLanguageById(language_id);

            List<Fieldlanguagesvalues> flvList = getFieldmanagment().getMixedFieldValuesList(language_id);

            if (fl != null && flvList != null) {
                Document doc = createDocument(flvList,
                        getFieldmanagment().getUntranslatedFieldValuesList(language_id));

                String requestedFile = fl.getName() + ".xml";

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                OutputStream out = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                httpServletResponse.setHeader("Content-Disposition",
                        "attachment; filename=\"" + requestedFile + "\"");
                // httpServletResponse.setHeader("Content-Length", ""+
                // rf.length());

                this.serializetoXML(out, "UTF-8", doc);

                out.flush();
                out.close();
            }
        } else {
            log.debug("ERROR LangExport: not authorized FileDownload " + (new Date()));
        }

    } catch (Exception er) {
        log.error("ERROR ", er);
        System.out.println("Error exporting: " + er);
        er.printStackTrace();
    }
}

From source file:org.openmeetings.servlet.outputhandler.Export.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {// ww  w.  jav  a 2  s . com

        if (getUserManagement() == null || getSessionManagement() == null || getUsersDao() == null) {
            return;
        }

        String sid = httpServletRequest.getParameter("sid");
        if (sid == null) {
            sid = "default";
        }
        System.out.println("sid: " + sid);

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        System.out.println("users_id: " + users_id);
        System.out.println("user_level: " + user_level);

        // if (user_level!=null && user_level > 0) {
        if (getAuthLevelManagement().checkUserLevel(user_level)) {

            String moduleName = httpServletRequest.getParameter("moduleName");
            if (moduleName == null) {
                moduleName = "moduleName";
            }
            System.out.println("moduleName: " + moduleName);

            if (moduleName.equals("users") || moduleName.equals("userorganisations")) {
                String organisation = httpServletRequest.getParameter("organisation");
                if (organisation == null) {
                    organisation = "0";
                }
                Long organisation_id = Long.valueOf(organisation).longValue();
                System.out.println("organisation_id: " + organisation_id);

                List<Users> uList = null;
                String downloadName = "users";
                if (moduleName.equals("userorganisations")) {
                    Organisation orga = getOrganisationmanagement().getOrganisationById(organisation_id);
                    downloadName += "_" + orga.getName();
                    uList = getOrganisationmanagement().getUsersByOrganisationId(organisation_id);
                } else {
                    uList = getUsersDao().getAllUsers();
                }

                if (uList != null) {
                    Document doc = this.createDocument(uList);

                    httpServletResponse.reset();
                    httpServletResponse.resetBuffer();
                    OutputStream out = httpServletResponse.getOutputStream();
                    httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                    httpServletResponse.setHeader("Content-Disposition",
                            "attachment; filename=\"" + downloadName + ".xml\"");
                    // httpServletResponse.setHeader("Content-Length", ""+
                    // rf.length());

                    this.serializetoXML(out, "UTF-8", doc);

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

            }
        } else {
            System.out.println("ERROR LangExport: not authorized FileDownload " + (new Date()));
        }
    } catch (Exception er) {
        log.error("ERROR ", er);
        System.out.println("Error exporting: " + er);
        er.printStackTrace();
    }
}

From source file:org.openmeetings.servlet.outputhandler.BackupExport.java

public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        ServletContext servletCtx) throws ServletException, IOException {

    String sid = httpServletRequest.getParameter("sid");
    if (sid == null) {
        sid = "default";
    }//from  w ww.ja va2s . co m
    log.debug("sid: " + sid);

    Long users_id = sessionManagement.checkSession(sid);
    Long user_level = userManagement.getUserLevelByID(users_id);

    log.debug("users_id: " + users_id);
    log.debug("user_level: " + user_level);

    if (authLevelManagement.checkAdminLevel(user_level)) {
        // if (true) {

        String includeFileOption = httpServletRequest.getParameter("includeFileOption");
        boolean includeFiles = includeFileOption == null || "yes".equals(includeFileOption);

        String moduleName = httpServletRequest.getParameter("moduleName");
        if (moduleName == null) {
            moduleName = "moduleName";
        }
        log.debug("moduleName: " + moduleName);

        if (moduleName.equals("backup")) {

            /*
             * ##################### Create Base Folder structure
             */

            String current_dir = servletCtx.getRealPath("/");
            File working_dir = new File(new File(current_dir, OpenmeetingsVariables.UPLOAD_DIR), "backup");

            if (!working_dir.exists()) {
                working_dir.mkdir();
            }

            String dateString = "backup_" + CalendarPatterns.getTimeForStreamId(new Date());

            File backup_dir = new File(working_dir, dateString);
            String requestedFile = dateString + ".zip";
            File backupFile = new File(backup_dir, requestedFile);

            String full_path = backupFile.getAbsolutePath();
            try {
                performExport(full_path, backup_dir, includeFiles, current_dir);

                RandomAccessFile rf = new RandomAccessFile(full_path, "r");

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                httpServletResponse.setHeader("Content-Disposition",
                        "attachment; filename=\"" + requestedFile + "\"");
                httpServletResponse.setHeader("Content-Length", "" + rf.length());

                OutputStream out = httpServletResponse.getOutputStream();

                byte[] buffer = new byte[1024];
                int readed = -1;

                while ((readed = rf.read(buffer, 0, buffer.length)) > -1) {
                    out.write(buffer, 0, readed);
                }

                rf.close();

                out.flush();
                out.close();
            } catch (Exception er) {
                log.error("Error exporting: ", er);
            }

            if (backupFile.exists()) {
                // log.debug("DELETE :1: "+backupFile.getAbsolutePath());
                backupFile.delete();
            }

            deleteDirectory(backup_dir);

        }
    } else {
        log.debug("ERROR LangExport: not authorized FileDownload " + (new Date()));
    }
}

From source file:org.openmeetings.servlet.outputhandler.ExportToImage.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {/*ww  w  . jav a 2 s .  c  o m*/
        if (getUserManagement() == null || getSessionManagement() == null || getGenerateImage() == null) {
            return;
        }

        String sid = httpServletRequest.getParameter("sid");
        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        String hash = httpServletRequest.getParameter("hash");
        if (hash == null) {
            hash = "";
        }
        log.debug("hash: " + hash);

        String fileName = httpServletRequest.getParameter("fileName");
        if (fileName == null) {
            fileName = "file_xyz";
        }

        String exportType = httpServletRequest.getParameter("exportType");
        if (exportType == null) {
            exportType = "svg";
        }

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        log.debug("users_id: " + users_id);
        log.debug("user_level: " + user_level);

        if (user_level != null && user_level > 0 && hash != "") {

            PrintBean pBean = PrintService.getPrintItemByHash(hash);

            // Whiteboard Objects
            @SuppressWarnings("rawtypes")
            List whiteBoardMap = pBean.getMap();

            // Get a DOMImplementation.
            DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

            // Create an instance of org.w3c.dom.Document.
            // String svgNS = "http://www.w3.org/2000/svg";
            String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;

            Document document = domImpl.createDocument(svgNS, "svg", null);

            // Get the root element (the 'svg' element).
            Element svgRoot = document.getDocumentElement();

            // Set the width and height attributes on the root 'svg'
            // element.
            svgRoot.setAttributeNS(null, "width", "" + pBean.getWidth());
            svgRoot.setAttributeNS(null, "height", "" + pBean.getHeight());

            log.debug("pBean.getWidth(),pBean.getHeight()" + pBean.getWidth() + "," + pBean.getHeight());

            // Create an instance of the SVG Generator.
            SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

            svgGenerator = WhiteboardMapToSVG.getInstance().convertMapToSVG(svgGenerator, whiteBoardMap);

            // Finally, stream out SVG to the standard output using
            // UTF-8 encoding.
            boolean useCSS = true; // we want to use CSS style attributes
            // Writer out = new OutputStreamWriter(System.out, "UTF-8");

            if (exportType.equals("svg")) {
                // OutputStream out = httpServletResponse.getOutputStream();
                // httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                // httpServletResponse.setHeader("Content-Disposition","attachment; filename=\""
                // + requestedFile + "\"");
                Writer out = httpServletResponse.getWriter();

                svgGenerator.stream(out, useCSS);

            } else if (exportType.equals("png") || exportType.equals("jpg") || exportType.equals("gif")
                    || exportType.equals("tif") || exportType.equals("pdf")) {

                String current_dir = getServletContext().getRealPath("/");
                String working_dir = current_dir + OpenmeetingsVariables.UPLOAD_TEMP_DIR + File.separatorChar;

                String requestedFileSVG = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date())
                        + ".svg";
                String resultFileName = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + "."
                        + exportType;

                log.debug("current_dir: " + current_dir);
                log.debug("working_dir: " + working_dir);
                log.debug("requestedFileSVG: " + requestedFileSVG);
                log.debug("resultFileName: " + resultFileName);

                File svgFile = new File(working_dir + requestedFileSVG);
                File resultFile = new File(working_dir + resultFileName);

                log.debug("svgFile: " + svgFile.getAbsolutePath());
                log.debug("resultFile: " + resultFile.getAbsolutePath());
                log.debug("svgFile P: " + svgFile.getPath());
                log.debug("resultFile P: " + resultFile.getPath());

                FileWriter out = new FileWriter(svgFile);
                svgGenerator.stream(out, useCSS);

                // Get file and handle download
                RandomAccessFile rf = new RandomAccessFile(resultFile.getAbsoluteFile(), "r");

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                OutputStream outStream = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                httpServletResponse.setHeader("Content-Disposition",
                        "attachment; filename=\"" + resultFileName + "\"");
                httpServletResponse.setHeader("Content-Length", "" + rf.length());

                byte[] buffer = new byte[1024];
                int readed = -1;

                while ((readed = rf.read(buffer, 0, buffer.length)) > -1) {
                    outStream.write(buffer, 0, readed);
                }
                outStream.close();
                rf.close();

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

            }

        }

    } catch (Exception er) {
        log.error("ERROR ", er);
        System.out.println("Error exporting: " + er);
        er.printStackTrace();
    }
}

From source file:org.openmeetings.servlet.outputhandler.CalendarServlet.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {//from   w w w. j  ava 2  s .  com

        if (getUserManagement() == null || getOmTimeZoneDaoImpl() == null || getCfgManagement() == null
                || getSessionManagement() == null || getAppointmentLogic() == null
                || getTimezoneUtil() == null) {
            return;
        }

        String sid = httpServletRequest.getParameter("sid");

        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        if (user_level != null && user_level > 0) {

            String timeZoneIdAsStr = httpServletRequest.getParameter("timeZoneId");

            if (timeZoneIdAsStr == null) {
                log.error("No timeZoneIdAsStr given, using default");
                timeZoneIdAsStr = "";
            }

            TimeZone timezone = getTimezoneUtil()
                    .getTimezoneByOmTimeZoneId(Long.valueOf(timeZoneIdAsStr).longValue());

            String yearStr = httpServletRequest.getParameter("year");
            String monthStr = httpServletRequest.getParameter("month");
            String userStr = httpServletRequest.getParameter("user");
            String contactUser = httpServletRequest.getParameter("contactUser");

            Calendar starttime = GregorianCalendar.getInstance(timezone);
            starttime.set(Calendar.DATE, 1);
            starttime.set(Calendar.MONTH, Integer.parseInt(monthStr) - 1);
            starttime.set(Calendar.MINUTE, 0);
            starttime.set(Calendar.SECOND, 0);
            starttime.set(Calendar.YEAR, Integer.parseInt(yearStr));

            Calendar endtime = GregorianCalendar.getInstance(timezone);
            endtime.set(Calendar.DATE, 1);
            endtime.set(Calendar.MONTH, Integer.parseInt(monthStr));
            endtime.set(Calendar.MINUTE, 0);
            endtime.set(Calendar.SECOND, 0);
            endtime.set(Calendar.YEAR, Integer.parseInt(yearStr));

            Long userToShowId = Long.parseLong(contactUser);
            if (userToShowId == 0) {
                userToShowId = Long.parseLong(userStr);
            }

            List<Appointment> appointements = getAppointmentLogic().getAppointmentByRange(userToShowId,
                    new Date(starttime.getTimeInMillis()), new Date(endtime.getTimeInMillis()));

            Document document = DocumentHelper.createDocument();
            document.setXMLEncoding("UTF-8");
            document.addComment("###############################################\n"
                    + getServletContext().getServletContextName() + " Calendar \n"
                    + "###############################################");

            Element vcalendar = document.addElement("vcalendar");

            Element year = vcalendar.addElement("year" + yearStr);
            Element month = year.addElement("month" + monthStr);

            int previousDay = 0;
            Element day = null;

            for (Appointment appointment : appointements) {

                Calendar appStart = Calendar.getInstance(timezone);
                appStart.setTime(appointment.getAppointmentStarttime());

                int dayAsInt = appStart.get(Calendar.DATE);

                if (previousDay != dayAsInt) {

                    day = month.addElement("day" + dayAsInt);

                    previousDay = dayAsInt;

                }

                if (appStart.get(Calendar.MONTH) + 1 == Integer.parseInt(monthStr)) {

                    Element event = day.addElement("event");

                    Element appointementId = event.addElement("appointementId");
                    appointementId.addAttribute("value", "" + appointment.getAppointmentId());

                    Element isConnectedEvent = event.addElement("isConnectedEvent");
                    isConnectedEvent.addAttribute("value", "" + appointment.getIsConnectedEvent());

                    Element rooms_id = event.addElement("rooms_id");
                    Element roomtype = event.addElement("roomtype");
                    if (appointment.getRoom() != null) {
                        rooms_id.addAttribute("value", "" + appointment.getRoom().getRooms_id());
                        roomtype.addAttribute("value",
                                "" + appointment.getRoom().getRoomtype().getRoomtypes_id());
                    } else {
                        rooms_id.addAttribute("value", "0");
                        roomtype.addAttribute("value", "1");
                    }
                    Element remindType = event.addElement("remindtype");
                    remindType.addAttribute("value",
                            appointment.getRemind() != null ? "" + appointment.getRemind().getTypId() : "0");

                    Element summary = event.addElement("summary");
                    summary.addAttribute("value", appointment.getAppointmentName());

                    Element comment = event.addElement("comment");
                    comment.addAttribute("value", appointment.getAppointmentDescription());

                    Element start = event.addElement("start");

                    start.addAttribute("year", "" + appStart.get(Calendar.YEAR));
                    start.addAttribute("month", "" + (appStart.get(Calendar.MONTH) + 1));
                    start.addAttribute("day", "" + appStart.get(Calendar.DATE));
                    start.addAttribute("hour", "" + appStart.get(Calendar.HOUR_OF_DAY));
                    start.addAttribute("minute", "" + appStart.get(Calendar.MINUTE));

                    Calendar appEnd = Calendar.getInstance(timezone);
                    appEnd.setTime(appointment.getAppointmentEndtime());
                    Element end = event.addElement("end");
                    end.addAttribute("year", "" + appEnd.get(Calendar.YEAR));
                    end.addAttribute("month", "" + (appEnd.get(Calendar.MONTH) + 1));
                    end.addAttribute("day", "" + appEnd.get(Calendar.DATE));
                    end.addAttribute("hour", "" + appEnd.get(Calendar.HOUR_OF_DAY));
                    end.addAttribute("minute", "" + appEnd.get(Calendar.MINUTE));

                    Element category = event.addElement("category");
                    category.addAttribute("value", "" + appointment.getAppointmentCategory().getCategoryId());

                    Element uid = event.addElement("uid");
                    uid.addAttribute("value", "" + appointment.getAppointmentId());

                    Element attendees = event.addElement("attendees");

                    for (MeetingMember meetingMember : appointment.getMeetingMember()) {

                        Element attendee = attendees.addElement("attendee");

                        Element email = attendee.addElement("email");
                        email.addAttribute("value", meetingMember.getEmail());

                        Element userId = attendee.addElement("userId");
                        if (meetingMember.getUserid() != null) {
                            userId.addAttribute("value", "" + meetingMember.getUserid().getUser_id());
                        } else {
                            userId.addAttribute("value", "");
                        }

                        Element memberId = attendee.addElement("memberId");
                        memberId.addAttribute("value", "" + meetingMember.getMeetingMemberId());

                        Element firstname = attendee.addElement("firstname");
                        memberId.addAttribute("value", "" + meetingMember.getMeetingMemberId());
                        firstname.addAttribute("value", meetingMember.getFirstname());

                        Element lastname = attendee.addElement("lastname");
                        lastname.addAttribute("value", meetingMember.getLastname());

                        Element jNameTimeZoneMember = attendee.addElement("jNameTimeZone");
                        if (meetingMember.getOmTimeZone() != null) {
                            jNameTimeZoneMember.addAttribute("value", meetingMember.getOmTimeZone().getJname());
                        } else {
                            jNameTimeZoneMember.addAttribute("value", "");
                        }

                    }

                }

            }

            httpServletResponse.reset();
            httpServletResponse.resetBuffer();
            OutputStream out = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType("text/xml");

            // httpServletResponse.setHeader("Content-Length", ""+
            // rf.length());

            OutputFormat outformat = OutputFormat.createPrettyPrint();
            outformat.setEncoding("UTF-8");
            XMLWriter writer = new XMLWriter(out, outformat);
            writer.write(document);
            writer.flush();

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

        }

    } catch (Exception er) {
        log.error("[Calendar :: service]", er);
    }
}

From source file:org.openmeetings.servlet.outputhandler.DownloadHandler.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

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

        if (getUserManagement() == null || getSessionManagement() == null) {
            return;
        }

        httpServletRequest.setCharacterEncoding("UTF-8");

        log.debug("\nquery = " + httpServletRequest.getQueryString());
        log.debug("\n\nfileName = " + httpServletRequest.getParameter("fileName"));
        log.debug("\n\nparentPath = " + httpServletRequest.getParameter("parentPath"));

        String queryString = httpServletRequest.getQueryString();
        if (queryString == null) {
            queryString = "";
        }

        String sid = httpServletRequest.getParameter("sid");

        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        if (user_level != null && user_level > 0) {
            String room_id = httpServletRequest.getParameter("room_id");
            if (room_id == null) {
                room_id = "default";
            }

            String moduleName = httpServletRequest.getParameter("moduleName");
            if (moduleName == null) {
                moduleName = "nomodule";
            }

            String parentPath = httpServletRequest.getParameter("parentPath");
            if (parentPath == null) {
                parentPath = "nomodule";
            }

            String requestedFile = httpServletRequest.getParameter("fileName");
            if (requestedFile == null) {
                requestedFile = "";
            }

            String fileExplorerItemIdParam = httpServletRequest.getParameter("fileExplorerItemId");
            Long fileExplorerItemId = null;
            if (fileExplorerItemIdParam != null) {
                fileExplorerItemId = Long.parseLong(fileExplorerItemIdParam);
            }

            // make a complete name out of domain(organisation) + roomname
            String roomName = room_id;
            // trim whitespaces cause it is a directory name
            roomName = StringUtils.deleteWhitespace(roomName);

            // Get the current User-Directory

            String current_dir = getServletContext().getRealPath("/");

            String working_dir = "";

            working_dir = current_dir + OpenmeetingsVariables.UPLOAD_DIR + File.separatorChar;

            // Add the Folder for the Room
            if (moduleName.equals("lzRecorderApp")) {
                working_dir = current_dir + OpenmeetingsVariables.STREAMS_DIR + File.separatorChar + "hibernate"
                        + File.separatorChar;
            } else if (moduleName.equals("videoconf1")) {
                if (parentPath.length() != 0) {
                    if (parentPath.equals("/")) {
                        working_dir = working_dir + roomName + File.separatorChar;
                    } else {
                        working_dir = working_dir + roomName + File.separatorChar + parentPath
                                + File.separatorChar;
                    }
                } else {
                    working_dir = current_dir + roomName + File.separatorChar;
                }
            } else if (moduleName.equals("userprofile")) {
                working_dir += "profiles" + File.separatorChar;
                logNonExistentFolder(working_dir);

                working_dir += ScopeApplicationAdapter.profilesPrefix + users_id + File.separatorChar;
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofile")) {
                working_dir += "profiles" + File.separatorChar;
                logNonExistentFolder(working_dir);

                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                if (remoteUser_id == null) {
                    remoteUser_id = "0";
                }

                working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar;
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofilebig")) {
                working_dir += "profiles" + File.separatorChar;
                logNonExistentFolder(working_dir);

                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                if (remoteUser_id == null) {
                    remoteUser_id = "0";
                }

                working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar;
                logNonExistentFolder(working_dir);

                requestedFile = this.getBigProfileUserName(working_dir);

            } else if (moduleName.equals("chat")) {

                working_dir += "profiles" + File.separatorChar;
                logNonExistentFolder(working_dir);

                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                if (remoteUser_id == null) {
                    remoteUser_id = "0";
                }

                working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar;
                logNonExistentFolder(working_dir);

                requestedFile = this.getChatUserName(working_dir);
            } else {
                working_dir = working_dir + roomName + File.separatorChar;
            }

            if (!moduleName.equals("nomodule")) {

                log.debug("requestedFile: " + requestedFile + " current_dir: " + working_dir);

                String full_path = working_dir + requestedFile;

                File f = new File(full_path);

                // If the File does not exist or is not readable show/load a
                // place-holder picture

                if (!f.exists() || !f.canRead()) {
                    if (!f.canRead()) {
                        log.debug("LOG DownloadHandler: The request file is not readable");
                    } else {
                        log.debug(
                                "LOG DownloadHandler: The request file does not exist / has already been deleted");
                    }
                    log.debug("LOG ERROR requestedFile: " + requestedFile);
                    // replace the path with the default picture/document

                    if (requestedFile.endsWith(".jpg")) {
                        log.debug("LOG endsWith d.jpg");

                        log.debug("LOG moduleName: " + moduleName);

                        requestedFile = DownloadHandler.defaultImageName;
                        if (moduleName.equals("remoteuserprofile")) {
                            requestedFile = DownloadHandler.defaultProfileImageName;
                        } else if (moduleName.equals("remoteuserprofilebig")) {
                            requestedFile = DownloadHandler.defaultProfileImageNameBig;
                        } else if (moduleName.equals("userprofile")) {
                            requestedFile = DownloadHandler.defaultProfileImageName;
                        } else if (moduleName.equals("chat")) {
                            requestedFile = DownloadHandler.defaultChatImageName;
                        }
                        // request for an image
                        full_path = current_dir + "default" + File.separatorChar + requestedFile;
                    } else if (requestedFile.endsWith(".swf")) {
                        requestedFile = DownloadHandler.defaultSWFName;
                        // request for a SWFPresentation
                        full_path = current_dir + "default" + File.separatorChar
                                + DownloadHandler.defaultSWFName;
                    } else {
                        // Any document, must be a download request
                        // OR a Moodle Loggedin User
                        requestedFile = DownloadHandler.defaultImageName;
                        full_path = current_dir + "default" + File.separatorChar
                                + DownloadHandler.defaultImageName;
                    }
                }

                log.debug("full_path: " + full_path);

                File f2 = new File(full_path);
                if (!f2.exists() || !f2.canRead()) {
                    if (!f2.canRead()) {
                        log.debug(
                                "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted");
                    } else {
                        log.debug(
                                "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted");
                    }
                    // no file to handle abort processing
                    return;
                }
                // Requested file is outside OM webapp folder
                File curDirFile = new File(current_dir);
                if (!f2.getCanonicalPath().startsWith(curDirFile.getCanonicalPath())) {
                    throw new Exception("Invalid file requested: f2.cp == " + f2.getCanonicalPath()
                            + "; curDir.cp == " + curDirFile.getCanonicalPath());
                }

                // Get file and handle download
                RandomAccessFile rf = new RandomAccessFile(full_path, "r");

                // Default type - Explorer, Chrome and others
                int browserType = 0;

                // Firefox and Opera browsers
                if (httpServletRequest.getHeader("User-Agent") != null) {
                    if ((httpServletRequest.getHeader("User-Agent").contains("Firefox"))
                            || (httpServletRequest.getHeader("User-Agent").contains("Opera"))) {
                        browserType = 1;
                    }
                }

                log.debug("Detected browser type:" + browserType);

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                OutputStream out = httpServletResponse.getOutputStream();

                if (requestedFile.endsWith(".swf")) {
                    // trigger download to SWF => THIS is a workaround for
                    // Flash Player 10, FP 10 does not seem
                    // to accept SWF-Downloads with the Content-Disposition
                    // in the Header
                    httpServletResponse.setContentType("application/x-shockwave-flash");
                    httpServletResponse.setHeader("Content-Length", "" + rf.length());
                } else {
                    httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");

                    String fileNameResult = requestedFile;
                    if (fileExplorerItemId != null && fileExplorerItemId > 0) {
                        FileExplorerItem fileExplorerItem = getFileExplorerItemDaoImpl()
                                .getFileExplorerItemsById(fileExplorerItemId);
                        if (fileExplorerItem != null) {

                            fileNameResult = fileExplorerItem.getFileName().substring(0,
                                    fileExplorerItem.getFileName().length() - 4)
                                    + fileNameResult.substring(fileNameResult.length() - 4,
                                            fileNameResult.length());

                        }
                    }

                    if (browserType == 0) {
                        httpServletResponse.setHeader("Content-Disposition",
                                "attachment; filename=" + java.net.URLEncoder.encode(fileNameResult, "UTF-8"));
                    } else {
                        httpServletResponse.setHeader("Content-Disposition", "attachment; filename*=UTF-8'en'"
                                + java.net.URLEncoder.encode(fileNameResult, "UTF-8"));
                    }

                    httpServletResponse.setHeader("Content-Length", "" + rf.length());
                }

                byte[] buffer = new byte[1024];
                int readed = -1;

                while ((readed = rf.read(buffer, 0, buffer.length)) > -1) {
                    out.write(buffer, 0, readed);
                }

                rf.close();

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

            }
        } else {
            System.out.println("ERROR DownloadHandler: not authorized FileDownload " + (new Date()));
        }

    } catch (Exception er) {
        log.error("Error downloading: ", er);
        // er.printStackTrace();
    }
}

From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java

@SuppressWarnings("unchecked")
@Override/*from  w  w  w  . j a va 2s. c om*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream respOs = resp.getOutputStream();
    WebApp webApp = null;
    try {
        webApp = (WebApp) req.getAttribute(Definitions.ATTRNAME_WEBAPP);
        if (webApp.isClosed()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Service temporarily unavailable</h1></body></html>");
            return;
        }
        executeRequest(webApp, req, resp, respOs);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (webApp != null && webApp.getDevelopmentMode()) {
            resp.setContentType("text/plain; charset=UTF-8");
            e.printStackTrace(new PrintStream(respOs));
        } else if (!resp.isCommitted()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Internal Server Error</h1></body></html>");
        }
    } finally {
        // Delete any registered temporary files:
        try {
            List<File> tempFiles = (List<File>) req.getAttribute(Definitions.ATTRNAME_TEMPFILES);
            if (tempFiles != null) {
                ListIterator<File> li = tempFiles.listIterator();
                while (li.hasNext()) {
                    File file;
                    if ((file = li.next()) != null) {
                        FileUtils.deleteQuietly(file);
                    }
                }
            }
        } catch (Exception se) {
            logger.error("Error deleting registered temporary files", se);
        }

        // Close any closeables:
        try {
            List<Closeable> closeables = (List<Closeable>) req.getAttribute("xslweb-closeables");
            if (closeables != null) {
                ListIterator<Closeable> li = closeables.listIterator(closeables.size());
                while (li.hasPrevious()) {
                    li.previous().close();
                }
            }
        } catch (Exception se) {
            logger.error("Could not close Closeable", se);
        }
    }
}

From source file:org.adventure.CustomCorsFilter.java

/**
 * Handles a CORS request that violates specification.
 *
 * @param request/*w  w  w . ja  v a2s.c o  m*/
 *            The {@link HttpServletRequest} object.
 * @param response
 *            The {@link HttpServletResponse} object.
 * @param filterChain
 *            The {@link FilterChain} object.
 */
private void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) {
    String origin = request.getHeader(CustomCorsFilter.REQUEST_HEADER_ORIGIN);
    String method = request.getMethod();
    String accessControlRequestHeaders = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);

    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    response.resetBuffer();

    if (log.isDebugEnabled()) {
        // Debug so no need for i18n
        StringBuilder message = new StringBuilder("Invalid CORS request; Origin=");
        message.append(origin);
        message.append(";Method=");
        message.append(method);
        if (accessControlRequestHeaders != null) {
            message.append(";Access-Control-Request-Headers=");
            message.append(accessControlRequestHeaders);
        }
        log.debug(message.toString());
    }
}

From source file:org.apache.chemistry.opencmis.server.impl.atompub.CmisAtomPubServlet.java

/**
 * Prints the error HTML page./* w ww .java  2s.  c o m*/
 */
protected void printError(Exception ex, HttpServletRequest request, HttpServletResponse response) {
    int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    String exceptionName = "runtime";

    if (ex instanceof CmisRuntimeException) {
        LOG.error(createLogMessage(ex, request), ex);
        statusCode = getErrorCode((CmisRuntimeException) ex);
    } else if (ex instanceof CmisStorageException) {
        LOG.error(createLogMessage(ex, request), ex);
        statusCode = getErrorCode((CmisStorageException) ex);
        exceptionName = ((CmisStorageException) ex).getExceptionName();
    } else if (ex instanceof CmisBaseException) {
        statusCode = getErrorCode((CmisBaseException) ex);
        exceptionName = ((CmisBaseException) ex).getExceptionName();

        if (statusCode == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            LOG.error(createLogMessage(ex, request), ex);
        }
    } else if (ex instanceof IOException) {
        LOG.warn(createLogMessage(ex, request), ex);
    } else {
        LOG.error(createLogMessage(ex, request), ex);
    }

    if (response.isCommitted()) {
        LOG.warn("Failed to send error message to client. Response is already committed.", ex);
        return;
    }

    String message = ex.getMessage();
    if (!(ex instanceof CmisBaseException)) {
        message = "An error occurred!";
    }

    try {
        response.resetBuffer();
        response.setStatus(statusCode);
        response.setContentType("text/html");
        response.setCharacterEncoding(IOUtils.UTF8);

        PrintWriter pw = response.getWriter();

        pw.print("<html><head><title>Apache Chemistry OpenCMIS - " + exceptionName + " error</title>"
                + "<style><!--H1 {font-size:24px;line-height:normal;font-weight:bold;background-color:#f0f0f0;color:#003366;border-bottom:1px solid #3c78b5;padding:2px;} "
                + "BODY {font-family:Verdana,arial,sans-serif;color:black;font-size:14px;} "
                + "HR {color:#3c78b5;height:1px;}--></style></head><body>");
        pw.print("<h1>HTTP Status " + statusCode + " - <!--exception-->" + exceptionName
                + "<!--/exception--></h1>");
        pw.print("<p><!--message-->");
        StringEscapeUtils.ESCAPE_HTML4.translate(message, pw);
        pw.print("<!--/message--></p>");

        String st = ExceptionHelper.getStacktraceAsString(ex);
        if (st != null) {
            pw.print("<hr noshade='noshade'/><!--stacktrace--><pre>\n<!--key-->stacktrace<!--/key><!--value-->"
                    + st + "<!--/value-->\n</pre><!--/stacktrace--><hr noshade='noshade'/>");
        }

        if (ex instanceof CmisBaseException) {
            Map<String, String> additionalData = ((CmisBaseException) ex).getAdditionalData();
            if (additionalData != null && !additionalData.isEmpty()) {
                pw.print("<hr noshade='noshade'/>Additional data:<br><br>");
                for (Map.Entry<String, String> e : additionalData.entrySet()) {
                    pw.print("<!--key-->");
                    StringEscapeUtils.ESCAPE_HTML4.translate(e.getKey(), pw);
                    pw.print("<!--/key--> = <!--value-->");
                    StringEscapeUtils.ESCAPE_HTML4.translate(e.getValue(), pw);
                    pw.print("<!--/value--><br>");
                }
            }
        }

        pw.print("</body></html>");
    } catch (Exception e) {
        LOG.error(createLogMessage(ex, request), e);
        try {
            response.sendError(statusCode, message);
        } catch (Exception en) {
            // there is nothing else we can do
        }
    }
}

From source file:org.apache.openmeetings.core.servlet.outputhandler.DownloadHandler.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*  w ww.  j a v  a2 s  .  c  o  m*/
        request.setCharacterEncoding(StandardCharsets.UTF_8.name());

        log.debug("\nquery = " + request.getQueryString());
        log.debug("\n\nfileName = " + request.getParameter("fileName"));
        log.debug("\n\nparentPath = " + request.getParameter("parentPath"));

        String queryString = request.getQueryString();
        if (queryString == null) {
            queryString = "";
        }

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

        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        Long users_id = getBean(SessiondataDao.class).check(sid);
        Set<Right> rights = getBean(UserDao.class).getRights(users_id);

        if (rights != null && !rights.isEmpty()) {
            String room_id = request.getParameter("room_id");
            if (room_id == null) {
                room_id = "default";
            }

            String moduleName = request.getParameter("moduleName");
            if (moduleName == null) {
                moduleName = "nomodule";
            }

            String parentPath = request.getParameter("parentPath");
            if (parentPath == null) {
                parentPath = "nomodule";
            }

            String requestedFile = request.getParameter("fileName");
            if (requestedFile == null) {
                requestedFile = "";
            }

            String fileIdParam = request.getParameter("fileId");
            Long fileId = null;
            if (fileIdParam != null) {
                fileId = Long.valueOf(fileIdParam);
            }

            // make a complete name out of domain(group) + roomname
            String roomName = room_id;
            // trim whitespaces cause it is a directory name
            roomName = StringUtils.deleteWhitespace(roomName);

            // Get the current User-Directory

            File working_dir;

            // Add the Folder for the Room
            if (moduleName.equals("lzRecorderApp")) {
                working_dir = OmFileHelper.getStreamsHibernateDir();
            } else if (moduleName.equals("videoconf1")) {
                working_dir = OmFileHelper.getUploadRoomDir(roomName);
                if (parentPath.length() != 0 && !parentPath.equals("/")) {
                    working_dir = new File(working_dir, parentPath);
                }
            } else if (moduleName.equals("userprofile")) {
                working_dir = OmFileHelper.getUploadProfilesUserDir(users_id);
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofile")) {
                String remoteUser_id = request.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofilebig")) {
                String remoteUser_id = request.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);

                requestedFile = getBigProfileUserName(working_dir);
            } else if (moduleName.equals("chat")) {
                String remoteUser_id = request.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);

                requestedFile = getChatUserName(working_dir);
            } else {
                working_dir = OmFileHelper.getUploadRoomDir(roomName);
            }

            if (!moduleName.equals("nomodule")) {
                log.debug("requestedFile: " + requestedFile + " current_dir: " + working_dir);

                File full_path = new File(working_dir, requestedFile);

                // If the File does not exist or is not readable show/load a
                // place-holder picture

                if (!full_path.exists() || !full_path.canRead()) {
                    if (!full_path.canRead()) {
                        log.debug("LOG DownloadHandler: The request file is not readable ");
                    } else {
                        log.debug(
                                "LOG DownloadHandler: The request file does not exist / has already been deleted");
                    }
                    log.debug("LOG ERROR requestedFile: " + requestedFile);
                    // replace the path with the default picture/document

                    if (requestedFile.endsWith(".jpg")) {
                        log.debug("LOG endsWith d.jpg");

                        log.debug("LOG moduleName: " + moduleName);

                        requestedFile = defaultImageName;
                        if (moduleName.equals("remoteuserprofile")) {
                            requestedFile = defaultProfileImageName;
                        } else if (moduleName.equals("remoteuserprofilebig")) {
                            requestedFile = defaultProfileImageNameBig;
                        } else if (moduleName.equals("userprofile")) {
                            requestedFile = defaultProfileImageName;
                        } else if (moduleName.equals("chat")) {
                            requestedFile = defaultChatImageName;
                        }
                    } else if (requestedFile.endsWith(".swf")) {
                        requestedFile = defaultSWFName;
                    } else {
                        requestedFile = defaultImageName;
                    }
                    full_path = new File(OmFileHelper.getDefaultDir(), requestedFile);
                }

                log.debug("full_path: " + full_path);

                if (!full_path.exists() || !full_path.canRead()) {
                    log.debug(
                            "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted");
                    // no file to handle abort processing
                    return;
                }
                // Requested file is outside OM webapp folder
                File curDirFile = OmFileHelper.getOmHome();
                if (!full_path.getCanonicalPath().startsWith(curDirFile.getCanonicalPath())) {
                    throw new Exception("Invalid file requested: f2.cp == " + full_path.getCanonicalPath()
                            + "; curDir.cp == " + curDirFile.getCanonicalPath());
                }

                // Default type - Explorer, Chrome and others
                int browserType = 0;

                // Firefox and Opera browsers
                if (request.getHeader("User-Agent") != null) {
                    if ((request.getHeader("User-Agent").contains("Firefox"))
                            || (request.getHeader("User-Agent").contains("Opera"))) {
                        browserType = 1;
                    }
                }

                log.debug("Detected browser type:" + browserType);

                response.reset();
                response.resetBuffer();
                try (OutputStream out = response.getOutputStream()) {
                    if (requestedFile.endsWith(".swf")) {
                        // trigger download to SWF => THIS is a workaround for
                        // Flash Player 10, FP 10 does not seem
                        // to accept SWF-Downloads with the Content-Disposition
                        // in the Header
                        response.setContentType("application/x-shockwave-flash");
                        response.setHeader("Content-Length", "" + full_path.length());
                    } else {
                        response.setContentType("APPLICATION/OCTET-STREAM");

                        String fileNameResult = requestedFile;
                        if (fileId != null && fileId > 0) {
                            FileExplorerItem fileExplorerItem = getBean(FileExplorerItemDao.class).get(fileId);
                            if (fileExplorerItem != null) {

                                fileNameResult = fileExplorerItem.getName().substring(0,
                                        fileExplorerItem.getName().length() - 4)
                                        + fileNameResult.substring(fileNameResult.length() - 4,
                                                fileNameResult.length());

                            }
                        }

                        if (browserType == 0) {
                            response.setHeader("Content-Disposition", "attachment; filename="
                                    + URLEncoder.encode(fileNameResult, StandardCharsets.UTF_8.name()));
                        } else {
                            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8'en'"
                                    + URLEncoder.encode(fileNameResult, StandardCharsets.UTF_8.name()));
                        }

                        response.setHeader("Content-Length", "" + full_path.length());
                    }

                    OmFileHelper.copyFile(full_path, out);
                    out.flush();
                }
            }
        } else {
            log.error("ERROR DownloadHandler: not authorized FileDownload ");
        }

    } catch (ServerNotInitializedException e) {
        return;
    } catch (Exception er) {
        log.error("Error downloading: ", er);
    }
}