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.commons.fileupload.util;
018
019import java.io.ByteArrayOutputStream;
020import java.io.IOException;
021import java.io.InputStream;
022import java.io.OutputStream;
023
024import org.apache.commons.fileupload.InvalidFileNameException;
025import org.apache.commons.io.IOUtils;
026import org.apache.commons.io.output.NullOutputStream;
027
028/**
029 * Utility class for working with streams.
030 */
031public final class Streams {
032
033    /**
034     * Default buffer size for use in
035     * {@link #copy(InputStream, OutputStream, boolean)}.
036     */
037    public static final int DEFAULT_BUFFER_SIZE = 8192;
038
039    /**
040     * This convenience method allows to read a
041     * {@link org.apache.commons.fileupload.FileItemStream}'s
042     * content into a string. The platform's default character encoding
043     * is used for converting bytes into characters.
044     *
045     * @param inputStream The input stream to read.
046     * @see #asString(InputStream, String)
047     * @return The streams contents, as a string.
048     * @throws IOException An I/O error occurred.
049     */
050    public static String asString(final InputStream inputStream) throws IOException {
051        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
052        copy(inputStream, baos, true);
053        return baos.toString();
054    }
055
056    /**
057     * This convenience method allows to read a
058     * {@link org.apache.commons.fileupload.FileItemStream}'s
059     * content into a string, using the given character encoding.
060     *
061     * @param inputStream The input stream to read.
062     * @param encoding The character encoding, typically "UTF-8".
063     * @see #asString(InputStream)
064     * @return The streams contents, as a string.
065     * @throws IOException An I/O error occurred.
066     */
067    public static String asString(final InputStream inputStream, final String encoding) throws IOException {
068        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
069        copy(inputStream, baos, true);
070        return baos.toString(encoding);
071    }
072
073    /**
074     * Checks, whether the given file name is valid in the sense,
075     * that it doesn't contain any NUL characters. If the file name
076     * is valid, it will be returned without any modifications. Otherwise,
077     * an {@link InvalidFileNameException} is raised.
078     *
079     * @param fileName The file name to check
080     * @return Unmodified file name, if valid.
081     * @throws InvalidFileNameException The file name was found to be invalid.
082     */
083    public static String checkFileName(final String fileName) {
084        if (fileName != null  &&  fileName.indexOf('\u0000') != -1) {
085            // fileName.replace("\u0000", "\\0")
086            final StringBuilder sb = new StringBuilder();
087            for (int i = 0;  i < fileName.length();  i++) {
088                final char c = fileName.charAt(i);
089                switch (c) {
090                    case 0:
091                        sb.append("\\0");
092                        break;
093                    default:
094                        sb.append(c);
095                        break;
096                }
097            }
098            throw new InvalidFileNameException(fileName,
099                    "Invalid file name: " + sb);
100        }
101        return fileName;
102    }
103
104    /**
105     * Copies the contents of the given {@link InputStream}
106     * to the given {@link OutputStream}. Shortcut for
107     * <pre>
108     *   copy(pInputStream, outputStream, new byte[8192]);
109     * </pre>
110     *
111     * @param inputStream The input stream, which is being read.
112     * It is guaranteed, that {@link InputStream#close()} is called
113     * on the stream.
114     * @param outputStream The output stream, to which data should
115     * be written. May be null, in which case the input streams
116     * contents are simply discarded.
117     * @param closeOutputStream True guarantees, that {@link OutputStream#close()}
118     * is called on the stream. False indicates, that only
119     * {@link OutputStream#flush()} should be called finally.
120     *
121     * @return Number of bytes, which have been copied.
122     * @throws IOException An I/O error occurred.
123     */
124    public static long copy(final InputStream inputStream, final OutputStream outputStream,
125                            final boolean closeOutputStream)
126            throws IOException {
127        return copy(inputStream, outputStream, closeOutputStream, new byte[DEFAULT_BUFFER_SIZE]);
128    }
129
130    /**
131     * Copies the contents of the given {@link InputStream}
132     * to the given {@link OutputStream}.
133     *
134     * @param inputStream The input stream, which is being read.
135     *   It is guaranteed, that {@link InputStream#close()} is called
136     *   on the stream.
137     * @param outputStream The output stream, to which data should
138     *   be written. May be null, in which case the input streams
139     *   contents are simply discarded.
140     * @param closeOutputStream True guarantees, that {@link OutputStream#close()}
141     *   is called on the stream. False indicates, that only
142     *   {@link OutputStream#flush()} should be called finally.
143     * @param buffer Temporary buffer, which is to be used for
144     *   copying data.
145     * @return Number of bytes, which have been copied.
146     * @throws IOException An I/O error occurred.
147     */
148    public static long copy(final InputStream inputStream, final OutputStream outputStream, final boolean closeOutputStream, final byte[] buffer)
149            throws IOException {
150        try {
151            return IOUtils.copyLarge(inputStream, outputStream != null ? outputStream : NullOutputStream.INSTANCE, buffer);
152        } finally {
153            IOUtils.closeQuietly(inputStream);
154            if (closeOutputStream) {
155                IOUtils.closeQuietly(outputStream);
156            }
157        }
158    }
159
160    /**
161     * Private constructor, to prevent instantiation.
162     * This class has only static methods.
163     */
164    private Streams() {
165        // Does nothing
166    }
167
168}