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 */
017package org.apache.camel.util;
018
019import java.io.Closeable;
020import java.io.File;
021import java.io.FileInputStream;
022import java.io.FileNotFoundException;
023import java.io.IOException;
024import java.io.InputStream;
025import java.io.InputStreamReader;
026import java.io.StringReader;
027import java.nio.CharBuffer;
028import java.nio.channels.Channels;
029import java.nio.channels.ReadableByteChannel;
030import java.nio.charset.Charset;
031import java.nio.charset.CharsetDecoder;
032import java.nio.charset.IllegalCharsetNameException;
033import java.nio.charset.UnsupportedCharsetException;
034import java.util.InputMismatchException;
035import java.util.Iterator;
036import java.util.LinkedHashMap;
037import java.util.Map;
038import java.util.Map.Entry;
039import java.util.NoSuchElementException;
040import java.util.Objects;
041import java.util.regex.Matcher;
042import java.util.regex.Pattern;
043
044import static org.apache.camel.util.BufferCaster.cast;
045
046public final class Scanner implements Iterator<String>, Closeable {
047
048    static {
049        WHITESPACE_PATTERN = Pattern.compile("\\s+");
050        FIND_ANY_PATTERN = Pattern.compile("(?s).*");
051    }
052
053    private static final Map<String, Pattern> CACHE = new LinkedHashMap<String, Pattern>() {
054        @Override
055        protected boolean removeEldestEntry(Entry<String, Pattern> eldest) {
056            return size() >= 7;
057        }
058    };
059
060    private static final Pattern WHITESPACE_PATTERN;
061
062    private static final Pattern FIND_ANY_PATTERN;
063
064    private static final int BUFFER_SIZE = 1024;
065
066    private Readable source;
067    private Pattern delimPattern;
068    private Matcher matcher;
069    private CharBuffer buf;
070    private int position;
071    private boolean inputExhausted;
072    private boolean needInput;
073    private boolean skipped;
074    private int savedPosition = -1;
075    private boolean closed;
076    private IOException lastIOException;
077
078    public Scanner(InputStream source, String charsetName, String pattern) {
079        this(new InputStreamReader(Objects.requireNonNull(source, "source"), toDecoder(charsetName)), cachePattern(pattern));
080    }
081
082    public Scanner(File source, String charsetName, String pattern) throws FileNotFoundException {
083        this(new FileInputStream(Objects.requireNonNull(source, "source")).getChannel(), charsetName, pattern);
084    }
085
086    public Scanner(String source, String pattern) {
087        this(new StringReader(Objects.requireNonNull(source, "source")), cachePattern(pattern));
088    }
089
090    public Scanner(String source, Pattern pattern) {
091        this(new StringReader(Objects.requireNonNull(source, "source")), pattern);
092    }
093
094    public Scanner(ReadableByteChannel source, String charsetName, String pattern) {
095        this(Channels.newReader(Objects.requireNonNull(source, "source"), toDecoder(charsetName), -1), cachePattern(pattern));
096    }
097
098    public Scanner(Readable source, String pattern) {
099        this(Objects.requireNonNull(source, "source"), cachePattern(pattern));
100    }
101
102    private Scanner(Readable source, Pattern pattern) {
103        this.source = source;
104        delimPattern = pattern != null ? pattern : WHITESPACE_PATTERN;
105        buf = CharBuffer.allocate(BUFFER_SIZE);
106        cast(buf).limit(0);
107        matcher = delimPattern.matcher(buf);
108        matcher.useTransparentBounds(true);
109        matcher.useAnchoringBounds(false);
110    }
111
112    private static CharsetDecoder toDecoder(String charsetName) {
113        try {
114            Charset cs = charsetName != null ? Charset.forName(charsetName) : Charset.defaultCharset();
115            return cs.newDecoder();
116        } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
117            throw new IllegalArgumentException(e);
118        }
119    }
120
121    @Override
122    public boolean hasNext() {
123        checkClosed();
124        saveState();
125        while (!inputExhausted) {
126            if (hasTokenInBuffer()) {
127                revertState();
128                return true;
129            }
130            readMore();
131        }
132        boolean result = hasTokenInBuffer();
133        revertState();
134        return result;
135    }
136
137    @Override
138    public String next() {
139        checkClosed();
140        while (true) {
141            String token = getCompleteTokenInBuffer();
142            if (token != null) {
143                skipped = false;
144                return token;
145            }
146            if (needInput) {
147                readMore();
148            } else {
149                throwFor();
150            }
151        }
152    }
153
154    public String getDelim() {
155        return delimPattern.pattern();
156    }
157
158    private void saveState() {
159        savedPosition = position;
160    }
161
162    private void revertState() {
163        position = savedPosition;
164        savedPosition = -1;
165        skipped = false;
166    }
167
168    private void readMore() {
169        if (buf.limit() == buf.capacity()) {
170            expandBuffer();
171        }
172        int p = buf.position();
173        cast(buf).position(buf.limit());
174        cast(buf).limit(buf.capacity());
175        int n;
176        try {
177            n = source.read(buf);
178        } catch (IOException ioe) {
179            lastIOException = ioe;
180            n = -1;
181        }
182        if (n == -1) {
183            inputExhausted = true;
184            needInput = false;
185        } else if (n > 0) {
186            needInput = false;
187        }
188        cast(buf).limit(buf.position());
189        cast(buf).position(p);
190    }
191
192    private void expandBuffer() {
193        int offset = savedPosition == -1 ? position : savedPosition;
194        cast(buf).position(offset);
195        if (offset > 0) {
196            buf.compact();
197            translateSavedIndexes(offset);
198            position -= offset;
199            cast(buf).flip();
200        } else {
201            int newSize = buf.capacity() * 2;
202            CharBuffer newBuf = CharBuffer.allocate(newSize);
203            newBuf.put(buf);
204            cast(newBuf).flip();
205            translateSavedIndexes(offset);
206            position -= offset;
207            buf = newBuf;
208            matcher.reset(buf);
209        }
210    }
211
212    private void translateSavedIndexes(int offset) {
213        if (savedPosition != -1) {
214            savedPosition -= offset;
215        }
216    }
217
218    private void throwFor() {
219        skipped = false;
220        if (inputExhausted && position == buf.limit()) {
221            throw new NoSuchElementException();
222        } else {
223            throw new InputMismatchException();
224        }
225    }
226
227    private boolean hasTokenInBuffer() {
228        matcher.usePattern(delimPattern);
229        matcher.region(position, buf.limit());
230        if (matcher.lookingAt()) {
231            position = matcher.end();
232        }
233        return position != buf.limit();
234    }
235
236    private String getCompleteTokenInBuffer() {
237        matcher.usePattern(delimPattern);
238        if (!skipped) {
239            matcher.region(position, buf.limit());
240            if (matcher.lookingAt()) {
241                if (matcher.hitEnd() && !inputExhausted) {
242                    needInput = true;
243                    return null;
244                }
245                skipped = true;
246                position = matcher.end();
247            }
248        }
249        if (position == buf.limit()) {
250            if (inputExhausted) {
251                return null;
252            }
253            needInput = true;
254            return null;
255        }
256        matcher.region(position, buf.limit());
257        boolean foundNextDelim = matcher.find();
258        if (foundNextDelim && (matcher.end() == position)) {
259            foundNextDelim = matcher.find();
260        }
261        if (foundNextDelim) {
262            if (matcher.requireEnd() && !inputExhausted) {
263                needInput = true;
264                return null;
265            }
266            int tokenEnd = matcher.start();
267            matcher.usePattern(FIND_ANY_PATTERN);
268            matcher.region(position, tokenEnd);
269            if (matcher.matches()) {
270                String s = matcher.group();
271                position = matcher.end();
272                return s;
273            } else {
274                return null;
275            }
276        }
277        if (inputExhausted) {
278            matcher.usePattern(FIND_ANY_PATTERN);
279            matcher.region(position, buf.limit());
280            if (matcher.matches()) {
281                String s = matcher.group();
282                position = matcher.end();
283                return s;
284            }
285            return null;
286        }
287        needInput = true;
288        return null;
289    }
290
291    private void checkClosed() {
292        if (closed) {
293            throw new IllegalStateException();
294        }
295    }
296
297    @Override
298    public void close() throws IOException {
299        if (!closed) {
300            closed = true;
301            if (source instanceof Closeable) {
302                try {
303                    ((Closeable) source).close();
304                } catch (IOException e) {
305                    lastIOException = e;
306                }
307            }
308        }
309        if (lastIOException != null) {
310            throw lastIOException;
311        }
312    }
313
314    private static Pattern cachePattern(String pattern) {
315        if (pattern == null) {
316            return null;
317        }
318        synchronized (CACHE) {
319            return CACHE.computeIfAbsent(pattern, Pattern::compile);
320        }
321    }
322
323}