001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.   
018 */
019package org.apache.wiki.util;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023
024import java.io.BufferedReader;
025import java.io.ByteArrayOutputStream;
026import java.io.File;
027import java.io.FileDescriptor;
028import java.io.FileOutputStream;
029import java.io.IOException;
030import java.io.InputStream;
031import java.io.InputStreamReader;
032import java.io.OutputStream;
033import java.io.OutputStreamWriter;
034import java.io.Reader;
035import java.io.StringReader;
036import java.io.StringWriter;
037import java.io.Writer;
038import java.nio.ByteBuffer;
039import java.nio.CharBuffer;
040import java.nio.charset.CharacterCodingException;
041import java.nio.charset.Charset;
042import java.nio.charset.CharsetDecoder;
043import java.nio.charset.CodingErrorAction;
044import java.nio.charset.StandardCharsets;
045import java.nio.file.Files;
046
047/**
048 *  Generic utilities related to file and stream handling.
049 */
050public final class FileUtil {
051
052    /** Size of the buffer used when copying large chunks of data. */
053    private static final int      BUFFER_SIZE = 8192;
054    private static final Logger   LOG         = LogManager.getLogger(FileUtil.class);
055
056    /**
057     *  Private constructor prevents instantiation.
058     */
059    private FileUtil()
060    {}
061
062    /**
063     *  Makes a new temporary file and writes content into it. The temporary
064     *  file is created using <code>File.createTempFile()</code>, and the usual
065     *  semantics apply.  The files are not deleted automatically in exit.
066     *
067     *  @param content Initial content of the temporary file.
068     *  @param encoding Encoding to use.
069     *  @return The handle to the new temporary file
070     *  @throws IOException If the content creation failed.
071     *  @see java.io.File#createTempFile(String,String,File)
072     */
073    public static File newTmpFile( final String content, final Charset encoding ) throws IOException {
074        final File f = File.createTempFile( "jspwiki", null );
075        try( final Reader in = new StringReader( content );
076            final Writer out = new OutputStreamWriter( Files.newOutputStream( f.toPath() ), encoding ) ) {
077            copyContents( in, out );
078        }
079
080        return f;
081    }
082
083    /**
084     *  Creates a new temporary file using the default encoding of ISO-8859-1 (Latin1).
085     *
086     *  @param content The content to put into the file.
087     *  @throws IOException If writing was unsuccessful.
088     *  @return A handle to the newly created file.
089     *  @see #newTmpFile( String, Charset )
090     *  @see java.io.File#createTempFile(String,String,File)
091     */
092    public static File newTmpFile( final String content ) throws IOException {
093        return newTmpFile( content, StandardCharsets.ISO_8859_1 );
094    }
095
096    /**
097     *  Runs a simple command in given directory. The environment is inherited from the parent process (e.g. the
098     *  one in which this Java VM runs). The output of the command is decoded with the platform's default charset.
099     *
100     *  @return Standard output from the command.
101     *  @param  command The command to run
102     *  @param  directory The working directory to run the command in
103     *  @throws IOException If the command failed
104     *  @throws InterruptedException If the command was halted
105     */
106    public static String runSimpleCommand( final String command, final String directory ) throws IOException, InterruptedException {
107        return runSimpleCommand( command, directory, Charset.defaultCharset() );
108    }
109
110    /**
111     *  Runs a simple command in given directory. The environment is inherited from the parent process (e.g. the
112     *  one in which this Java VM runs).
113     *
114     *  @return Standard output from the command.
115     *  @param  command The command to run
116     *  @param  directory The working directory to run the command in
117     *  @param  charset The charset the output of the command is decoded with
118     *  @throws IOException If the command failed
119     *  @throws InterruptedException If the command was halted
120     *  @since 3.0.1
121     */
122    public static String runSimpleCommand( final String command, final String directory, final Charset charset ) throws IOException, InterruptedException {
123        LOG.info( "Running simple command " + command + " in " + directory );
124        final StringBuilder result = new StringBuilder();
125        final Process process = Runtime.getRuntime().exec( command, null, new File( directory ) );
126
127        try( final BufferedReader stdout = new BufferedReader( new InputStreamReader( process.getInputStream(), charset ) );
128             final BufferedReader stderr = new BufferedReader( new InputStreamReader( process.getErrorStream(), charset ) ) ) {
129            String line;
130
131            while( (line = stdout.readLine()) != null ) {
132                result.append( line ).append( "\n" );
133            }
134
135            final StringBuilder error = new StringBuilder();
136            while( (line = stderr.readLine()) != null ) {
137                error.append( line ).append( "\n" );
138            }
139
140            if( error.length() > 0 ) {
141                LOG.error("Command failed, error stream is: "+error);
142            }
143
144            process.waitFor();
145        } finally {
146            // we must close all by exec(..) opened streams: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
147            process.getInputStream().close();
148        }
149
150        return result.toString();
151    }
152
153
154    /**
155     *  Just copies all characters from <I>in</I> to <I>out</I>.  The copying is performed using a buffer of bytes.
156     *
157     *  @since 1.5.8
158     *  @param in The reader to copy from
159     *  @param out The reader to copy to
160     *  @throws IOException If reading or writing failed.
161     */
162    public static void copyContents( final Reader in, final Writer out ) throws IOException {
163        final char[] buf = new char[BUFFER_SIZE];
164        int bytesRead;
165        while( ( bytesRead = in.read( buf ) ) > 0 ) {
166            out.write( buf, 0, bytesRead );
167        }
168
169        out.flush();
170    }
171
172    /**
173     *  Just copies all bytes from <I>in</I> to <I>out</I>.  The copying is performed using a buffer of bytes.
174     *
175     *  @since 1.9.31
176     *  @param in The inputstream to copy from
177     *  @param out The outputstream to copy to
178     *  @throws IOException In case reading or writing fails.
179     */
180    public static void copyContents( final InputStream in, final OutputStream out ) throws IOException {
181        final byte[] buf = new byte[BUFFER_SIZE];
182        int bytesRead;
183        while( ( bytesRead = in.read( buf ) ) > 0 ) {
184            out.write( buf, 0, bytesRead );
185        }
186
187        out.flush();
188
189        // FileOutputStream.flush is an empty method, so in this case we grab the underlying file descriptor and force from there thw write to disk
190        if( out instanceof FileOutputStream ) {
191            final FileDescriptor fd = ( ( FileOutputStream )out ).getFD();
192            fd.sync();
193        }
194    }
195
196    /**
197     *  Reads in file contents.
198     *  <P>
199     *  This method is smart and falls back to ISO-8859-1 if the input stream does not
200     *  seem to be in the specified encoding.
201     *
202     *  @param input The InputStream to read from.
203     *  @param encoding The encoding to assume at first.
204     *  @return A String, interpreted in the "encoding", or, if it fails, in Latin1.
205     *  @throws IOException If the stream cannot be read or the stream cannot be
206     *          decoded (even) in Latin1
207     */
208    public static String readContents(final InputStream input, final String encoding )
209        throws IOException
210    {
211        final ByteArrayOutputStream out = new ByteArrayOutputStream();
212        FileUtil.copyContents( input, out );
213
214        ByteBuffer     bbuf        = ByteBuffer.wrap( out.toByteArray() );
215
216        final Charset        cset        = Charset.forName( encoding );
217        final CharsetDecoder csetdecoder = cset.newDecoder();
218
219        csetdecoder.onMalformedInput( CodingErrorAction.REPORT );
220        csetdecoder.onUnmappableCharacter( CodingErrorAction.REPORT );
221
222        try
223        {
224            final CharBuffer cbuf = csetdecoder.decode( bbuf );
225
226            return cbuf.toString();
227        }
228        catch( final CharacterCodingException e )
229        {
230            final Charset        latin1    = StandardCharsets.ISO_8859_1;
231            final CharsetDecoder l1decoder = latin1.newDecoder();
232
233            l1decoder.onMalformedInput( CodingErrorAction.REPORT );
234            l1decoder.onUnmappableCharacter( CodingErrorAction.REPORT );
235
236            try
237            {
238                bbuf = ByteBuffer.wrap( out.toByteArray() );
239
240                final CharBuffer cbuf = l1decoder.decode( bbuf );
241
242                return cbuf.toString();
243            }
244            catch( final CharacterCodingException ex )
245            {
246                throw (CharacterCodingException) ex.fillInStackTrace();
247            }
248        }
249    }
250
251    /**
252     *  Returns the full contents of the Reader as a String.
253     *
254     *  @since 1.5.8
255     *  @param in The reader from which the contents shall be read.
256     *  @return String read from the Reader
257     *  @throws IOException If reading fails.
258     */
259    public static String readContents( final Reader in ) throws IOException {
260        try(final Writer out = new StringWriter() ) {
261            copyContents( in, out );
262            return out.toString();
263        }
264    }
265
266    /**
267     *  Returns the class and method name (+a line number) in which the
268     *  Throwable was thrown.
269     *
270     *  @param t A Throwable to analyze.
271     *  @return A human-readable string stating the class and method.  Do not rely
272     *          the format to be anything fixed.
273     */
274    public static String getThrowingMethod(final Throwable t )
275    {
276        final StackTraceElement[] trace = t.getStackTrace();
277        final StringBuilder sb = new StringBuilder();
278
279        if( trace == null || trace.length == 0 )
280        {
281            sb.append( "[Stack trace not available]" );
282        }
283        else
284        {
285            sb.append( trace[0].isNativeMethod() ? "native method" : "" );
286            sb.append( trace[0].getClassName() );
287            sb.append(".");
288            sb.append( trace[0].getMethodName() ).append( "(), line " ).append( trace[0].getLineNumber() );
289        }
290        return sb.toString();
291    }
292}