/*
 * Copyright (c) 2002-2017 Oracle and/or its affiliates. All rights reserved.
 */

package javasoft.sqe.tests.api.javax.activation.MailcapCommandMap;

import java.util.*;
import java.io.*;
import javax.activation.*;
import com.sun.javatest.*;
import com.sun.javatest.lib.MultiTest; 

/**
 * This class tests that resource files are loaded as expected. <p>
 * api2test: public String[] getNativeCommands(String) <p>
 *
 * how2test: Create a MailcapCommandMap
 */

public class loadFromConf_Test extends MultiTest {

    private static final String mimeType = "application/x-test";
    private static final String entry1 = mimeType + ";test1";
    private static final String entry2 = mimeType + ";test2";

    public static void main( String argv[] )
    {
        loadFromConf_Test test = new loadFromConf_Test();
        Status s = test.run(argv, new PrintWriter(System.err, true), new PrintWriter(System.out, true));
	s.exit();
    }

    /**
     * We don't expect to be able to write into java.home so
     * create a fake java.home and point the System property
     * to it.
     */
    public void init() throws SetupException
    {
	try {
	    File home = File.createTempFile("javahome", "conf");
	    home.delete();	// delete the temp file
	    home.mkdir();	// reuse the name for a directory
	    home.deleteOnExit();
	    System.setProperty("java.home", home.getPath());
	    File conf = new File(home, "conf");
	    conf.mkdir();
	    conf.deleteOnExit();
	    File mailcap = new File(conf, "mailcap");
	    mailcap.deleteOnExit();
	    PrintWriter pw = new PrintWriter(mailcap);
	    pw.println(entry1);
	    pw.close();

	    // create another javamail.providers file in java.home/lib
	    // that should *not* be loaded
	    File lib = new File(home, "lib");
	    lib.mkdir();
	    lib.deleteOnExit();
	    mailcap = new File(lib, "mailcap");
	    mailcap.deleteOnExit();
	    pw = new PrintWriter(mailcap);
	    pw.println(entry2);
	    pw.close();
	} catch (IOException ioex) {
	    throw new SetupException(ioex.toString());
	}
    }

    public Status loadFromConfTest()
    {
        try {
          // BEGIN UNIT TEST 1:

	     // Get MailcapCommandMap object
	     MailcapCommandMap mc = new MailcapCommandMap();

	     String[] cmds = mc.getNativeCommands(mimeType);

             if (cmds != null && cmds.length == 1 && cmds[0].equals(entry1)) {
		return Status.passed("loadFromConf passed");
             } else {
		return Status.failed("loadFromConf FAILED");
             }
          // END UNIT TEST 1:

        } catch ( Exception e ) {
	    return Status.failed("loadFromConf FAILED with exception " + e);
        }
    }
}
