001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software GmbH & Co. KG, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.workplace.tools.workplace.rfsfile;
029
030import org.opencms.flex.CmsFlexController;
031import org.opencms.jsp.CmsJspActionElement;
032import org.opencms.main.CmsRuntimeException;
033import org.opencms.main.OpenCms;
034import org.opencms.security.CmsRole;
035import org.opencms.security.CmsRoleViolationException;
036import org.opencms.util.CmsRfsFileViewer;
037import org.opencms.workplace.CmsWidgetDialog;
038
039import java.io.BufferedInputStream;
040import java.io.File;
041import java.io.FileInputStream;
042import java.io.IOException;
043import java.io.InputStream;
044import java.net.SocketException;
045
046import javax.servlet.ServletOutputStream;
047import javax.servlet.http.HttpServletRequest;
048import javax.servlet.http.HttpServletResponse;
049import javax.servlet.jsp.PageContext;
050
051/**
052 * Generates a CSV file for a given list.<p>
053 *
054 * @since 6.0.0
055 */
056public class CmsRfsFileDisposalDialog extends CmsWidgetDialog {
057
058    /** Defines which pages are valid for this dialog. */
059    public static final String[] PAGES = {"page1"};
060
061    /** The file to download. */
062    private File m_downloadFile;
063
064    /**
065     * Public constructor.<p>
066     *
067     * @param jsp an initialized JSP action element
068     */
069    public CmsRfsFileDisposalDialog(CmsJspActionElement jsp) {
070
071        super(jsp);
072    }
073
074    /**
075     * Public constructor with JSP variables.<p>
076     *
077     * @param context the JSP page context
078     * @param req the JSP request
079     * @param res the JSP response
080     */
081    public CmsRfsFileDisposalDialog(PageContext context, HttpServletRequest req, HttpServletResponse res) {
082
083        this(new CmsJspActionElement(context, req, res));
084    }
085
086    /**
087     * @see org.opencms.workplace.tools.accounts.A_CmsUserDataImexportDialog#actionCommit()
088     */
089    @Override
090    public void actionCommit() {
091
092        // empty
093    }
094
095    /**
096     * @see org.opencms.workplace.CmsWidgetDialog#dialogButtonsCustom()
097     */
098    @Override
099    public String dialogButtonsCustom() {
100
101        return dialogButtons(new int[] {BUTTON_CLOSE}, new String[1]);
102    }
103
104    /**
105     * Generates the output.<p>
106     *
107     * @throws IOException if something goes wrong
108     */
109    public void generateOutput() throws IOException {
110
111        HttpServletResponse res = CmsFlexController.getController(getJsp().getRequest()).getTopResponse();
112        res.setContentType("application/octet-stream");
113        res.setHeader(
114            "Content-Disposition",
115            new StringBuffer("attachment; filename=\"").append(getDownloadFile().getName()).append("\"").toString());
116        res.setContentLength((int)getDownloadFile().length());
117
118        // getOutputStream() throws IllegalStateException if the jsp directive buffer="none" is set.
119        ServletOutputStream outStream = res.getOutputStream();
120        InputStream in = new BufferedInputStream(new FileInputStream(getDownloadFile()));
121
122        try {
123            // don't write the last '-1'
124            int bit = in.read();
125            while ((bit) >= 0) {
126                outStream.write(bit);
127                bit = in.read();
128            }
129        } catch (SocketException soe) {
130            // this is the case for ie if cancel in download window is chosen:
131            // "Connection reset by peer: socket write error". But not for firefox -> don't care
132        } finally {
133            if (outStream != null) {
134                try {
135                    outStream.flush();
136                    outStream.close();
137                } catch (SocketException soe) {
138                    // ignore
139                }
140            }
141            in.close();
142        }
143    }
144
145    /**
146     * @see org.opencms.workplace.CmsWorkplace#checkRole()
147     */
148    @Override
149    protected void checkRole() throws CmsRoleViolationException {
150
151        OpenCms.getRoleManager().checkRole(getCms(), CmsRole.WORKPLACE_MANAGER);
152    }
153
154    /**
155     * Creates the dialog HTML for all defined widgets of the named dialog (page).<p>
156     *
157     * This overwrites the method from the super class to create a layout variation for the widgets.<p>
158     *
159     * @param dialog the dialog (page) to get the HTML for
160     * @return the dialog HTML for all defined widgets of the named dialog (page)
161     */
162    @Override
163    protected String createDialogHtml(String dialog) {
164
165        StringBuffer result = new StringBuffer(1024);
166
167        result.append(createWidgetTableStart());
168        // show error header once if there were validation errors
169        result.append(createWidgetErrorHeader());
170
171        if (dialog.equals(PAGES[0])) {
172            // create the widgets for the first dialog page
173            result.append("<script >\n");
174            result.append("function download(){\n");
175            result.append("\twindow.open(\"").append(getJsp().link(getDownloadPath())).append("\", \"rfsfile\");\n");
176            result.append("}\n");
177            result.append("window.setTimeout(\"download()\",500);\n");
178            result.append("</script>\n");
179            result.append(
180                dialogBlockStart(
181                    key(
182                        Messages.GUI_WORLKPLACE_LOGVIEW_DODOWNLOAD_HEADER_1,
183                        new Object[] {getDownloadFile().getName()})));
184            result.append(key(Messages.GUI_WORLKPLACE_LOGVIEW_DODOWNLOAD_MESSAGE_0));
185            result.append(" <a href='javascript:download()'>");
186            result.append(key(Messages.GUI_WORLKPLACE_LOGVIEW_DODOWNLOAD_LINKTXT_0));
187            result.append("</a>.");
188            result.append(dialogBlockEnd());
189        }
190
191        result.append(createWidgetTableEnd());
192        return result.toString();
193    }
194
195    /**
196     * @see org.opencms.workplace.CmsWidgetDialog#defineWidgets()
197     */
198    @Override
199    protected void defineWidgets() {
200
201        // empty
202    }
203
204    /**
205     * Returns the file that will be downloaded upon clicking the download button
206     * generated in this form by <code>{@link #dialogButtonsOkCancel()}</code>.<p>
207     *
208     * @return the file that will be downloaded upon clicking the download button
209     *         generated in this form by <code>{@link #dialogButtonsOkCancel()}</code>
210     *
211     * @throws CmsRuntimeException if access to the chosen file to download fails
212     */
213    protected File getDownloadFile() throws CmsRuntimeException {
214
215        if (m_downloadFile == null) {
216            // no clone needed: we just read here.
217            CmsRfsFileViewer fileView = OpenCms.getWorkplaceManager().getFileViewSettings();
218            m_downloadFile = new File(fileView.getFilePath());
219            try {
220                // 2nd check: it is impossible to set an invalid path to that class.
221                m_downloadFile = m_downloadFile.getCanonicalFile();
222            } catch (IOException ioex) {
223                throw new CmsRuntimeException(Messages.get().container(Messages.ERR_FILE_ACCESS_0), ioex);
224            }
225        }
226        return m_downloadFile;
227    }
228
229    /**
230     * Returns the download path.<p>
231     *
232     * @return the download path
233     */
234    protected String getDownloadPath() {
235
236        return "/system/workplace/admin/workplace/logfileview/downloadTrigger.jsp";
237    }
238
239    /**
240     * @see org.opencms.workplace.CmsWidgetDialog#getPageArray()
241     */
242    @Override
243    protected String[] getPageArray() {
244
245        return PAGES;
246    }
247
248    /**
249     * @see org.opencms.workplace.CmsWorkplace#initMessages()
250     */
251    @Override
252    protected void initMessages() {
253
254        super.initMessages();
255        addMessages(org.opencms.workplace.tools.workplace.rfsfile.Messages.get().getBundleName());
256    }
257
258    /**
259     * @see org.opencms.workplace.CmsWidgetDialog#validateParamaters()
260     */
261    @Override
262    protected void validateParamaters() throws Exception {
263
264        OpenCms.getRoleManager().checkRole(getCms(), CmsRole.WORKPLACE_MANAGER);
265    }
266}