package com.pdflib.cookbook.pcos.interchange;

import java.io.IOException;

import com.pdflib.pCOS;
import com.pdflib.pCOSException;
import com.pdflib.cookbook.pcos.pcos_cookbook_example;

/** 
 * Retrieve the document's XMP meta data.
 * <p>
 * Required software: pCOS interface 3 (pCOS 2.x, PDFlib 7.x, TET 2.2,
 * PLOP 3.x)<br>
 * Required data: PDF document
 * 
 * @version  $Id: document_metadata.java,v 1.2 2007/09/19 09:29:33 stm Exp $
 */
public class document_metadata extends pcos_cookbook_example {
    
    /* This is where the data files are. Adjust as necessary. */
    private final static String SEARCH_PATH = "../input";

    private final static String KEY = "/Root/Metadata";

    public void example_code(pCOS p, String filename) throws pCOSException, Exception {
        /* Open the PDF document */
        int doc = p.open_document(filename, "");
        if (doc == -1)
            throw new Exception("Error: " + p.get_errmsg());
        
        System.out.println("File name: " + p.get_string(doc, "filename"));
        
        String objtype = p.get_string(doc, "type:" + KEY);
        
        if (objtype.equals("stream")) {
            byte[] contents = p.get_stream(doc, "", KEY);
            if (contents != null && contents.length > 0) {
                try {
                    System.out.write(contents);
                }
                catch (IOException e) {
                    System.err.println("IOException occurred:");
                    System.err.println(e.getMessage());
                }
            }
            else {
                System.out.println("Not found");
            }
        }
        else {
            System.out.println("Not found");
        }
        
        p.close_document(doc);
    }
    
    public document_metadata(String[] argv, String readable_name,
        String search_path, String full_rcs_file_name, String revision) {
        super(argv, readable_name, search_path, full_rcs_file_name, revision);
    }

    public static void main(String argv[]) {
        document_metadata example = new document_metadata(argv,
            "Document XMP metadata", SEARCH_PATH,
            "$RCSfile: document_metadata.java,v $", "$Revision: 1.2 $");
        example.execute();
    }
}
