OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 180 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
185 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
17 ilm 5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils;
15
 
67 ilm 16
import java.io.BufferedWriter;
94 ilm 17
import java.io.ByteArrayOutputStream;
17 ilm 18
import java.io.File;
19
import java.io.IOException;
20
import java.io.InputStream;
21
import java.io.OutputStream;
67 ilm 22
import java.io.OutputStreamWriter;
23
import java.io.Writer;
17 ilm 24
import java.nio.charset.Charset;
156 ilm 25
import java.nio.file.Files;
26
import java.nio.file.StandardCopyOption;
27
import java.util.logging.Level;
17 ilm 28
 
29
public class StreamUtils {
30
 
31
    public static final OutputStream NULL_OS = new OutputStream() {
32
        @Override
33
        public void write(int b) throws IOException {
34
            // ignore
35
        }
36
 
37
        public void write(byte b[], int off, int len) throws IOException {
38
            if (b == null)
39
                throw new NullPointerException();
40
            // ignore
41
        }
42
    };
43
 
177 ilm 44
    public static final File NULL_FILE = new File(System.getProperty("os.name").startsWith("Windows") ? "NUL" : "/dev/null");
45
 
17 ilm 46
    /**
47
     * Verbatim copy an entry from input to output stream.
48
     *
49
     * @param in the source.
50
     * @param out the destination.
51
     * @throws IOException if an error occurs while reading or writing.
180 ilm 52
     * @throws RTInterruptedException if interrupted (can only be checked between
53
     *         {@link InputStream#read(byte[], int, int)} reads).
17 ilm 54
     */
55
    public static void copy(InputStream in, OutputStream out) throws IOException {
156 ilm 56
        // TODO use in.transferTo(out) in Java 9
17 ilm 57
        copy(in, out, 512 * 1024);
58
    }
59
 
60
    public static void copy(InputStream in, OutputStream out, final int bufferSize) throws IOException {
67 ilm 61
        copy(in, out, bufferSize, -1);
62
    }
63
 
64
    public static long copy(InputStream in, OutputStream out, final int bufferSize, final long length) throws IOException {
156 ilm 65
        if (bufferSize < 1)
66
            throw new IllegalArgumentException("Buffer size too small : " + bufferSize);
17 ilm 67
        final byte[] buffer = new byte[bufferSize];
67 ilm 68
        long totalCount = 0;
69
        final boolean copyAll = length < 0;
70
        while (copyAll || totalCount < length) {
71
            final long toRead = copyAll ? buffer.length : Math.min(length - totalCount, buffer.length);
72
            // since buffer.length is an int
156 ilm 73
            assert 0 < toRead && toRead <= Integer.MAX_VALUE;
180 ilm 74
            if (Thread.interrupted())
75
                throw new RTInterruptedException();
67 ilm 76
            final int count = in.read(buffer, 0, (int) toRead);
156 ilm 77
            if (count <= 0) {
78
                // like Files.copy(InputStream, OutputStream), stop if reading 0 bytes
79
                if (count == 0)
80
                    Log.get().log(Level.WARNING, "", new IllegalStateException("read() returned 0 for " + in));
17 ilm 81
                break;
156 ilm 82
            }
67 ilm 83
            totalCount += count;
180 ilm 84
            // if interrupted while blocked in read(), then we don't want to use the data read after
85
            // the interrupt.
86
            if (Thread.interrupted())
87
                throw new RTInterruptedException();
17 ilm 88
            out.write(buffer, 0, count);
89
        }
67 ilm 90
        // < if end of stream
91
        assert copyAll || totalCount <= length;
92
        return totalCount;
17 ilm 93
    }
94
 
95
    public static void copy(InputStream ins, File out) throws IOException {
156 ilm 96
        Files.copy(ins, out.toPath(), StandardCopyOption.REPLACE_EXISTING);
17 ilm 97
    }
98
 
94 ilm 99
    /**
100
     * Read until the end of the stream is reached. NOTE : since this method didn't create the
101
     * stream, it doesn't close it.
102
     *
103
     * @param ins the stream to read from.
104
     * @return the bytes.
105
     * @throws IOException if an error occurs.
106
     */
107
    public static byte[] read(final InputStream ins) throws IOException {
108
        final ByteArrayOutputStream out = new ByteArrayOutputStream(512);
109
        copy(ins, out);
110
        return out.toByteArray();
111
    }
112
 
17 ilm 113
    public static void writeln(final String s, final OutputStream out) throws IOException {
114
        write(s + "\n", out);
115
    }
116
 
117
    public static void write(final String s, final OutputStream out) throws IOException {
67 ilm 118
        write(s, out, StringUtils.UTF8);
17 ilm 119
    }
120
 
121
    public static void write(final String s, final OutputStream out, Charset charset) throws IOException {
122
        out.write(s.getBytes(charset));
123
    }
124
 
67 ilm 125
    /**
126
     * Wrap the output stream into a writer, and write the XML declaration.
127
     *
128
     * @param outs an output stream.
129
     * @return a writer with the same encoding as the XML.
130
     * @throws IOException if an error occurs.
131
     */
132
    public static BufferedWriter createXMLWriter(OutputStream outs) throws IOException {
133
        return new BufferedWriter(createXMLUnbufferedWriter(outs));
134
    }
135
 
136
    public static Writer createXMLUnbufferedWriter(OutputStream outs) throws IOException {
137
        // see http://www.w3.org/TR/REC-xml/#sec-guessing
138
        // don't use UTF-8 BOM as Java does not support it :
139
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
140
        final Writer res = new OutputStreamWriter(outs, StringUtils.UTF8);
141
        res.write("<?xml version='1.0' encoding='UTF-8' ?>\n");
142
        return res;
143
    }
17 ilm 144
}