summaryrefslogtreecommitdiff
path: root/app/src/main/java/org/apache/commons/net/ftp/FTPListParseEngine.java
blob: 468bf390153b9a226726f0552ebe896e6d225ba0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
 * 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 org.apache.commons.net.ftp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;


/**
 * This class handles the entire process of parsing a listing of
 * file entries from the server.
 * <p>
 * This object defines a two-part parsing mechanism.
 * <p>
 * The first part is comprised of reading the raw input into an internal
 * list of strings.  Every item in this list corresponds to an actual
 * file.  All extraneous matter emitted by the server will have been
 * removed by the end of this phase.  This is accomplished in conjunction
 * with the FTPFileEntryParser associated with this engine, by calling
 * its methods <code>readNextEntry()</code> - which handles the issue of
 * what delimits one entry from another, usually but not always a line
 * feed and <code>preParse()</code> - which handles removal of
 * extraneous matter such as the preliminary lines of a listing, removal
 * of duplicates on versioning systems, etc.
 * <p>
 * The second part is composed of the actual parsing, again in conjunction
 * with the particular parser used by this engine.  This is controlled
 * by an iterator over the internal list of strings.  This may be done
 * either in block mode, by calling the <code>getNext()</code> and
 * <code>getPrevious()</code> methods to provide "paged" output of less
 * than the whole list at one time, or by calling the
 * <code>getFiles()</code> method to return the entire list.
 * <p>
 * Examples:
 * <p>
 * Paged access:
 * <pre>
 *    FTPClient f=FTPClient();
 *    f.connect(server);
 *    f.login(username, password);
 *    FTPListParseEngine engine = f.initiateListParsing(directory);
 *
 *    while (engine.hasNext()) {
 *       FTPFile[] files = engine.getNext(25);  // "page size" you want
 *       //do whatever you want with these files, display them, etc.
 *       //expensive FTPFile objects not created until needed.
 *    }
 * </pre>
 * <p>
 * For unpaged access, simply use FTPClient.listFiles().  That method
 * uses this class transparently.
 * @version $Id: FTPListParseEngine.java 658518 2008-05-21 01:04:30Z sebb $
 */
public class FTPListParseEngine {
    private List<String> entries = new LinkedList<String>();
    private ListIterator<String> _internalIterator = entries.listIterator();

    FTPFileEntryParser parser = null;

    public FTPListParseEngine(FTPFileEntryParser parser) {
        this.parser = parser;
    }

    /**
     * handle the iniitial reading and preparsing of the list returned by
     * the server.  After this method has completed, this object will contain
     * a list of unparsed entries (Strings) each referring to a unique file
     * on the server.
     *
     * @param stream input stream provided by the server socket.
     *
     * @exception IOException
     *                   thrown on any failure to read from the sever.
     */
    public void readServerList(InputStream stream, String encoding)
    throws IOException
    {
        this.entries = new LinkedList<String>();
        readStream(stream, encoding);
        this.parser.preParse(this.entries);
        resetIterator();
    }
    
    /**
     * handle the iniitial reading and preparsing of the list returned by
     * the server.  After this method has completed, this object will contain
     * a list of unparsed entries (Strings) each referring to a unique file
     * on the server.
     *
     * @param stream input stream provided by the server socket.
     *
     * @exception IOException
     *                   thrown on any failure to read from the sever.
     *
     * @deprecated The version of this method which takes an encoding should be used.
    */
    public void readServerList(InputStream stream)
    throws IOException
    {
        readServerList(stream, null);
    }
    


    /**
     * Internal method for reading the input into the <code>entries</code> list.
     * After this method has completed, <code>entries</code> will contain a
     * collection of entries (as defined by
     * <code>FTPFileEntryParser.readNextEntry()</code>), but this may contain
     * various non-entry preliminary lines from the server output, duplicates,
     * and other data that will not be part of the final listing.
     *
     * @param stream The socket stream on which the input will be read.
     * @param encoding The encoding to use.
     *
     * @exception IOException
     *                   thrown on any failure to read the stream
     */
    private void readStream(InputStream stream, String encoding) throws IOException
    {
        BufferedReader reader;
        if (encoding == null)
        {
            reader = new BufferedReader(new InputStreamReader(stream));
        }
        else
        {
            reader = new BufferedReader(new InputStreamReader(stream, encoding));
        }
        
        String line = this.parser.readNextEntry(reader);

        while (line != null)
        {
            this.entries.add(line);
            line = this.parser.readNextEntry(reader);
        }
        reader.close();
    }

