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;
019import java.io.BufferedReader;
020import java.io.IOException;
021import java.text.ParseException;
022import java.util.StringTokenizer;
023
024import org.apache.commons.net.ftp.FTPClientConfig;
025import org.apache.commons.net.ftp.FTPFile;
026
027/**
028 * Implementation FTPFileEntryParser and FTPFileListParser for VMS Systems.
029 * This is a sample of VMS LIST output
030 *
031 *  "1-JUN.LIS;1              9/9           2-JUN-1998 07:32:04  [GROUP,OWNER]    (RWED,RWED,RWED,RE)",
032 *  "1-JUN.LIS;2              9/9           2-JUN-1998 07:32:04  [GROUP,OWNER]    (RWED,RWED,RWED,RE)",
033 *  "DATA.DIR;1               1/9           2-JUN-1998 07:32:04  [GROUP,OWNER]    (RWED,RWED,RWED,RE)",
034 * <P><B>
035 * Note: VMSFTPEntryParser can only be instantiated through the
036 * DefaultFTPParserFactory by classname.  It will not be chosen
037 * by the autodetection scheme.
038 * </B>
039 * <P>
040 *
041 * @version $Id: VMSFTPEntryParser.java 1752660 2016-07-14 13:25:39Z sebb $
042 *
043 * @see org.apache.commons.net.ftp.FTPFileEntryParser FTPFileEntryParser (for usage instructions)
044 * @see org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory
045 */
046public class VMSFTPEntryParser extends ConfigurableFTPFileEntryParserImpl
047{
048
049    private static final String DEFAULT_DATE_FORMAT
050        = "d-MMM-yyyy HH:mm:ss"; //9-NOV-2001 12:30:24
051
052    /**
053     * this is the regular expression used by this parser.
054     */
055    private static final String REGEX =
056        "(.*?;[0-9]+)\\s*"                                                  //1  file and version
057        + "(\\d+)/\\d+\\s*"                                                 //2  size/allocated
058        +"(\\S+)\\s+(\\S+)\\s+"                                             //3+4 date and time
059        + "\\[(([0-9$A-Za-z_]+)|([0-9$A-Za-z_]+),([0-9$a-zA-Z_]+))\\]?\\s*" //5(6,7,8) owner
060        + "\\([a-zA-Z]*,([a-zA-Z]*),([a-zA-Z]*),([a-zA-Z]*)\\)";            //9,10,11 Permissions (O,G,W)
061    // TODO - perhaps restrict permissions to [RWED]* ?
062
063
064
065    /**
066     * Constructor for a VMSFTPEntryParser object.
067     *
068     * @throws IllegalArgumentException
069     * Thrown if the regular expression is unparseable.  Should not be seen
070     * under normal conditions.  It it is seen, this is a sign that
071     * <code>REGEX</code> is  not a valid regular expression.
072     */
073    public VMSFTPEntryParser()
074    {
075        this(null);
076    }
077
078    /**
079     * This constructor allows the creation of a VMSFTPEntryParser object with
080     * something other than the default configuration.
081     *
082     * @param config The {@link FTPClientConfig configuration} object used to
083     * configure this parser.
084     * @throws IllegalArgumentException
085     * Thrown if the regular expression is unparseable.  Should not be seen
086     * under normal conditions.  It it is seen, this is a sign that
087     * <code>REGEX</code> is  not a valid regular expression.
088     * @since 1.4
089     */
090    public VMSFTPEntryParser(FTPClientConfig config)
091    {
092        super(REGEX);
093        configure(config);
094    }
095
096    /**
097     * Parses a line of a VMS FTP server file listing and converts it into a
098     * usable format in the form of an <code> FTPFile </code> instance.  If the
099     * file listing line doesn't describe a file, <code> null </code> is
100     * returned, otherwise a <code> FTPFile </code> instance representing the
101     * files in the directory is returned.
102     *
103     * @param entry A line of text from the file listing
104     * @return An FTPFile instance corresponding to the supplied entry
105     */
106    @Override
107    public FTPFile parseFTPEntry(String entry)
108    {
109        //one block in VMS equals 512 bytes
110        long longBlock = 512;
111
112        if (matches(entry))
113        {
114            FTPFile f = new FTPFile();
115            f.setRawListing(entry);
116            String name = group(1);
117            String size = group(2);
118            String datestr = group(3)+" "+group(4);
119            String owner = group(5);
120            String permissions[] = new String[3];
121            permissions[0]= group(9);
122            permissions[1]= group(10);
123            permissions[2]= group(11);
124            try
125            {
126                f.setTimestamp(super.parseTimestamp(datestr));
127            }
128            catch (ParseException e)
129            {
130                 // intentionally do nothing
131            }
132
133
134            String grp;
135            String user;
136            StringTokenizer t = new StringTokenizer(owner, ",");
137            switch (t.countTokens()) {
138                case 1:
139                    grp  = null;
140                    user = t.nextToken();
141                    break;
142                case 2:
143                    grp  = t.nextToken();
144                    user = t.nextToken();
145                    break;
146                default:
147                    grp  = null;
148                    user = null;
149            }
150
151            if (name.lastIndexOf(".DIR") != -1)
152            {
153                f.setType(FTPFile.DIRECTORY_TYPE);
154            }
155            else
156            {
157                f.setType(FTPFile.FILE_TYPE);
158            }
159            //set FTPFile name
160            //Check also for versions to be returned or not
161            if (isVersioning())
162            {
163                f.setName(name);
164            }
165            else
166            {
167                name = name.substring(0, name.lastIndexOf(";"));
168                f.setName(name);
169            }
170            //size is retreived in blocks and needs to be put in bytes
171            //for us humans and added to the FTPFile array
172            long sizeInBytes = Long.parseLong(size) * longBlock;
173            f.setSize(sizeInBytes);
174
175            f.setGroup(grp);
176            f.setUser(user);
177            //set group and owner
178
179            //Set file permission.
180            //VMS has (SYSTEM,OWNER,GROUP,WORLD) users that can contain
181            //R (read) W (write) E (execute) D (delete)
182
183            //iterate for OWNER GROUP WORLD permissions
184            for (int access = 0; access < 3; access++)
185            {
186                String permission = permissions[access];
187
188                f.setPermission(access, FTPFile.READ_PERMISSION, permission.indexOf('R')>=0);
189                f.setPermission(access, FTPFile.WRITE_PERMISSION, permission.indexOf('W')>=0);
190                f.setPermission(access, FTPFile.EXECUTE_PERMISSION, permission.indexOf('E')>=0);
191            }
192
193            return f;
194        }
195        return null;
196    }
197
198
199    /**
200     * Reads the next entry using the supplied BufferedReader object up to
201     * whatever delemits one entry from the next.   This parser cannot use
202     * the default implementation of simply calling BufferedReader.readLine(),
203     * because one entry may span multiple lines.
204     *
205     * @param reader The BufferedReader object from which entries are to be
206     * read.
207     *
208     * @return A string representing the next ftp entry or null if none found.
209     * @throws IOException thrown on any IO Error reading from the reader.
210     */
211    @Override
212    public String readNextEntry(BufferedReader reader) throws IOException
213    {
214        String line = reader.readLine();
215        StringBuilder entry = new StringBuilder();
216        while (line != null)
217        {
218            if (line.startsWith("Directory") || line.startsWith("Total")) {
219                line = reader.readLine();
220                continue;
221            }
222
223            entry.append(line);
224            if (line.trim().endsWith(")"))
225            {
226                break;
227            }
228            line = reader.readLine();
229        }
230        return (entry.length() == 0 ? null : entry.toString());
231    }
232
233    protected boolean isVersioning() {
234        return false;
235    }
236
237    /**
238     * Defines a default configuration to be used when this class is
239     * instantiated without a {@link  FTPClientConfig  FTPClientConfig}
240     * parameter being specified.
241     * @return the default configuration for this parser.
242     */
243    @Override
244    protected FTPClientConfig getDefaultConfiguration() {
245        return new FTPClientConfig(
246                FTPClientConfig.SYST_VMS,
247                DEFAULT_DATE_FORMAT,
248                null);
249    }
250
251    // DEPRECATED METHODS - for API compatibility only - DO NOT USE
252
253    /**
254     * DO NOT USE
255     * @param listStream the stream
256     * @return the array of files
257     * @throws IOException on error
258     * @deprecated (2.2) No other FTPFileEntryParser implementations have this method.
259     */
260    @Deprecated
261    public FTPFile[] parseFileList(java.io.InputStream listStream) throws IOException {
262        org.apache.commons.net.ftp.FTPListParseEngine engine = new org.apache.commons.net.ftp.FTPListParseEngine(this);
263        engine.readServerList(listStream, null);
264        return engine.getFiles();
265    }
266
267}
268
269/* Emacs configuration
270 * Local variables:        **
271 * mode:             java  **
272 * c-basic-offset:   4     **
273 * indent-tabs-mode: nil   **
274 * End:                    **
275 */