Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.SimpleDoc;
import javax.print.StreamPrintService;
import javax.print.StreamPrintServiceFactory;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;

public class Main {
    public static void main(String[] args) throws Exception {
        InputStream is = new BufferedInputStream(new FileInputStream("filename.gif"));

        OutputStream fos = new BufferedOutputStream(new FileOutputStream("filename.ps"));

        DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
        StreamPrintServiceFactory[] factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
                DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());

        if (factories.length > 0) {
            StreamPrintService service = factories[0].getPrintService(fos);
            DocPrintJob job = service.createPrintJob();
            Doc doc = new SimpleDoc(is, flavor, null);

            PrintJobWatcher pjDone = new PrintJobWatcher(job);

            job.print(doc, null);

            pjDone.waitForDone();
        }

        is.close();
        fos.close();
    }
}

class PrintJobWatcher {
    boolean done = false;

    PrintJobWatcher(DocPrintJob job) {
        job.addPrintJobListener(new PrintJobAdapter() {
            public void printJobCanceled(PrintJobEvent pje) {
                synchronized (PrintJobWatcher.this) {
                    done = true;
                    PrintJobWatcher.this.notify();
                }
            }

            public void printJobCompleted(PrintJobEvent pje) {
                synchronized (PrintJobWatcher.this) {
                    done = true;
                    PrintJobWatcher.this.notify();
                }
            }

            public void printJobFailed(PrintJobEvent pje) {
                synchronized (PrintJobWatcher.this) {
                    done = true;
                    PrintJobWatcher.this.notify();
                }
            }

            public void printJobNoMoreEvents(PrintJobEvent pje) {
                synchronized (PrintJobWatcher.this) {
                    done = true;
                    PrintJobWatcher.this.notify();
                }
            }
        });
    }

    public synchronized void waitForDone() {
        try {
            while (!done) {
                wait();
            }
        } catch (InterruptedException e) {
        }
    }
}