    /**
     * Returns an array of at most <code>quantityRequested</code> FTPFile
     * objects starting at this object's internal iterator's current position.
     * If fewer than <code>quantityRequested</code> such
     * elements are available, the returned array will have a length equal
     * to the number of entries at and after after the current position.
     * If no such entries are found, this array will have a length of 0.
     *
     * After this method is called this object's internal iterator is advanced
     * by a number of positions equal to the size of the array returned.
     *
     * @param quantityRequested
     * the maximum number of entries we want to get.
     *
     * @return an array of at most <code>quantityRequested</code> FTPFile
     * objects starting at the current position of this iterator within its
     * list and at least the number of elements which  exist in the list at
     * and after its current position.
     * <p><b> 
     * NOTE:</b> This array may contain null members if any of the 
     * individual file listings failed to parse.  The caller should 
     * check each entry for null before referencing it.
     */
    public FTPFile[] getNext(int quantityRequested) {
        List<FTPFile> tmpResults = new LinkedList<FTPFile>();
        int count = quantityRequested;
        while (count > 0 && this._internalIterator.hasNext()) {
            String entry = this._internalIterator.next();
            FTPFile temp = this.parser.parseFTPEntry(entry);
            tmpResults.add(temp);
            count--;
        }
        return tmpResults.toArray(new FTPFile[0]);

    }

    /**
     * Returns an array of at most <code>quantityRequested</code> FTPFile
     * objects starting at this object's internal iterator's current position,
     * and working back toward the beginning.
     *
     * If fewer than <code>quantityRequested</code> such
     * elements are available, the returned array will have a length equal
     * to the number of entries at and after after the current position.
     * If no such entries are found, this array will have a length of 0.
     *
     * After this method is called this object's internal iterator is moved
     * back by a number of positions equal to the size of the array returned.
     *
     * @param quantityRequested
     * the maximum number of entries we want to get.
     *
     * @return an array of at most <code>quantityRequested</code> FTPFile
     * objects starting at the current position of this iterator within its
     * list and at least the number of elements which  exist in the list at
     * and after its current position.  This array will be in the same order
     * as the underlying list (not reversed).
     * <p><b> 
     * NOTE:</b> This array may contain null members if any of the 
     * individual file listings failed to parse.  The caller should 
     * check each entry for null before referencing it.
     */
    public FTPFile[] getPrevious(int quantityRequested) {
        List<FTPFile> tmpResults = new LinkedList<FTPFile>();
        int count = quantityRequested;
        while (count > 0 && this._internalIterator.hasPrevious()) {
            String entry = this._internalIterator.previous();
            FTPFile temp = this.parser.parseFTPEntry(entry);
            tmpResults.add(0,temp);
            count--;
        }
        return tmpResults.toArray(new FTPFile[0]);
    }

    /**
     * Returns an array of FTPFile objects containing the whole list of
     * files returned by the server as read by this object's parser.
     *
     * @return an array of FTPFile objects containing the whole list of
     *         files returned by the server as read by this object's parser.
     * <p><b> 
     * NOTE:</b> This array may contain null members if any of the 
     * individual file listings failed to parse.  The caller should 
     * check each entry for null before referencing it.
     * @exception IOException
     */
    public FTPFile[] getFiles()
    throws IOException
    {
        List<FTPFile> tmpResults = new LinkedList<FTPFile>();
        Iterator<String> iter = this.entries.iterator();
        while (iter.hasNext()) {
            String entry = iter.next();
            FTPFile temp = this.parser.parseFTPEntry(entry);
            tmpResults.add(temp);
        }
        return tmpResults.toArray(new FTPFile[0]);

    }

    /**
     * convenience method to allow clients to know whether this object's
     * internal iterator's current position is at the end of the list.
     *
     * @return true if internal iterator is not at end of list, false
     * otherwise.
     */
    public boolean hasNext() {
        return _internalIterator.hasNext();
    }

    /**
     * convenience method to allow clients to know whether this object's
     * internal iterator's current position is at the beginning of the list.
     *
     * @return true if internal iterator is not at beginning of list, false
     * otherwise.
     */
    public boolean hasPrevious() {
        return _internalIterator.hasPrevious();
    }

    /**
     * resets this object's internal iterator to the beginning of the list.
     */
    public void resetIterator() {
        this._internalIterator = this.entries.listIterator();
    }
}