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

📄 basicattachmentprovider.java

📁 jspwiki source code,jspwiki source code
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*     JSPWiki - a JSP-based WikiWiki clone.    Licensed to the Apache Software Foundation (ASF) under one    or more contributor license agreements.  See the NOTICE file    distributed with this work for additional information    regarding copyright ownership.  The ASF licenses this file    to you under the Apache License, Version 2.0 (the    "License"); you may not use this file except in compliance    with the License.  You may obtain a copy of the License at       http://www.apache.org/licenses/LICENSE-2.0    Unless required by applicable law or agreed to in writing,    software distributed under the License is distributed on an    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY    KIND, either express or implied.  See the License for the    specific language governing permissions and limitations    under the License.   */package com.ecyrd.jspwiki.providers;import java.io.InputStream;import java.io.OutputStream;import java.io.IOException;import java.io.FileNotFoundException;import java.io.File;import java.io.FilenameFilter;import java.io.FileOutputStream;import java.io.FileInputStream;import java.util.Collection;import java.util.Properties;import java.util.ArrayList;import java.util.Iterator;import java.util.Date;import java.util.List;import java.util.Collections;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.apache.log4j.Logger;import com.ecyrd.jspwiki.*;import com.ecyrd.jspwiki.attachment.Attachment;/** *  Provides basic, versioning attachments. * *  <PRE> *   Structure is as follows: *      attachment_dir/ *         ThisPage/ *            attachment.doc/ *               attachment.properties *               1.doc *               2.doc *               3.doc *            picture.png/ *               attachment.properties *               1.png *               2.png *         ThatPage/ *            picture.png/ *               attachment.properties *               1.png *              *  </PRE> * *  The names of the directories will be URLencoded. *  <p> *  "attachment.properties" consists of the following items: *  <UL> *   <LI>1.author = author name for version 1 (etc) *  </UL> */public class BasicAttachmentProvider    implements WikiAttachmentProvider{    private WikiEngine         m_engine;    private String             m_storageDir;        /** The property name for where the attachments should be stored.  Value is <tt>{@value}</tt>. */    public static final String PROP_STORAGEDIR = "jspwiki.basicAttachmentProvider.storageDir";        /*     * Disable client cache for files with patterns     * since 2.5.96     */    private Pattern            m_disableCache = null;        /** The property name for specifying which attachments are not cached.  Value is <tt>{@value}</tt>. */    public static final String PROP_DISABLECACHE = "jspwiki.basicAttachmentProvider.disableCache";    /** The name of the property file. */    public static final String PROPERTY_FILE   = "attachment.properties";    /** The default extension for the page attachment directory name. */    public static final String DIR_EXTENSION   = "-att";        /** The default extension for the attachment directory. */    public static final String ATTDIR_EXTENSION = "-dir";        static final Logger log = Logger.getLogger( BasicAttachmentProvider.class );    /**     *  {@inheritDoc}     */    public void initialize( WikiEngine engine, Properties properties )         throws NoRequiredPropertyException,               IOException    {        m_engine = engine;        m_storageDir = WikiEngine.getRequiredProperty( properties, PROP_STORAGEDIR );                String patternString = engine.getWikiProperties().getProperty( PROP_DISABLECACHE );        if ( patternString != null )        {            m_disableCache = Pattern.compile(patternString);        }        //        //  Check if the directory exists - if it doesn't, create it.        //        File f = new File( m_storageDir );        if( !f.exists() )        {            f.mkdirs();        }        //        // Some sanity checks        //        if( !f.exists() )             throw new IOException("Could not find or create attachment storage directory '"+m_storageDir+"'");        if( !f.canWrite() )             throw new IOException("Cannot write to the attachment storage directory '"+m_storageDir+"'");                if( !f.isDirectory() )            throw new IOException("Your attachment storage points to a file, not a directory: '"+m_storageDir+"'");    }    /**     *  Finds storage dir, and if it exists, makes sure that it is valid.     *     *  @param wikipage Page to which this attachment is attached.     */    private File findPageDir( String wikipage )        throws ProviderException    {        wikipage = mangleName( wikipage );        File f = new File( m_storageDir, wikipage+DIR_EXTENSION );        if( f.exists() && !f.isDirectory() )        {            throw new ProviderException("Storage dir '"+f.getAbsolutePath()+"' is not a directory!");        }        return f;    }    private static String mangleName( String wikiname )    {        String res = TextUtil.urlEncodeUTF8( wikiname );        return res;    }    private static String unmangleName( String filename )    {        return TextUtil.urlDecodeUTF8( filename );    }        /**     *  Finds the dir in which the attachment lives.     */    private File findAttachmentDir( Attachment att )        throws ProviderException    {        File f = new File( findPageDir(att.getParentName()),                            mangleName(att.getFileName()+ATTDIR_EXTENSION) );        //        //  Migration code for earlier versions of JSPWiki.        //  Originally, we used plain filename.  Then we realized we need        //  to urlencode it.  Then we realized that we have to use a        //  postfix to make sure illegal file names are never formed.        //        if( !f.exists() )        {            File oldf = new File( findPageDir( att.getParentName() ),                                  mangleName( att.getFileName() ) );            if( oldf.exists() )            {                f = oldf;            }            else            {                oldf = new File( findPageDir( att.getParentName() ),                                 att.getFileName() );                if( oldf.exists() )                {                    f = oldf;                }            }        }        return f;    }    /**     *  Goes through the repository and decides which version is     *  the newest one in that directory.     *     *  @return Latest version number in the repository, or 0, if     *          there is no page in the repository.     */    private int findLatestVersion( Attachment att )        throws ProviderException    {        // File pageDir = findPageDir( att.getName() );        File attDir  = findAttachmentDir( att );        // log.debug("Finding pages in "+attDir.getAbsolutePath());        String[] pages = attDir.list( new AttachmentVersionFilter() );        if( pages == null )        {            return 0; // No such thing found.        }        int version = 0;        for( int i = 0; i < pages.length; i++ )        {            // log.debug("Checking: "+pages[i]);            int cutpoint = pages[i].indexOf( '.' );                String pageNum = ( cutpoint > 0 ) ? pages[i].substring( 0, cutpoint ) : pages[i] ;                try                {                    int res = Integer.parseInt( pageNum );                    if( res > version )                    {                        version = res;                    }                }                catch( NumberFormatException e ) {} // It's okay to skip these.            }        return version;    }    /**     *  Returns the file extension.  For example "test.png" returns "png".     *  <p>     *  If file has no extension, will return "bin"     *       *  @param filename The file name to check     *  @return The extension.  If no extension is found, returns "bin".     */    protected static String getFileExtension( String filename )    {        String fileExt = "bin";        int dot = filename.lastIndexOf('.');        if( dot >= 0 && dot < filename.length()-1 )        {            fileExt = mangleName( filename.substring( dot+1 ) );        }        return fileExt;    }    /**     *  Writes the page properties back to the file system.     *  Note that it WILL overwrite any previous properties.     */    private void putPageProperties( Attachment att, Properties properties )        throws IOException,               ProviderException    {        File attDir = findAttachmentDir( att );        File propertyFile = new File( attDir, PROPERTY_FILE );        OutputStream out = new FileOutputStream( propertyFile );        properties.store( out,                           " JSPWiki page properties for "+                          att.getName()+                          ". DO NOT MODIFY!" );        out.close();    }    /**     *  Reads page properties from the file system.     */    private Properties getPageProperties( Attachment att )        throws IOException,               ProviderException    {        Properties props = new Properties();        File propertyFile = new File( findAttachmentDir(att), PROPERTY_FILE );        if( propertyFile.exists() )        {            InputStream in = new FileInputStream( propertyFile );            props.load(in);            in.close();        }                return props;    }    /**     *  {@inheritDoc}     */    public void putAttachmentData( Attachment att, InputStream data )        throws ProviderException,               IOException    {        OutputStream out = null;        File attDir = findAttachmentDir( att );        if(!attDir.exists())        {            attDir.mkdirs();        }        int latestVersion = findLatestVersion( att );        // System.out.println("Latest version is "+latestVersion);        try        {            int versionNumber = latestVersion+1;            File newfile = new File( attDir, versionNumber+"."+                                     getFileExtension(att.getFileName()) );            log.info("Uploading attachment "+att.getFileName()+" to page "+att.getParentName());            log.info("Saving attachment contents to "+newfile.getAbsolutePath());            out = new FileOutputStream(newfile);            FileUtil.copyContents( data, out );            out.close();            Properties props = getPageProperties( att );            String author = att.getAuthor();            if( author == null )            {                author = "unknown"; // FIXME: Should be localized, but cannot due to missing WikiContext            }            props.setProperty( versionNumber+".author", author );                        String changeNote = (String)att.getAttribute(WikiPage.CHANGENOTE);            if( changeNote != null )            {                props.setProperty( versionNumber+".changenote", changeNote );            }                        putPageProperties( att, props );        }        catch( IOException e )

⌨️ 快捷键说明

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