    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.net.ftp.parser;
    019
    020import java.util.regex.Pattern;
    021
    022import org.apache.commons.net.ftp.Configurable;
    023import org.apache.commons.net.ftp.FTPClientConfig;
    024import org.apache.commons.net.ftp.FTPFileEntryParser;
    025
    026
    027/**
    028 * This is the default implementation of the
    029 * FTPFileEntryParserFactory interface.  This is the
    030 * implementation that will be used by
    031 * org.apache.commons.net.ftp.FTPClient.listFiles()
    032 * if no other implementation has been specified.
    033 *
    034 * @see org.apache.commons.net.ftp.FTPClient#listFiles
    035 * @see org.apache.commons.net.ftp.FTPClient#setParserFactory
    036 */
    037public class DefaultFTPFileEntryParserFactory
    038    implements FTPFileEntryParserFactory
    039{
    040
    041    // Match a plain Java Identifier
    042    private static final String JAVA_IDENTIFIER = "\\p{javaJavaIdentifierStart}(\\p{javaJavaIdentifierPart})*";
    043    // Match a qualified name, e.g. a.b.c.Name - but don't allow the default package as that would allow "VMS"/"UNIX" etc.
    044    private static final String JAVA_QUALIFIED_NAME  = "("+JAVA_IDENTIFIER+"\\.)+"+JAVA_IDENTIFIER;
    045    // Create the pattern, as it will be reused many times
    046    private static final Pattern JAVA_QUALIFIED_NAME_PATTERN = Pattern.compile(JAVA_QUALIFIED_NAME);
    047
    048    /**
    049     * This default implementation of the FTPFileEntryParserFactory
    050     * interface works according to the following logic:
    051     * First it attempts to interpret the supplied key as a fully
    052     * qualified classname (default package is not allowed) of a class implementing the
    053     * FTPFileEntryParser interface.  If that succeeds, a parser
    054     * object of this class is instantiated and is returned;
    055     * otherwise it attempts to interpret the key as an identirier
    056     * commonly used by the FTP SYST command to identify systems.
    057     * <p>
    058     * If <code>key</code> is not recognized as a fully qualified
    059     * classname known to the system, this method will then attempt
    060     * to see whether it <b>contains</b> a string identifying one of
    061     * the known parsers.  This comparison is <b>case-insensitive</b>.
    062     * The intent here is where possible, to select as keys strings
    063     * which are returned by the SYST command on the systems which
    064     * the corresponding parser successfully parses.  This enables
    065     * this factory to be used in the auto-detection system.
    066     *
    067     * @param key    should be a fully qualified classname corresponding to
    068     *               a class implementing the FTPFileEntryParser interface<br>
    069     *               OR<br>
    070     *               a string containing (case-insensitively) one of the
    071     *               following keywords:
    072     *               <ul>
    073     *               <li>{@link FTPClientConfig#SYST_UNIX UNIX}</li>
    074     *               <li>{@link FTPClientConfig#SYST_NT WINDOWS}</li>
    075     *               <li>{@link FTPClientConfig#SYST_OS2 OS/2}</li>
    076     *               <li>{@link FTPClientConfig#SYST_OS400 OS/400}</li>
    077     *               <li>{@link FTPClientConfig#SYST_AS400 AS/400}</li>
    078     *               <li>{@link FTPClientConfig#SYST_VMS VMS}</li>
    079     *               <li>{@link FTPClientConfig#SYST_MVS MVS}</li>
    080     *               <li>{@link FTPClientConfig#SYST_NETWARE NETWARE}</li>
    081     *               <li>{@link FTPClientConfig#SYST_L8 TYPE:L8}</li>
    082     *               </ul>
    083     * @return the FTPFileEntryParser corresponding to the supplied key.
    084     * @throws ParserInitializationException thrown if for any reason the factory cannot resolve
    085     *                   the supplied key into an FTPFileEntryParser.
    086     * @see FTPFileEntryParser
    087     */
    088    @Override
    089    public FTPFileEntryParser createFileEntryParser(final String key)
    090    {
    091        if (key == null) {
    092            throw new ParserInitializationException("Parser key cannot be null");
    093        }
    094        return createFileEntryParser(key, null);
    095    }
    096
    097    // Common method to process both key and config parameters.
    098    private FTPFileEntryParser createFileEntryParser(final String key, final FTPClientConfig config) {
    099        FTPFileEntryParser parser = null;
    100
    101        // Is the key a possible class name?
    102        if (JAVA_QUALIFIED_NAME_PATTERN.matcher(key).matches()) {
    103            try
    104            {
    105                final Class<?> parserClass = Class.forName(key);
    106                try {
    107                    parser = (FTPFileEntryParser) parserClass.newInstance();
    108                } catch (final ClassCastException e) {
    109                    throw new ParserInitializationException(parserClass.getName()
    110                        + " does not implement the interface "
    111                        + "org.apache.commons.net.ftp.FTPFileEntryParser.", e);
    112                } catch (final Exception | ExceptionInInitializerError e) {
    113                    throw new ParserInitializationException("Error initializing parser", e);
    114                }
    115            } catch (final ClassNotFoundException e) {
    116                // OK, assume it is an alias
    117            }
    118        }
    119
    120        if (parser == null) { // Now try for aliases
    121            final String ukey = key.toUpperCase(java.util.Locale.ENGLISH);
    122            if (ukey.indexOf(FTPClientConfig.SYST_UNIX_TRIM_LEADING) >= 0)
    123            {
    124                parser = new UnixFTPEntryParser(config, true);
    125            }
    126            // must check this after SYST_UNIX_TRIM_LEADING as it is a substring of it
    127            else if (ukey.indexOf(FTPClientConfig.SYST_UNIX) >= 0)
    128            {
    129                parser = new UnixFTPEntryParser(config, false);
    130            }
    131            else if (ukey.indexOf(FTPClientConfig.SYST_VMS) >= 0)
    132            {
    133                parser = new VMSVersioningFTPEntryParser(config);
    134            }
    135            else if (ukey.indexOf(FTPClientConfig.SYST_NT) >= 0)
    136            {
    137                parser = createNTFTPEntryParser(config);
    138            }
    139            else if (ukey.indexOf(FTPClientConfig.SYST_OS2) >= 0)
    140            {
    141                parser = new OS2FTPEntryParser(config);
    142            }
    143            else if (ukey.indexOf(FTPClientConfig.SYST_OS400) >= 0 ||
    144                    ukey.indexOf(FTPClientConfig.SYST_AS400) >= 0)
    145            {
    146                parser = createOS400FTPEntryParser(config);
    147            }
    148            else if (ukey.indexOf(FTPClientConfig.SYST_MVS) >= 0)
    149            {
    150                parser = new MVSFTPEntryParser(); // Does not currently support config parameter
    151            }
    152            else if (ukey.indexOf(FTPClientConfig.SYST_NETWARE) >= 0)
    153            {
    154                parser = new NetwareFTPEntryParser(config);
    155            }
    156            else if (ukey.indexOf(FTPClientConfig.SYST_MACOS_PETER) >= 0)
    157            {
    158                parser = new MacOsPeterFTPEntryParser(config);
    159            }
    160            else if (ukey.indexOf(FTPClientConfig.SYST_L8) >= 0)
    161            {
    162                // L8 normally means Unix, but move it to the end for some L8 systems that aren't.
    163                // This check should be last!
    164                parser = new UnixFTPEntryParser(config);
    165            }
    166            else
    167            {
    168                throw new ParserInitializationException("Unknown parser type: " + key);
    169            }
    170        }
    171
    172        if (parser instanceof Configurable) {
    173            ((Configurable)parser).configure(config);
    174        }
    175        return parser;
    176    }
    177
    178    /**
    179     * <p>Implementation extracts a key from the supplied
    180     * {@link  FTPClientConfig FTPClientConfig}
    181     * parameter and creates an object implementing the
    182     * interface FTPFileEntryParser and uses the supplied configuration
    183     * to configure it.
    184     * </p><p>
    185     * Note that this method will generally not be called in scenarios
    186     * that call for autodetection of parser type but rather, for situations
    187     * where the user knows that the server uses a non-default configuration
    188     * and knows what that configuration is.
    189     * </p>
    190     * @param config  A {@link  FTPClientConfig FTPClientConfig}
    191     * used to configure the parser created
    192     *
    193     * @return the @link  FTPFileEntryParser FTPFileEntryParser} so created.
    194     * @throws ParserInitializationException
    195     *                   Thrown on any exception in instantiation
    196     * @throws NullPointerException if {@code config} is {@code null}
    197     * @since 1.4
    198     */
    199    @Override
    200    public FTPFileEntryParser createFileEntryParser(final FTPClientConfig config)
    201    throws ParserInitializationException
    202    {
    203        final String key = config.getServerSystemKey();
    204        return createFileEntryParser(key, config);
    205    }
    206
    207
    208    public FTPFileEntryParser createUnixFTPEntryParser()
    209    {
    210        return new UnixFTPEntryParser();
    211    }
    212
    213    public FTPFileEntryParser createVMSVersioningFTPEntryParser()
    214    {
    215        return new VMSVersioningFTPEntryParser();
    216    }
    217
    218    public FTPFileEntryParser createNetwareFTPEntryParser() {
    219        return new NetwareFTPEntryParser();
    220    }
    221
    222    public FTPFileEntryParser createNTFTPEntryParser()
    223    {
    224        return createNTFTPEntryParser(null);
    225    }
    226
    227    /**
    228     * Creates an NT FTP parser: if the config exists, and the system key equals
    229     * {@link FTPClientConfig#SYST_NT} then a plain {@link NTFTPEntryParser} is used,
    230     * otherwise a composite of {@link NTFTPEntryParser} and {@link UnixFTPEntryParser} is used.
    231     * @param config the config to use, may be {@code null}
    232     * @return the parser
    233     */
    234    private FTPFileEntryParser createNTFTPEntryParser(final FTPClientConfig config)
    235    {
    236        if (config != null && FTPClientConfig.SYST_NT.equals(
    237                config.getServerSystemKey()))
    238        {
    239            return new NTFTPEntryParser(config);
    240        }
    241        // clone the config as it may be changed by the parsers (NET-602)
    242        final FTPClientConfig config2 =  config != null ? new FTPClientConfig(config) : null;
    243        return new CompositeFileEntryParser(new FTPFileEntryParser[]
    244               {
    245                   new NTFTPEntryParser(config),
    246                   new UnixFTPEntryParser(config2,
    247                           config2 != null && FTPClientConfig.SYST_UNIX_TRIM_LEADING.equals(config2.getServerSystemKey()))
    248               });
    249    }
    250
    251     public FTPFileEntryParser createOS2FTPEntryParser()
    252    {
    253        return new OS2FTPEntryParser();
    254    }
    255
    256    public FTPFileEntryParser createOS400FTPEntryParser()
    257    {
    258        return createOS400FTPEntryParser(null);
    259    }
    260
    261    /**
    262     * Creates an OS400 FTP parser: if the config exists, and the system key equals
    263     * {@link FTPClientConfig#SYST_OS400} then a plain {@link OS400FTPEntryParser} is used,
    264     * otherwise a composite of {@link OS400FTPEntryParser} and {@link UnixFTPEntryParser} is used.
    265     * @param config the config to use, may be {@code null}
    266     * @return the parser
    267     */
    268    private FTPFileEntryParser createOS400FTPEntryParser(final FTPClientConfig config)
    269        {
    270        if (config != null &&
    271                FTPClientConfig.SYST_OS400.equals(config.getServerSystemKey()))
    272        {
    273            return new OS400FTPEntryParser(config);
    274        }
    275        // clone the config as it may be changed by the parsers (NET-602)
    276        final FTPClientConfig config2 =  config != null ? new FTPClientConfig(config) : null;
    277        return new CompositeFileEntryParser(new FTPFileEntryParser[]
    278            {
    279                new OS400FTPEntryParser(config),
    280                new UnixFTPEntryParser(config2,
    281                        config2 != null && FTPClientConfig.SYST_UNIX_TRIM_LEADING.equals(config2.getServerSystemKey()))
    282            });
    283    }
    284
    285    public FTPFileEntryParser createMVSEntryParser()
    286    {
    287        return new MVSFTPEntryParser();
    288    }
    289
    290}
    291