/*
 *  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.compress.archivers.ar;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.compress.AbstractTestCase;

public class ArArchiveOutputStreamTest extends AbstractTestCase {

    public void testLongFileNamesCauseExceptionByDefault() {
        ArArchiveOutputStream os = null;
        try {
            os = new ArArchiveOutputStream(new ByteArrayOutputStream());
            ArArchiveEntry ae = new ArArchiveEntry("this_is_a_long_name.txt",
                                                   0);
            os.putArchiveEntry(ae);
            fail("Expected an exception");
        } catch (IOException ex) {
            assertTrue(ex.getMessage().startsWith("filename too long"));
        } finally {
            closeQuietly(os);
        }
    }

    public void testLongFileNamesWorkUsingBSDDialect() throws Exception {
        FileOutputStream fos = null;
        ArArchiveOutputStream os = null;
        File[] df = createTempDirAndFile();
        try {
            fos = new FileOutputStream(df[1]);
            os = new ArArchiveOutputStream(fos);
            os.setLongFileMode(ArArchiveOutputStream.LONGFILE_BSD);
            ArArchiveEntry ae = new ArArchiveEntry("this_is_a_long_name.txt",
                                                   14);
            os.putArchiveEntry(ae);
            os.write(new byte[] {
                    'H', 'e', 'l', 'l', 'o', ',', ' ',
                    'w', 'o', 'r', 'l', 'd', '!', '\n'
                });
            os.closeArchiveEntry();
            os.close();
            os = null;
            fos = null;

            List<String> expected = new ArrayList<String>();
            expected.add("this_is_a_long_name.txt");
            checkArchiveContent(df[1], expected);
        } finally {
            if (os != null) {
                os.close();
            }
            if (fos != null) {
                fos.close();
            }
            rmdir(df[0]);
        }
    }
}