⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 attachmentservlet.java

📁 wiki建站资源 java编写的 很好用
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*     JSPWiki - a JSP-based WikiWiki clone.    Copyright (C) 2001-2002 Janne Jalkanen (Janne.Jalkanen@iki.fi)    This program is free software; you can redistribute it and/or modify    it under the terms of the GNU Lesser General Public License as published by    the Free Software Foundation; either version 2.1 of the License, or    (at your option) any later version.    This program is distributed in the hope that it will be useful,    but WITHOUT ANY WARRANTY; without even the implied warranty of    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    GNU Lesser General Public License for more details.    You should have received a copy of the GNU Lesser General Public License    along with this program; if not, write to the Free Software    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */package com.ecyrd.jspwiki.attachment;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;import java.io.*;import java.text.SimpleDateFormat;import java.text.DateFormat;import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;import com.ecyrd.jspwiki.*;import com.ecyrd.jspwiki.util.HttpUtil;import com.ecyrd.jspwiki.auth.UserProfile;import com.ecyrd.jspwiki.auth.AuthorizationManager;import com.ecyrd.jspwiki.providers.ProviderException;import com.ecyrd.jspwiki.dav.WebdavServlet;import com.ecyrd.jspwiki.filters.RedirectException;// multipartrequest.jar imports:import http.utils.multipartrequest.*;/** * This is a simple file upload servlet customized for JSPWiki. It receives  * a mime/multipart POST message, as sent by an Attachment page, stores it * temporarily, figures out what WikiName to use to store it, checks for * previously existing versions. * * <p>This servlet does not worry about authentication; we leave that to the  * container, or a previous servlet that chains to us. * * @author Erik Bunn * @author Janne Jalkanen * * @since 1.9.45. */public class AttachmentServlet    extends WebdavServlet{    private WikiEngine m_engine;    Logger log = Logger.getLogger(this.getClass().getName());    public static final String HDR_VERSION     = "version";    public static final String HDR_NAME        = "page";    /** Default expiry period is 1 day */    protected static final long DEFAULT_EXPIRY = 1 * 24 * 60 * 60 * 1000;     private String m_tmpDir;    /**     *  The maximum size that an attachment can be.     */    private int   m_maxSize = Integer.MAX_VALUE;    //    // Not static as DateFormat objects are not thread safe.    // Used to handle the RFC date format = Sat, 13 Apr 2002 13:23:01 GMT    //    private final DateFormat rfcDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");    /**     * Initializes the servlet from WikiEngine properties.     */    public void init( ServletConfig config )        throws ServletException     {        super.init( config );        m_engine         = WikiEngine.getInstance( config );        Properties props = m_engine.getWikiProperties();        m_tmpDir         = m_engine.getWorkDir()+File.separator+"attach-tmp";         m_maxSize        = TextUtil.getIntegerProperty( props,                                                         AttachmentManager.PROP_MAXSIZE,                                                        Integer.MAX_VALUE );        File f = new File( m_tmpDir );        if( !f.exists() )        {            f.mkdirs();        }        else if( !f.isDirectory() )        {            log.fatal("A file already exists where the temporary dir is supposed to be: "+m_tmpDir+".  Please remove it.");        }        log.debug( "UploadServlet initialized. Using " +                    m_tmpDir + " for temporary storage." );    }/*	public void doPropFind( HttpServletRequest req, HttpServletResponse res )    throws IOException, ServletException    {        DavMethod dm = new PropFindMethod( m_engine );                dm.execute( req, res );	}*/    protected void doOptions( HttpServletRequest req, HttpServletResponse res )    {        res.setHeader( "DAV", "1" ); // We support only Class 1        res.setHeader( "Allow", "GET, PUT, POST, OPTIONS, PROPFIND, PROPPATCH, MOVE, COPY, DELETE");        res.setStatus( HttpServletResponse.SC_OK );    }	    /**     * Serves a GET with two parameters: 'wikiname' specifying the wikiname     * of the attachment, 'version' specifying the version indicator.     */    // FIXME: Messages would need to be localized somehow.    public void doGet( HttpServletRequest  req, HttpServletResponse res )         throws IOException, ServletException     {        String version  = m_engine.safeGetParameter( req, HDR_VERSION );        String nextPage = m_engine.safeGetParameter( req, "nextpage" );        String msg      = "An error occurred. Ouch.";        int    ver      = WikiProvider.LATEST_VERSION;        AttachmentManager mgr = m_engine.getAttachmentManager();        AuthorizationManager authmgr = m_engine.getAuthorizationManager();        UserProfile wup = m_engine.getUserManager().getUserProfile( req );        WikiContext context = m_engine.createContext( req, WikiContext.ATTACH );        String page = context.getPage().getName();        if( page == null )        {            log.info("Invalid attachment name.");            res.sendError( HttpServletResponse.SC_BAD_REQUEST );            return;        }        else        {            OutputStream out = null;            InputStream  in  = null;                        try             {                log.debug("Attempting to download att "+page+", version "+version);                if( version != null )                {                    ver = Integer.parseInt( version );                }                Attachment att = mgr.getAttachmentInfo( page, ver );                if( att != null )                {                    //                    //  Check if the user has permission for this attachment                    //                    if( !authmgr.checkPermission( att, wup, "view" ) )                    {                        log.debug("User does not have permission for this");                        res.sendError( HttpServletResponse.SC_FORBIDDEN );                        return;                    }                                                                     //                    //  Check if the client already has a version of this attachment.                    //                    if( HttpUtil.checkFor304( req, att ) )                    {                        log.debug("Client has latest version already, sending 304...");                        res.sendError( HttpServletResponse.SC_NOT_MODIFIED );                        return;                    }                    String mimetype = getServletConfig().getServletContext().getMimeType( att.getFileName().toLowerCase() );                    if( mimetype == null )                    {                        mimetype = "application/binary";                    }                    res.setContentType( mimetype );                    //                    //  We use 'inline' instead of 'attachment' so that user agents                    //  can try to automatically open the file.                    //                    res.addHeader( "Content-Disposition",                                   "inline; filename=\"" + att.getFileName() + "\";" );                    // long expires = new Date().getTime() + DEFAULT_EXPIRY;                    // res.addDateHeader("Expires",expires);                    res.addDateHeader("Last-Modified",att.getLastModified().getTime());                    // If a size is provided by the provider, report it.                    if( att.getSize() >= 0 )                    {                        // log.info("size:"+att.getSize());                        res.setContentLength( (int)att.getSize() );                    }                    out = res.getOutputStream();                    in  = mgr.getAttachmentStream( att );                    int read = 0;                    byte buffer[] = new byte[8192];                                        while( (read = in.read( buffer )) > -1 )                    {                        out.write( buffer, 0, read );                    }                                        if(log.isDebugEnabled())                    {                        msg = "Attachment "+att.getFileName()+" sent to "+req.getRemoteUser()+" on "+req.getRemoteAddr();                        log.debug( msg );                    }                    if( nextPage != null ) res.sendRedirect( nextPage );                    return;                }                               else                {                    msg = "Attachment '" + page + "', version " + ver +                           " does not exist.";                    log.info( msg );                    res.sendError( HttpServletResponse.SC_NOT_FOUND,                                   msg );                    return;                }                            }            catch( ProviderException pe )            {                msg = "Provider error: "+pe.getMessage();                res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,                               msg );                return;            }            catch( NumberFormatException nfe )            {                msg = "Invalid version number (" + version + ")";                res.sendError( HttpServletResponse.SC_BAD_REQUEST,                               msg );                return;            }            catch( IOException ioe )            {                msg = "Error: " + ioe.getMessage();                res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,                               msg );                return;            }            finally            {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -